ngram
listlengths
0
67.8k
[ "type:ignore # Copy generic argument (SI) if not set explicitly # This makes", "ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr()", "database. This is only needed to check if the domain model and database", "= uuid4() # Make sure product block stuff is already set if new", "makes sure we always have a specific instance.. \"\"\" if not cls.__base_type__: cls", "Unless required by applicable law or agreed to in writing, software # distributed", "Match domain attribute from relation (not wanted when loading product blocks directly related", "of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore #", "= [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union", "defined on the base class and need not to be defined on the", "product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and", "domain models. Contains all common Product block/Subscription instance code \"\"\" class Config: validate_assignment", "that. Args: db_instances: list of database models to load from status: SubscriptionLifecycle of", "else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls, other:", "class should have been called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with", "match a superclass to an instance when loading for klass in cls.__mro__: if", "import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime", "__init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI)", "return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) ->", "and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and status", "@classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create", "= {} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING:", "return model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable]", "to create product block instances. This metaclass is used to make sure the", "This needs to be an instance var because its part of the API", "SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]],", "SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain model attribute", "instances for it. This function does that. Args: db_instances: list of database models", "Optional[datetime] = None # pragma: no mutate end_date: Optional[datetime] = None # pragma:", "use for constructor \"\"\" instance_values_dict: State = {} list_field_names = set() # Set", "relations to those if not match_domain_attr: return True attr_names = { relation.domain_model_attr for", "product block metadata. This metaclass should not be used directly in the class", "an existing subscription. We also create all subscription instances for it. This function", "can find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID", "UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate", "sure we have a valid subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get(", "{specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of", "for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id)", "This makes sure we always have a speficic instance. \"\"\" if not cls.__base_type__:", "status if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if", "super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI) if not set explicitly #", "{} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore", "S: \"\"\"Create new domain model from instance while changing the status. This makes", "get_origin from sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable,", "= TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for domain", "ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return", "-> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model. When a", "ignore ) model._db_model = subscription_instance return model except ValidationError: logger.exception( \"Subscription is not", "type: ignore **sub_instances, # type: ignore ) model._db_model = subscription_instance return model except", "model = cls(**data) model._db_model = other._db_model return model @classmethod def from_db( cls: Type[B],", "Args: subscription_id: The subscription id status: SubscriptionLifecycle of subscription to check if models", "for fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db", "the product block model types. This strips any List[..] or Optional[...] types. \"\"\"", "current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values). Returns:", "use an already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id", "= cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: #", "= default_value return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr:", "= BlockInactive() # doctest:+SKIP Create a new instance based on a dict in", "id needed if this is a new model Returns: List of saved instances", "if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value", "is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has", "def _fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot create instance of abstract", "sure we refresh the object and not use an already mapped object db.session.refresh(sub)", "subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id,", "cls.__base_type__: # Import here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls", "ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def", "import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import", "for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists are handled OK", "= field_type assert ( # noqa: S101 product_block_model is not None ), \"Product", "str]: \"\"\"Load non product block fields (instance values). Args: instance_values: List of instance", "to the new model \"\"\" if skip_keys is None: skip_keys = [] instances:", "pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str]", "status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self,", "List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values). Returns: List of database instances", "= cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status,", "= [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models", "saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type)", "fields when a subscription is active. To support this a lifecycle specific product", "siv in the instance and act accordingly: only lists and scalar values supported", "class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of product blocks.\"\"\" def __init_subclass__(cls,", "import version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set,", ") product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif", "for field_type in get_args(product_block_field_type) ), ) ) ) product_block_model = None if instance", "= issubclass(type, ConstrainedList) except Exception: # Strip generic arguments, it still might be", "cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new", "{} if diff: missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id( cls: Type[S],", "all other states. `product_type` must be defined on the base class and need", "missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name] = diff return missing_data @classmethod", "nowtz() model = cls(**data) model._db_model = other._db_model return model @classmethod def from_subscription(cls: Type[S],", "sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id without committing", "sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status = self.status.value", "subscription_id) else: data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type)", "description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", ").get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status =", "generic argument (SI) if not set explicitly # This makes a lot of", "normal constructor because that assumes you pass in all required values. That is", ") else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The", "\"\"\"Return all the product block model types. This strips any List[..] or Optional[...]", "instances and stores the domain model attribute in the hierarchy relationship. Args: subscription_instance_mapping:", "\"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag", "register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type,", "a valid subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if", "for it. This function does that. Args: skip_keys: list of fields on the", "== SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model = other._db_model return model", "assert subscription_instance_id # noqa: S101 assert subscription_instance # noqa: S101 if not status:", "a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None", "= {pb.name for pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values()", "database. This function is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP", "is set. return not attr_names or field_name in attr_names return domain_filter for product_block_field_name,", "OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values: # check", "to add to the session if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id", "{status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label", "{status}\") fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status,", "def db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma: no mutate", "None elif not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription instance is", "# pragma: no mutate start_date: Optional[datetime] = None # pragma: no mutate end_date:", "no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of", "only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), )", "instance_values: # check the type of the siv in the instance and act", "= self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product", "if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type:", "validation. Different stages of a subscription lifecycle could require different product block definition.", "SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance based on a dict in", "missing_data_children: Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore", "to remove instances_set = {instance.subscription_instance_id for instance in sub.instances} for instance_id in instances_set:", "in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def", "db # So now we do it just before we instantiate the instance", "(SI) if not set explicitly # This makes a lot of assuptions about", "self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id without committing transaction old_instances_dict", "in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description: str tag: str", "Set[str] name: Optional[str] product_block_id: UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] =", "pass in all required values. That is cumbersome since that means creating a", "one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has minimum, return that minimum else", "an instance when loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__", "enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations", "When a new domain model is created that is not loaded from an", "values). Args: instance_values: List of instance values from database Returns: Dict of fields", "pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing", "= None if instance is None: raise ValueError(\"Required subscription instance is missing in", "status)): raise ValueError(f\"{cls} is not valid for status {status}\") return super().__new__(cls) def __init_subclass__(", "orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check", ") from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State,", "get_annotations annotations = get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try:", "we instantiate the instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one()", "cumbersome since that means creating a tree of product blocks. This is similar", "sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id:", "= {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try:", "\"\"\" Save the domain model attribute to the database. This function iterates through", "= {} # pragma: no mutate def _fix_pb_data(self) -> None: if not self.name:", "pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] =", "but that runs outside the app context so we cant access the db", "# a list field of ProductBlockModels without limits gets an empty list default_value", "set name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__(", "SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) #", "= children_relations def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable],", "This is a superclass we can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name", "if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only be one in the", "instance. \"\"\" if not cls.__base_type__: # Import here to prevent cyclic imports from", "which would be done during testing... \"\"\" if not cls.name: # This is", "UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription", "attribute. Args: instance: child instance Returns: Boolean of match. \"\"\" # We don't", "list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), ) )", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "to save all child subscription instances for it. Args: subscription_id: The subscription id", "if relation.domain_model_attr } # We can assume true is no domain_model_attr is set.", "from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin", "filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and", "@classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str,", "or field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func =", "name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: #", "str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def", "also load all subscription instances for it. This function does that. Args: db_instances:", "no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) ->", "field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None ) ->", "start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs}", "if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations =", "import groupby, zip_longest from operator import attrgetter from sys import version_info from typing", "= 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws exception and", "ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] #", "{instance.subscription_instance_id for instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's", "# Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance", "product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here", "return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create", "a list of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_", "is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in", "k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db,", "doctest:+SKIP Create a new instance based on a dict in the state: >>>", "# doctest:+SKIP ... block: ProductBlockModel This example defines a subscription model with two", "field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item in getattr(other, field_name):", "# pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]]", "get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T = TypeVar(\"T\") # pragma:", "specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" )", "cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model = db_model return model @classmethod", "saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot create instance of abstract class.", "UUID) -> Dict: data = other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type):", "product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for", "product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ... str_field: Optional[str] = None >>>", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "B: \"\"\"Create new domain model from instance while changing the status. This makes", "value=str(val)) ) else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value)", "Block unsafe status changes on domain models that have Subscription instances with parent", "sub.customer_id = self.customer_id sub.description = self.description sub.status = self.status.value sub.insync = self.insync sub.start_date", "Ensure that empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name)", "if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id #", "cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync,", "def __init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs:", "in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif", "if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized", "zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type,", "not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data", "# doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from", "else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str,", "= SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model", "the object and not use an already mapped object db.session.refresh(sub) self._db_model = sub", "Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a product block based on a", "do it just before we instantiate the instance if not hasattr(self, \"product_block_id\"): product_block", "= TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no", "specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status", "_is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T = TypeVar(\"T\") # pragma: no mutate", "specific lifecycle version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name]", "= SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert", "product subscription models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP", "That is cumbersome since that means creating a tree of product blocks. This", ") missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model", "throws exception and there is no good way to test for this try:", "subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id:", "match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type()", "ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type,", ") and product_block_models is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field]", "parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class", "__init_subclass__ but that runs outside the app context so we cant access the", "block metadata. This metaclass should not be used directly in the class definition.", "} missing_data = {} if diff: missing_data[product_db.name] = diff return missing_data @classmethod def", "= cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription,", "for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for the", "a new empty subscription.\"\"\" # Caller wants a new instance and provided a", "is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types: if f_type.name == value.name: field_type", "product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple):", "= product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def __call__(self, *args: Any, **kwargs:", "makes sure we always have a speficic instance. \"\"\" if not cls.__base_type__: #", "**instances, # type: ignore ) model._db_model = subscription return model except ValidationError: logger.exception(", "= db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load", "to return required fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block)", "parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of Subscription with", "context so we cant access the db # So now we do it", "access the db # So now we do it just before we instantiate", "product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There", "status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and", "diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db,", "missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model),", "lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base:", "instances values to save \"\"\" resource_types = {rt.resource_type: rt for rt in product_block.resource_types}", "class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example defines a subscription", "# pragma: no mutate def _fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot", "always necessary. However when it is set, it is necessary to filter through", "fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False)", "Dict[str, str]: \"\"\"Load non product block fields (instance values). Args: instance_values: List of", "f\"The lifecycle status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on", ") else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value)", "instance based on a dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state) #", "Union types always cross subscription boundaries.\" ) else: product_block_model = product_block_field_type # Scalar", "= TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma:", "a subscription lifecycle could require different product block definition. Mainly to support mandatory", "a mapping of the domain model attribute a underlying instances Returns: None \"\"\"", "@classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences between the", "no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base", "class definition. Instead a new product block model should inherit from ProductBlockModel which", "current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) )", "we also load all subscription instances for it. This function does that. Args:", "List[..] or Optional[...] types. \"\"\" result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items():", "is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id:", "don't have parent relations to those if not match_domain_attr: return True attr_names =", "db. # However newly created SubscriptionInstances might not have the correct order for", "and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r},", "to return required fields of a new empty subscription.\"\"\" # Caller wants a", "), \"Product block model has not been resolved. Unable to continue\" instances[product_block_field_name] =", "= SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to prevent cyclic imports from", ") product_block_model = None if instance is None: raise ValueError(\"Required subscription instance is", "not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__ is", "Tuple, Type, TypeVar, Union from uuid import UUID, uuid4 import structlog from more_itertools", "= field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle", "the db. # However newly created SubscriptionInstances might not have the correct order", "selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model # Make sure we refresh", "is already set if new is the first usage of this class cls._fix_pb_data()", "if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model", "None # type:ignore cls.__names__ = set() # For everything except abstract classes if", ").get(self.subscription_id) if not sub: sub = self._db_model # Make sure we refresh the", "operator import attrgetter from sys import version_info from typing import TYPE_CHECKING, Any, Callable,", "if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has minimum,", "product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else:", "Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str]", "elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\")", "lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This example defines a product_block with", "f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return", "this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model =", "end_date: Optional[datetime] = None # pragma: no mutate note: Optional[str] = None #", "when calling `.new().` We are unable to detect which type to intialise and", "None, ) -> S: \"\"\"Use product_id (and customer_id) to return required fields of", "we just stop saving and return it so only its relation is saved", "if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, )", "self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in", "and overriding its fields. All product blocks are related to a database ProductBlockTable", "creating dummy instances. Returns: A dict with instances to pass to the new", "from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls,", "have a specific instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) #", "actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert", "while changing the status. This makes sure we always have a specific instance..", "missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else", "# Make sure product block stuff is already set if new is the", "newly created SubscriptionInstances might not have the correct order for field_name in list_field_names:", "missing_data[cls.name] = diff return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any)", "arguments, it still might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return", "end_date: Optional[datetime] = None, note: Optional[str] = None, ) -> S: \"\"\"Use product_id", "wanted when loading product blocks directly related to subscriptions) Returns: A dict with", "values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists are handled", "subscription instance from the database. This function is similar to `from_subscription()` >>> subscription_instance_id", "database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances):", "the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from", "cant access the db # So now we do it just before we", "= SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save(", "fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model =", "a subscription. Not all subscriptions have a domain model attribute that is set", "model._db_model = subscription return model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status:", "{rt.resource_type for rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model -", "it is not always necessary. However when it is set, it is necessary", "fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db,", "So now we do it just before we instantiate the instance if not", "issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for the field:", "return result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and store a list", "db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property", "{fi.name for fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model -", "set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable", "product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db =", "field_name in resource_types ), f\"Domain model {self.__class__} does not match the ProductBlockTable {product_block.name},", "None: \"\"\"Make and store a list of resource_type fields and product block fields.\"\"\"", "typing types is_product_block_field = False # We only want fields that are on", "subclass on typing.List throws exception and there is no good way to test", "= current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values", "not use this file except in compliance with the License. # You may", "product_block_model = product_block_field_type # Scalar field of a ProductBlockModel expects 1 instance default_value", "and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type)", "isinstance(first(product_blocks_types_in_model), tuple): # There may only be one in the type if it", "the generic product block with keyword argument 'lifecycle' and overriding its fields. All", "instance. Args: status: current SubscriptionLifecycle to check if all constraints match subscription_id: Optional", "no mutate def _fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot create instance", "set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db", "cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model class\", # pragma:", "\"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id:", "not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable,", "not suitable for the lifecycle status ({lifecycle_status}) of this model\" ) else: specialized_type", "Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys:", "models match Returns: A list with instances which are saved and a dict", "insync: bool = False # pragma: no mutate start_date: Optional[datetime] = None #", "instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model SI", "cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, #", "annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel)", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "this instance. Args: status: current SubscriptionLifecycle to check if all constraints match subscription_id:", "= False # pragma: no mutate start_date: Optional[datetime] = None # pragma: no", "data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for f_type", "missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks", "db.session.flush() # Everything is ok, make sure we are of the right class", "valid subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance:", "of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type):", "we can match a superclass to an instance when loading for klass in", "f\"Domain model {self.__class__} does not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type", "to check if models match Returns: A list with instances which are saved", "by subclassing the generic product block with keyword argument 'lifecycle' and overriding its", "get_args(product_block_field_type) ), ) ) ) product_block_model = None if instance is None: raise", "return required fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types),", "from pydantic import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main import", "SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self,", "example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database.: >>>", "[] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models =", "data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model = other._db_model return model", "agreed to in writing, software # distributed under the License is distributed on", "instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is a \"foreign\" instance we just", "= cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances,", "to create constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None:", "in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls):", "status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to the", "instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls( product=product,", "model._db_model = subscription return model except ValidationError: logger.exception( \"Subscription is not correct in", "to an instance when loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name)", "= resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\",", "correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable, current_values:", "True # pragma: no mutate validate_all = True # pragma: no mutate arbitrary_types_allowed", "f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id,", "arbitrary_types_allowed = True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma:", "{product_block_field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this model\" )", "= subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance # noqa: S101 if", "# Set default values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty", "in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k,", "_is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is a constained list type. Example:", "sure product block stuff is already set if new is the first usage", "that means creating a tree of product blocks. This is similar to `from_product_id()`", "is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance", "dataclass.\"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all = True", "if not match_domain_attr: return True attr_names = { relation.domain_model_attr for relation in instance.parent_relations", "{type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub:", "product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model =", "Any]: \"\"\"Return any differences between the attrs defined on the domain model and", "rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model", "This makes a lot of assuptions about the internals of `typing` if \"__orig_bases__\"", "= self._db_model # Make sure we refresh the object and not use an", "is created that is not loaded from an existing subscription. We also create", "= getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value,", "S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") #", "in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls)", "instance_values: List of instance values from database Returns: Dict of fields to use", "**kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments", "retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel", "... int_field: int ... str_field: str This example defines a product_block with two", "during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks}", "in the database as a dataclass.\"\"\" class Config: validate_assignment = True # pragma:", "and database models match which would be done during testing... \"\"\" if not", "field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel)", "**kwargs: Any) -> \"SubscriptionModel\": # status can be none if created during change_lifecycle", "boundaries.\" ) else: product_block_model = product_block_field_type # Scalar field of a ProductBlockModel expects", "status, subscription_id) return data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) ->", "[] # Set the domain_model_attrs in the database for domain_model_attr, instances in subscription_instance_mapping.items():", "add to the session if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id =", "this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip generic arguments, it", "= first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in", ") children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle,", "Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff", "= [] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else:", "pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of product", "`.new().` We are unable to detect which type to intialise and Union types", "from uuid import UUID, uuid4 import structlog from more_itertools import first, flatten, one,", "None, note: Optional[str] = None, ) -> S: \"\"\"Use product_id (and customer_id) to", "parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *,", "to filter through all relations in a subscription. Not all subscriptions have a", "lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for status {status}\") return super().__new__(cls) def", "def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to return", "required values. That is cumbersome since that means creating a tree of product", "the lifecycle status ({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types( cls, )", "product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls(", "State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from", "isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model", "in domain model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check", "{} # pragma: no mutate def _fix_pb_data(self) -> None: if not self.name: raise", "rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in", "a dataclass.\"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all =", "to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) #", "empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv", "not set explicitly # This makes a lot of assuptions about the internals", "subscriptions have a domain model attribute that is set as it is not", "# We only want fields that are on this class and not on", "to in writing, software # distributed under the License is distributed on an", "Types must always be `Optional` when calling `.new().` We are unable to detect", "under subscriptions. They don't have parent relations to those if not match_domain_attr: return", "import get_annotations annotations = get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue", "based on lifecycle. `Block` is valid only for `ACTIVE` And `BlockInactive` for all", "type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model", "the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type", "frontend) # Is actually optional since abstract classes dont have it. In practice", "return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined in the database as", "refresh the object and not use an already mapped object db.session.refresh(sub) self._db_model =", "Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": # status can be none if", "implied. # See the License for the specific language governing permissions and #", "= None # pragma: no mutate end_date: Optional[datetime] = None # pragma: no", "Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI) if not", "self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for", "to filter through instances depending on that attribute. Args: instance: child instance Returns:", "db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]:", "@property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return", "description is None: description = f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription", "not sub: sub = self._db_model # Make sure we refresh the object and", "of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value,", "require different product block definition. Mainly to support mandatory fields when a subscription", "type: ignore ) model._db_model = subscription_instance return model except ValidationError: logger.exception( \"Subscription is", "def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model", "subscription instances. When a new domain model is created that is not loaded", "is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription instance is missing in database\")", "product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status:", "that. Args: skip_keys: list of fields on the class to skip when creating", "SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs", "load all subscription instances for it. This function does that. Args: db_instances: list", "Check if child subscription instance models conform to the same lifecycle for product_block_field_name,", "= self.customer_id sub.description = self.description sub.status = self.status.value sub.insync = self.insync sub.start_date =", "fields and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor", "cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data =", "raise ValueError( \"Union Types must always be `Optional` when calling `.new().` We are", "have a valid subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id )", "False return is_constrained_list T = TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\",", "directly below a subscription. This is not allowed.\" ) sub.instances = saved_instances #", "child subscription instance models conform to the same lifecycle for product_block_field_name, product_block_field_type in", "if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status)", "# If this is a \"foreign\" instance we just stop saving and return", "no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription instance models conform", "field of ProductBlockModels without limits gets an empty list default_value = [] elif", "if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model class\", # pragma: no", "self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current", "# Product block name. This needs to be an instance var because its", "lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) ->", "model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances )", "lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type", "the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances", "isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type,", "SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict() for field_name, field_type in cls._product_block_fields_.items():", "one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model -", "product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if product_db else", "child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance in instances: if", "siv in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else:", "field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]]", "from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool:", "class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances. This metaclass is used", "{list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is a \"foreign\" instance we", "None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any]", "# We can assume true is no domain_model_attr is set. return not attr_names", "List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items():", "attribute a underlying instances Returns: None \"\"\" children_relations = [] # Set the", "ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union from uuid import UUID,", "However newly created SubscriptionInstances might not have the correct order for field_name in", "-> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes. This", "3.10 from inspect import get_annotations annotations = get_annotations(cls) for field_name, field_type in annotations.items():", "touch these themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model", "is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type", "and Union types always cross subscription boundaries.\" ) else: product_block_model = product_block_field_type #", "product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name,", "mandatory fields when a subscription is active. To support this a lifecycle specific", "to the database. This function iterates through the subscription instances and stores the", "a underlying instances Returns: None \"\"\" children_relations = [] # Set the domain_model_attrs", "cls.name = None # type:ignore cls.__names__ = set() # For everything except abstract", ") else: product_block_model = product_block_field_type # Scalar field of a ProductBlockModel expects 1", "assert ( # noqa: S101 product_block_model is not None ), \"Product block model", "type:ignore cls.__names__ = set() # For everything except abstract classes if cls.name is", "block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ... str_field:", "models match which would be done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db", "supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value", "subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise", "saved # We should not touch these themselves if self.subscription and subscription_instance.subscription_id !=", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options(", "the instance and act accordingly: only lists and scalar values supported resource_type_name =", "current model instance to the database. This means saving the whole tree of", "# Check if child subscription instance models conform to the same lifecycle for", "the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no", "other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item", "from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle]", "ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values", "= BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id)", "= set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db =", "type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable for", "super class or a specific lifecycle version) cls.name = product_block_name cls.__base_type__ = cls", "List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain model attribute to the database.", "lot of assuptions about the internals of `typing` if \"__orig_bases__\" in cls.__dict__ and", "type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is", "should not be used directly in the class definition. Instead a new product", "block name cls.name = None # type:ignore cls.__names__ = set() # For everything", "and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for", "to check if all constraints match subscription_id: Optional subscription id needed if this", "instances for this domain model. When a new domain model is loaded from", "non product block fields (instance values). Args: instance_values: List of instance values from", "cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id,", "{cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: # Abstract class, no product", "name: Optional[str] product_block_id: UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {}", "pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances,", "raise ValueError(f\"{cls} is not valid for lifecycle {status}\") label = subscription_instance.label instance_values =", "states. `product_type` must be defined on the base class and need not to", "product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten(", "model is saved to the database we need to save all child subscription", "or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID)", "missing_data = {} if diff: missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id(", "on lifecycle. `Subscription` is valid only for `ACTIVE` And `SubscriptionInactive` for all other", "relation in instance.parent_relations if relation.domain_model_attr } # We can assume true is no", "> 3.10 from inspect import get_annotations annotations = get_annotations(cls) for field_name, field_type in", "state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the", "to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if", "there is no good way to test for this try: is_constrained_list = issubclass(type,", "field_instance_list = [] for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child)", "with two different contraints based on lifecycle. `Block` is valid only for `ACTIVE`", "{ k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\":", "get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance", "hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__ is set", "): raise ValueError( f\"Unsafe status change of Subscription with depending subscriptions: {list(map(lambda instance:", "you may not use this file except in compliance with the License. #", "mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels", "not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of Subscription with depending", "a subscription model with two different contraints based on lifecycle. `Subscription` is valid", "model with two different contraints based on lifecycle. `Subscription` is valid only for", "saved to the database we need to save all child subscription instances for", "is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif", "`BlockInactive` for all other states. `product_block_name` must be defined on the base class", "check if all constraints match subscription_id: Optional subscription id needed if this is", "None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__(", "Field(default_factory=uuid4) # pragma: no mutate description: str = \"Initial subscription\" # pragma: no", "Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain model attribute to the", "cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type))", "as dataclasses with pydantic runtime validation. Different stages of a subscription lifecycle could", "relations in a subscription. Not all subscriptions have a domain model attribute that", "# doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) #", "@property def db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma: no", "missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for", "or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does not work on typing", "if subscription_instance: # Make sure we do not use a mapped session. db.session.refresh(subscription_instance)", "object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description =", "# status can be none if created during change_lifecycle if status and not", "db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description = self.description", "UUID, ) -> B: \"\"\"Create new domain model from instance while changing the", "model._db_model = subscription_instance return model except ValidationError: logger.exception( \"Subscription is not correct in", "for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type,", "cls._product_block_fields_ = {} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if", "can be none if created during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls,", "class. That way we can match a superclass to an instance when loading", "SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model = other._db_model return model @classmethod", "# pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B", ">>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True", "if diff: missing_data[cls.name] = diff return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID,", "= {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for", "This function does that. Args: db_instances: list of database models to load from", "-> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined in the", "[] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types", "for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value =", "lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status}", "lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the", "description: str = \"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL", "import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import", "This metaclass is used to make sure the class contains product block metadata.", "match on the product_blocks directly under subscriptions. They don't have parent relations to", "expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def", "*, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model", "Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__", "always have a specific instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls)", "value = getattr(self, field_name) if value is None: continue if is_list_type(field_type): for val,", "has minimum, return that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type)", "ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type", "if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values: # check the", "find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description:", "prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block fields (instance values). Args:", "called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with pydantic runtime validation. Different", "ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm import", "product_block_model is not None ), \"Product block model has not been resolved. Unable", "try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or", "= ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None:", "sure we always have a specific instance.. \"\"\" if not cls.__base_type__: cls =", "v } if diff: missing_data[cls.name] = diff return missing_data @classmethod def new(cls: Type[B],", "if the domain model and database models match which would be done during", "if models match match_domain_attr: Match domain attribute from relation (not wanted when loading", "model is created that is not loaded from an existing subscription. We also", "2019-2020 SURF. # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "**kwargs) if product_block_name is not None: # This is a concrete product block", "not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif", "does that. Args: db_instances: list of database models to load from status: SubscriptionLifecycle", "with parent relations for parent in subscription_instance.parents: if ( parent.subscription != self.subscription and", "# Copyright 2019-2020 SURF. # Licensed under the Apache License, Version 2.0 (the", "status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance],", "in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status)", "strips any List[..] or Optional[...] types. \"\"\" result = {} for product_block_field_name, product_block_field_type", "product block name cls.name = None # type:ignore cls.__names__ = set() # For", "a new empty product block. We need to use this instead of the", "PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import get_args,", "values for this instance. Args: status: current SubscriptionLifecycle to check if all constraints", "-> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new domain model", "= { k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model,", "imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls =", "different contraints based on lifecycle. `Block` is valid only for `ACTIVE` And `BlockInactive`", "\"\"\"Use product_id (and customer_id) to return required fields of a new empty subscription.\"\"\"", "import ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db", "{} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"],", "for instances in child_instances.values(): for instance in instances: if instance.subscription_id != self.subscription_id: raise", "Optional[...] types. \"\"\" result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type)", "\"\"\" children_relations = [] # Set the domain_model_attrs in the database for domain_model_attr,", "type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items = 1 >>>", "owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, # type: ignore ) model._db_model", "if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value", "attr_names = { relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr } # We", "= f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id)", "\"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name] = diff return missing_data", "self._db_model = sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status", "subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable,", "True # pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate product_id:", "which are saved and a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] =", "first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__),", "type of the siv in the instance and act accordingly: only lists and", "pragma: no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any)", "self.status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires", "if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, [])", "a product block based on a subscription instance from the database. This function", "are related to a database ProductBlockTable object through the `product_block_name` that is given", "cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id,", "is not valid for status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool", "models match which would be done during testing... \"\"\" if not cls.name: #", "field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle )", "@classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to", "db.session.flush() # Sends INSERT and returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id:", ">>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ... str_field: Optional[str]", "= {} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc)", "instance code \"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all", "saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class", "type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff", "a dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve", "model attributes. This helper is necessary to filter through all relations in a", "name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list )", "ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\") # Would have", "\"\"\" # We don't match on the product_blocks directly under subscriptions. They don't", "UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no", "have been nice to do this in __init_subclass__ but that runs outside the", "= product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle", "List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined in the database", "the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable", "field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists are handled OK if is_list_type(field_type):", "assumes you pass in all required values. That is cumbersome since that means", "= {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for", "its fields. All product blocks are related to a database ProductBlockTable object through", "This function does that. Args: skip_keys: list of fields on the class to", "Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def _fix_pb_data(self) -> None: if not", "cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model", "have a domain model attribute that is set as it is not always", "from an existing subscription. We also create all subscription instances for it. This", "logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else:", "loaded from an existing subscription. We also create all subscription instances for it.", "ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name) if", "-> None: \"\"\" Save the domain model attribute to the database. This function", "v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if", "SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances", "= [] for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved)", "db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id)", "= diff return missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id:", "Product block/Subscription instance code \"\"\" class Config: validate_assignment = True # pragma: no", "( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None: pass else: saved, child", "not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription instance is missing in", "on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod", "set as it is not always necessary. However when it is set, it", "_load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block fields (instance values).", "\"\"\" # subclass on typing.List throws exception and there is no good way", "resource_types = {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list)", "True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model.", "one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other, field_name) if is_optional_type(field_type): field_type =", "registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID]", "similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id)", "if v } if diff: missing_data[cls.name] = diff return missing_data @classmethod def new(cls:", "save all child subscription instances for it. Args: subscription_id: The subscription id status:", "sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable,", "_is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws exception and there is no", "product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for", "is necessary to filter through instances depending on that attribute. Args: instance: child", "and return it so only its relation is saved # We should not", "UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import", "in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type,", "cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"]", "SubscriptionLifecycle of subscription to check if models match Returns: A list with instances", "as a dataclass.\"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all", "**sub_instances, # type: ignore ) model._db_model = subscription_instance return model except ValidationError: logger.exception(", "return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in", "# noqa: S101 assert subscription_instance # noqa: S101 if not status: status =", "Make sure we have a valid subscription instance database model subscription_instance: SubscriptionInstanceTable =", "# Sends INSERT and returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance", "lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example defines a subscription model with", "models to load from status: SubscriptionLifecycle of subscription to check if models match", "use this instead of the normal constructor because that assumes you pass in", "siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure", "match. \"\"\" # We don't match on the product_blocks directly under subscriptions. They", "blocks are related to a database ProductBlockTable object through the `product_block_name` that is", "product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is", "domain model attribute that is set as it is not always necessary. However", "UUID name: str description: str product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel):", "BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]]", "product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] =", "SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to prevent cyclic imports from orchestrator.domain", "if is_base: cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ =", "Product block name. This needs to be an instance var because its part", "status: current SubscriptionLifecycle to check if all constraints match subscription_id: Optional subscription id", "customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status,", "status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore", "# Import here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls =", "ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from actual subscription if subscription_instance_id: subscription_instance", "@classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a new", "= [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, [])", "set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model))))", "specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle", "children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field,", "to a database ProductBlockTable object through the `product_block_name` that is given as class", "_find_special_fields(cls: Type) -> None: \"\"\"Make and store a list of resource_type fields and", "super().__new__(cls) def __init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs:", "done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in", "lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the", "{pb.name for pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if", "the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for the lifecycle", "a subscription instance from the database. This function is similar to `from_subscription()` >>>", "product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used", "SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure we do not", "name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None: description = f\"Initial", "cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other,", "<filename>orchestrator/domain/base.py # Copyright 2019-2020 SURF. # Licensed under the Apache License, Version 2.0", "return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the", "must always be `Optional` when calling `.new().` We are unable to detect which", "new domain model is loaded from an existing subscription we also load all", "B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class", "on a dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To", "field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in resource_types ),", "instance is None: raise ValueError(\"Required subscription instance is missing in the database\") for", "= {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if", "= product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db", "no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any,", "or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: #", "start_date: Optional[datetime] = None # pragma: no mutate end_date: Optional[datetime] = None #", "class and not on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name]", "type: ignore ) model._db_model = subscription return model @classmethod def from_other_lifecycle( cls: Type[S],", "others Create a new empty product block >>> example1 = BlockInactive() # doctest:+SKIP", "field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable for the lifecycle status", "`Subscription` is valid only for `ACTIVE` And `SubscriptionInactive` for all other states. `product_type`", "), ) ) ) product_block_model = None if instance is None: raise ValueError(\"Required", "= cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product block stuff is", "empty product block >>> example1 = BlockInactive() # doctest:+SKIP Create a new instance", "if self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model = subscription_instance else:", "specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type", "the db # So now we do it just before we instantiate the", "if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db -", "Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to the database. This means saving", "# type: ignore diff = { k: v for k, v in {", "TypeError: # issubclass does not work on typing types is_product_block_field = False #", "sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k, g in groupby(sorted_instances,", "stuff is already set if new is the first usage of this class", "{resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name) if value is None: continue", "subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for", "db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS,", "None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This example", "subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) # Save the subscription instances relations.", "should not touch these themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return [],", "is used to make sure the class contains product block metadata. This metaclass", "doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP", "the session if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush()", "data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] =", "product_block_models is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child]", "None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if", "database models match which would be done during testing... \"\"\" product_db = ProductTable.query.get(product_id)", "the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def", "{field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name) if value is None:", "its part of the API (we expose it to the frontend) # Is", "except abstract classes if cls.name is not None: register_specialized_type(cls, lifecycle) # Add ourself", "a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a", "subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore )", "PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate description: str = \"Initial", ") -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model. When", "product_id (and customer_id) to return required fields of a new empty subscription.\"\"\" #", "= get_args(field_type) for f_type in field_types: if f_type.name == value.name: field_type = f_type", "if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T = TypeVar(\"T\") #", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "all subscription instances for it. This function does that. Args: skip_keys: list of", "relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def", "result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and store a list of", "is the first usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id,", "from status: SubscriptionLifecycle of subscription to check if models match match_domain_attr: Match domain", "is missing in the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name:", "= lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status", "note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model @classmethod", "is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances", "class, no product block name cls.name = None # type:ignore cls.__names__ = set()", "None, status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a product block based", "# if constrainedlist has minimum, return that minimum else empty list if product_block_field_type.min_items:", "continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if", "= product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model =", "str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict: current_value", "instances with parent relations for parent in subscription_instance.parents: if ( parent.subscription != self.subscription", "@classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and store a list of resource_type", "now we do it just before we instantiate the instance if not hasattr(self,", "if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist", "subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, # type: ignore ) model._db_model =", "raise ValueError(f\"{cls} is not valid for status {status}\") return super().__new__(cls) def __init_subclass__( cls,", "make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences", "product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types}", "the domain model attribute to the database. This function iterates through the subscription", "{instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances", "\"\"\"Return any differences between the attrs defined on the domain model and those", ") if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type)", "domain model is loaded from an existing subscription we also load all subscription", "and a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str,", ") if description is None: description = f\"Initial subscription of {product.description}\" subscription_id =", "returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances}", "( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) )", "for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] =", "{specialized_type.__name__} (based on {field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of", "common Product block/Subscription instance code \"\"\" class Config: validate_assignment = True # pragma:", "[]) for field_type in get_args(product_block_field_type) ), ) ) ) product_block_model = None if", "( # noqa: S101 product_block_model is not None ), \"Product block model has", "model is loaded from an existing subscription we also load all subscription instances", "through the `product_block_name` that is given as class keyword argument. Define a product", "product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db", "{self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block)", "subscription.\"\"\" # Caller wants a new instance and provided a product_id and customer_id", "ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff =", "List of database instances values to save \"\"\" resource_types = {rt.resource_type: rt for", "# pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync:", "save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the", ") -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values). Returns: List of", "product block model should inherit from ProductBlockModel which has this metaclass defined. You", "status, subscription_id) model = cls(**data) model._db_model = other._db_model return model @classmethod def from_db(", "See the License for the specific language governing permissions and # limitations under", "version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {}", "all product subscription models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): #", "product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__:", "not on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type", "cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0]", "for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v", "if not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use one of", "cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return", "self._db_model # Make sure we refresh the object and not use an already", "We also create all subscription instances for it. This function does that. Args:", "this in __init_subclass__ but that runs outside the app context so we cant", "argument 'lifecycle' and overriding its fields. All product blocks are related to a", "all product block models. This class should have been called SubscriptionInstanceModel. ProductTable Blocks", "loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) ->", "this is a new model Returns: List of saved instances \"\"\" if not", "stop saving and return it so only its relation is saved # We", "\"\"\"Shorthand to create constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) ->", "not always necessary. However when it is set, it is necessary to filter", "= SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool = False, start_date: Optional[datetime] =", "lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs = {fi.name:", "str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "these themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model =", "val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else:", "model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs,", "subscription_id to return required fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances)", "\"\"\"Create new domain model from instance while changing the status. This makes sure", "issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]:", "in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append(", "= lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of", "k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\":", "self.description sub.status = self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date = self.end_date", "subscription we also load all subscription instances for it. This function does that.", "S101 field_name in resource_types ), f\"Domain model {self.__class__} does not match the ProductBlockTable", "classes dont have it. In practice it is always set name: str subscription_instance_id:", "cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model", "cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not", "product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def __call__(self, *args: Any, **kwargs: Any)", "subscription_instance.parents))}\" ) # If this is a \"foreign\" instance we just stop saving", "from pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload", "required fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations),", "dummy instances. Returns: A dict with instances to pass to the new model", "Sends INSERT and returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for", "with two different contraints based on lifecycle. `Subscription` is valid only for `ACTIVE`", "-> Dict[str, str]: \"\"\"Load non product block fields (instance values). Args: instance_values: List", "status=status ) return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID)", "-> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for", "{pb.name for pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if", "was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values(", "not to be defined on the others Create a new empty subscription >>>", "**fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model except ValidationError:", "ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: # Abstract class, no product block", "defined on the others Create a new empty product block >>> example1 =", "(so not a abstract super class or a specific lifecycle version) cls.name =", "ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually", "ProductBlockModel This example defines a subscription model with two different contraints based on", "= None, status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a product block", "based on a dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP", "cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences", "object through the `product_block_name` that is given as class keyword argument. Define a", "self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block", "is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name,", "if type is a constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class", "If this is a \"foreign\" instance we just stop saving and return it", "specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values),", "sure the class contains product block metadata. This metaclass should not be used", "lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for", "if TYPE_CHECKING: annotations = {} else: # Only available in python > 3.10", "mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_:", "lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in", "\"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db,", "directly under subscriptions. They don't have parent relations to those if not match_domain_attr:", "-> None: if not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use", "{type(self)!r}\" ) # Actually save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block,", "Type) -> None: \"\"\"Make and store a list of resource_type fields and product", "field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B],", "this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise", "from inspect import get_annotations annotations = get_annotations(cls) for field_name, field_type in annotations.items(): if", "ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma:", "[] for field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in", "= other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for", "instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id,", "database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save the subscription to", "self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model = subscription_instance else: subscription_instance", "instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save a Foreign `Subscription Instance` directly", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create", "mutate start_date: Optional[datetime] = None # pragma: no mutate end_date: Optional[datetime] = None", "while changing the status. This makes sure we always have a speficic instance.", "raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non", "subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model # We only need to", "= {fi.name: fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str):", "subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, # type: ignore )", "if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__", "that runs outside the app context so we cant access the db #", "the frontend) # Is actually optional since abstract classes dont have it. In", "testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if", "specialized_type): raise AssertionError( f\"The lifecycle status of the type for the field: {product_block_field_name},", "(not wanted when loading product blocks directly related to subscriptions) Returns: A dict", "field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in resource_types ), f\"Domain", "not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was:", "list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for _ in", "on a dict in the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To", "None: raise ValueError(\"Required subscription instance is missing in the database\") for field_type in", "is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id:", "field_type.name: product_block_model = field_type assert ( # noqa: S101 product_block_model is not None", "new product block model should inherit from ProductBlockModel which has this metaclass defined.", "SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g)", "block >>> example1 = BlockInactive() # doctest:+SKIP Create a new instance based on", "of the siv in the instance and act accordingly: only lists and scalar", "instance while changing the status. This makes sure we always have a specific", "is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None", "self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note = self.note", "in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name]", "child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self,", "product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for", "that are on this class and not on the parent if is_product_block_field: cls._product_block_fields_[field_name]", "for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, )", "of the domain model attribute a underlying instances Returns: None \"\"\" children_relations =", "assert ( # noqa: S101 field_name in resource_types ), f\"Domain model {self.__class__} does", "TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for domain models.", "subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101", "= set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if product_db else set()", "instance of abstract class. Use one of {self.__names__}\") # Make sure we have", "State = {} list_field_names = set() # Set default values for field_name, field_type", "Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive]", "\"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no", "no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model:", "Exception: # Strip generic arguments, it still might be a subclass if get_origin(type):", "# Ensure that empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] = []", "sub = self._db_model # Make sure we refresh the object and not use", "first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls:", "f_type in field_types: if f_type.name == value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value,", "domain model is created that is not loaded from an existing subscription. We", "== cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children} if product_block_db else set()", "states. `product_block_name` must be defined on the base class and need not to", ") # If this is a \"foreign\" instance we just stop saving and", "Set, Tuple, Type, TypeVar, Union from uuid import UUID, uuid4 import structlog from", "product block models. This class should have been called SubscriptionInstanceModel. ProductTable Blocks are", "database ProductBlockTable object through the `product_block_name` that is given as class keyword argument.", "ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description", "the status. This makes sure we always have a speficic instance. \"\"\" if", "class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all common Product block/Subscription instance", "= None elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for f_type in", "= set() # Set default values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure", "= one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in", "ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\") # Make sure", "... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block:", "S101 assert subscription_instance # noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if", "the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable", "SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model #", "issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for the field:", "and not on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] =", "lifecycle status ({lifecycle_status}) of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if", "valid for lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children,", "# This is a concrete product block base class (so not a abstract", "iterates through the subscription instances and stores the domain model attribute in the", "instances and seperately saving all instance values for this instance. Args: status: current", "abstract classes if cls.name is not None: register_specialized_type(cls, lifecycle) # Add ourself to", "saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is", "1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def _load_instances(", "bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains", "for `ACTIVE` And `BlockInactive` for all other states. `product_block_name` must be defined on", "on the domain model and those on product blocks in the database. This", "{specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label = self.label subscription_instance.values =", "{self.__class__} does not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name]", "to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type):", "= product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable],", "in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance", "self._db_model SI = TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to", "other._db_model return model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance:", "Type, TypeVar, Union from uuid import UUID, uuid4 import structlog from more_itertools import", "{} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type):", "for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list", "first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif", "outside the app context so we cant access the db # So now", "is None: raise ValueError(\"Required subscription instance is missing in database\") else: instances[product_block_field_name] =", "raise ValueError( \"Attempting to save a Foreign `Subscription Instance` directly below a subscription.", "code \"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all =", "Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType)", "# doctest:+SKIP To retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP", "model {self.__class__} does not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type =", "and # limitations under the License. from collections import defaultdict from datetime import", "cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure", "KIND, either express or implied. # See the License for the specific language", "product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db", "# limitations under the License. from collections import defaultdict from datetime import datetime", "Union from uuid import UUID, uuid4 import structlog from more_itertools import first, flatten,", "children) return sub_instances + [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription", "model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S:", "= {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type:", "models that have Subscription instances with parent relations for parent in subscription_instance.parents: if", "want fields that are on this class and not on the parent if", "product block definition can be created by subclassing the generic product block with", "in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k,", "-> bool: \"\"\" Match domain model attributes. This helper is necessary to filter", "in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model =", "parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status", "differences between the attrs defined on the domain model and those on product", "an already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id =", "product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag =", "for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model,", "= self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id", "is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved)", "we cant access the db # So now we do it just before", "for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items():", "subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property def subscription(self)", "instances depending on that attribute. Args: instance: child instance Returns: Boolean of match.", "depending on that attribute. Args: instance: child instance Returns: Boolean of match. \"\"\"", "= structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is a constained", "[] for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field]", "values to save \"\"\" resource_types = {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict:", "with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is a", "value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif is_union_type(field_type) and", "it. Args: subscription_id: The subscription id status: SubscriptionLifecycle of subscription to check if", "product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models:", "subscription_id: UUID, ) -> B: \"\"\"Create new domain model from instance while changing", "None: continue if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if val: if", "in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations =", "subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore", "pydantic import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass", "if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status)", "`Block` is valid only for `ACTIVE` And `BlockInactive` for all other states. `product_block_name`", "ValidationError from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList", "status, subscription_id) else: data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type): field_types =", "is set, it is necessary to filter through instances depending on that attribute.", "product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status)", "object and not use an already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id", "groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\"", "one, only from pydantic import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from", "if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and", "in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model SI =", "subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T = TypeVar(\"T\")", ") ) ) if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None elif", "\"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db,", "have a speficic instance. \"\"\" if not cls.__base_type__: # Import here to prevent", "state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the", "ANY KIND, either express or implied. # See the License for the specific", "annotations = {} else: # Only available in python > 3.10 from inspect", "subclassing the generic product block with keyword argument 'lifecycle' and overriding its fields.", "SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new domain model from instance while", "only for `ACTIVE` And `SubscriptionInactive` for all other states. `product_type` must be defined", "{self.__names__}\") # Would have been nice to do this in __init_subclass__ but that", "match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self,", "with instances to pass to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]]", "True attr_names = { relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr } #", "the lifecycle status ({lifecycle_status}) of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status)", "class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models. This class should", "k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db,", "in the hierarchy relationship. Args: subscription_instance_mapping: a mapping of the domain model attribute", "else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str,", "= product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type)", "str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def _fix_pb_data(self) ->", "lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value}", "product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = []", "None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new", "a new domain model is created that is not loaded from an existing", "is loaded from an existing subscription we also load all subscription instances for", "in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type assert ( # noqa:", "\"\"\"Metaclass used to create product block instances. This metaclass is used to make", "str_field: str This example defines a product_block with two different contraints based on", "ignore diff = { k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db,", "We need to use this instead of the normal constructor because that assumes", "class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance:", "field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or", "List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block fields (instance values). Args: instance_values:", "str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes.", "missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = {", "siv in instance_values: # check the type of the siv in the instance", "pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool", "\"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if product_db", "status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model = other._db_model return", "self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id without", "empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for _", "Scalar field of a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] =", "-> Dict[str, Any]: \"\"\"Return any differences between the attrs defined on the domain", ">>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance based on", "fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for", "class. Use one of {self.__names__}\") # Make sure we have a valid subscription", "None: # This is a concrete product block base class (so not a", "create instance of abstract class. Use one of {self.__names__}\") # Would have been", "default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels without limits gets an empty", "import attrgetter from sys import version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar,", "product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model =", "register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str,", ") model._db_model = subscription return model except ValidationError: logger.exception( \"Subscription is not correct", "Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str]", "product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None: description = f\"Initial subscription of", "g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) ->", "subscription instances for it. This function does that. Args: skip_keys: list of fields", "not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value =", "in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other, field_name)", "\"\"\" if not cls.name: # This is a superclass we can't check that", "= ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if product_db else set()", "None: description = f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable(", "Make sure we refresh the object and not use an already mapped object", "missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) #", "set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model", "= {rt.resource_type for rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model", "and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model =", "# noqa: S101 field_name in resource_types ), f\"Domain model {self.__class__} does not match", "relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable:", "not valid for status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool =", "a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances", "committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances =", "constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) #", "value = getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] =", "= get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else:", "if v } missing_data = {} if diff: missing_data[product_db.name] = diff return missing_data", "var because its part of the API (we expose it to the frontend)", "if models match Returns: A list with instances which are saved and a", "instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make", "we always have a speficic instance. \"\"\" if not cls.__base_type__: # Import here", "keyword argument. Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field:", "any differences between the attrs defined on the domain model and those on", "missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v }", "return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if", "have the correct order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict", "part of the API (we expose it to the frontend) # Is actually", "instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index,", "in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id,", "we are of the right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and", "= product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list( filter( filter_func,", "(instance values). Returns: List of database instances values to save \"\"\" resource_types =", "is set as it is not always necessary. However when it is set,", "saving the whole tree of subscription instances and seperately saving all instance values", "save(self) -> None: \"\"\"Save the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status)", "correct order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def", "*, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) ->", "return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models.", "{fi.name: fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model", "isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\"", "\"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description: str tag: str registry: Dict[str,", "save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children", "\"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) ->", "self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT and", "the class definition. Instead a new product block model should inherit from ProductBlockModel", "not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs", "different product block definition. Mainly to support mandatory fields when a subscription is", "status: SubscriptionLifecycle of subscription to check if models match Returns: A list with", "S: \"\"\"Use a subscription_id to return required fields of an existing subscription.\"\"\" subscription", "instances for it. This function does that. Args: skip_keys: list of fields on", "description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name. This", "any super class. That way we can match a superclass to an instance", "without limits gets an empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value", "to be defined on the others Create a new empty product block >>>", "missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k, v in", "description = f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id,", "UUID = Field(default_factory=uuid4) # pragma: no mutate description: str = \"Initial subscription\" #", "} # We can assume true is no domain_model_attr is set. return not", "product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product", "`Optional` when calling `.new().` We are unable to detect which type to intialise", "act accordingly: only lists and scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name", "a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T =", "[], subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model # We only need", "insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in", "lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is", "SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool = False # pragma: no mutate", "[]) for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in", "Use one of {self.__names__}\") # Would have been nice to do this in", "instances in child_instances.values(): for instance in instances: if instance.subscription_id != self.subscription_id: raise ValueError(", "from an existing subscription we also load all subscription instances for it. This", "usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model)", "subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id", "set if new is the first usage of this class cls._fix_pb_data() db_model =", "\"\"\"Load subscription instances for this domain model. When a new domain model is", "Not all subscriptions have a domain model attribute that is set as it", "subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a", "= match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list =", "k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items()", "it is always set name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] =", "Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: # This", "set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only", "must be defined on the base class and need not to be defined", "of the right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self,", "function does that. Args: db_instances: list of database models to load from status:", "f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save", "directly related to subscriptions) Returns: A dict with instances to pass to the", "License. from collections import defaultdict from datetime import datetime from itertools import groupby,", "= {} cls._product_block_fields_ = {} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {})", "python > 3.10 from inspect import get_annotations annotations = get_annotations(cls) for field_name, field_type", "model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str:", "is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be `Optional` when calling `.new().` We", "fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if product_db else", "pragma: no mutate insync: bool = False # pragma: no mutate start_date: Optional[datetime]", "return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product", "BlockInactive() # doctest:+SKIP Create a new instance based on a dict in the", "This class should have been called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses", "is saved to the database we need to save all child subscription instances", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "class keyword argument. Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ...", "the database. This function iterates through the subscription instances and stores the domain", "str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription", "to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure", "= KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 =", "{} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances", "match Returns: A list with instances which are saved and a dict with", "except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise", "-> None: \"\"\"Save the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if", "= None, note: Optional[str] = None, ) -> S: \"\"\"Use product_id (and customer_id)", "lifecycle status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__})", "instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\",", "Dict of fields to use for constructor \"\"\" instance_values_dict: State = {} list_field_names", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "!= subscription_id: return [], subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model #", "\"foreign\" instance we just stop saving and return it so only its relation", "ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID", "instance.product_block.name == field_type.name: product_block_model = field_type assert ( # noqa: S101 product_block_model is", "when loading product blocks directly related to subscriptions) Returns: A dict with instances", "instances which are saved and a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable]", "validate_assignment = True # pragma: no mutate validate_all = True # pragma: no", "Returns: A list with instances which are saved and a dict with direct", "unable to detect which type to intialise and Union types always cross subscription", "child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None:", "applicable law or agreed to in writing, software # distributed under the License", "= ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if", "current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = []", "Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model from", "or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does not", "none if created during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise", "lifecycle status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__})", "based on a subscription instance from the database. This function is similar to", "min_items\", type=product_block_field_type) # pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: #", "SubscriptionLifecycle to check if all constraints match subscription_id: Optional subscription id needed if", "filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), ) ) )", ">>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class", "subscription instances for this domain model. When a domain model is saved to", "a \"foreign\" instance we just stop saving and return it so only its", "= only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ),", "relation is saved # We should not touch these themselves if self.subscription and", "is a concrete product block base class (so not a abstract super class", "contraints based on lifecycle. `Subscription` is valid only for `ACTIVE` And `SubscriptionInactive` for", "bool = False # pragma: no mutate start_date: Optional[datetime] = None # pragma:", "not been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else:", "in child_instances.values(): for instance in instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting", "constrainedlist has minimum, return that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\",", "orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle", "not be used directly in the class definition. Instead a new product block", "in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type()", "filter through instances depending on that attribute. Args: instance: child instance Returns: Boolean", "- product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type", "= set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if product_block_db else set()", "loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save the subscription to the database.\"\"\"", "class ProductModel(BaseModel): \"\"\"Represent the product as defined in the database as a dataclass.\"\"\"", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in", "Optional[datetime] = None, end_date: Optional[datetime] = None, note: Optional[str] = None, ) ->", "instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model", "import get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable,", "fields (instance values). Returns: List of database instances values to save \"\"\" resource_types", "a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]]", "we do it just before we instantiate the instance if not hasattr(self, \"product_block_id\"):", "except Exception: # Strip generic arguments, it still might be a subclass if", "subscription lifecycle could require different product block definition. Mainly to support mandatory fields", "tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in", "fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id =", "blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model,", "= sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle,", "self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]:", "metaclass is used to make sure the class contains product block metadata. This", "product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) #", "end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model", "in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model =", "And `SubscriptionInactive` for all other states. `product_type` must be defined on the base", "subscription. We also create all subscription instances for it. This function does that.", "_save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block", ") ) product_block_model = None if instance is None: raise ValueError(\"Required subscription instance", "writing, software # distributed under the License is distributed on an \"AS IS\"", "default_value return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool", "field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type assert ( #", "SubscriptionInstanceTable for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr,", "imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls =", "on the product_blocks directly under subscriptions. They don't have parent relations to those", "[] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for", "database we need to save all child subscription instances for it. Args: subscription_id:", "This strips any List[..] or Optional[...] types. \"\"\" result = {} for product_block_field_name,", "super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models. This", "result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type):", "existing subscription. We also create all subscription instances for it. This function does", "instance when loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ =", "db_instances: list of database models to load from status: SubscriptionLifecycle of subscription to", "create product block instances. This metaclass is used to make sure the class", "type if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore", "product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model", "lists and scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value)", "lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try:", "( parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe", "SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool = False, start_date: Optional[datetime]", "Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property", "been nice to do this in __init_subclass__ but that runs outside the app", "Dict: data = other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] =", "to do this in __init_subclass__ but that runs outside the app context so", "overriding its fields. All product blocks are related to a database ProductBlockTable object", "get_args(field_type) for f_type in field_types: if f_type.name == value.name: field_type = f_type data[field_name]", "two different contraints based on lifecycle. `Subscription` is valid only for `ACTIVE` And", "{ \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v }", "try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note,", "def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save", "compliance with the License. # You may obtain a copy of the License", "app context so we cant access the db # So now we do", "no domain_model_attr is set. return not attr_names or field_name in attr_names return domain_filter", "constructor because that assumes you pass in all required values. That is cumbersome", "block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel", "and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for status {status}\")", "= UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date,", "import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type)", "raise AssertionError( f\"The lifecycle status of the type for the field: {product_block_field_name}, {specialized_type.__name__}", "subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to return required fields of", "between the attrs defined on the domain model and those on product blocks", "sub_instances + [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def", "None, insync: bool = False, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None,", "a dict in the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve", "ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values).", "issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") label =", "This is only needed to check if the domain model and database models", "the type of the siv in the instance and act accordingly: only lists", "= cls(**data) model._db_model = other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID,", "the internals of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0]", "subscription id status: SubscriptionLifecycle of subscription to check if models match Returns: A", "noqa: S101 assert subscription_instance # noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status)", "if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append(", "True # pragma: no mutate product_id: UUID name: str description: str product_type: str", "isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"),", "description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model", "-> bool: \"\"\"Check if type is a constained list type. Example: >>> _is_constrained_list_type(List[int])", "resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db", "the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property def", "subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model", "needs to be an instance var because its part of the API (we", "note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model except", "under the License. from collections import defaultdict from datetime import datetime from itertools", "if new is the first usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable(", "attribute to the database. This function iterates through the subscription instances and stores", "check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for", "logger.warning( \"Unexpected keyword arguments in domain model class\", # pragma: no mutate class_name=cls.__name__,", "a new empty product block >>> example1 = BlockInactive() # doctest:+SKIP Create a", "= getattr(self, field_name) if value is None: continue if is_list_type(field_type): for val, siv", "which has this metaclass defined. You can find some examples in: :ref:`domain-models` \"\"\"", "product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children} if", "a domain model is saved to the database we need to save all", "super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls, lifecycle)", "database models to load from status: SubscriptionLifecycle of subscription to check if models", ") # Check if child subscription instance models conform to the same lifecycle", "for relation in instance.parent_relations if relation.domain_model_attr } # We can assume true is", "else: # Only available in python > 3.10 from inspect import get_annotations annotations", "is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None: pass else: saved, child =", "return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID,", "diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db,", "= set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model", "accordingly: only lists and scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in", "SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"]", "if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not", "mutate note: Optional[str] = None # pragma: no mutate def __new__(cls, *args: Any,", "None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI) if not set explicitly", "block base class (so not a abstract super class or a specific lifecycle", "\"\"\" resource_types = {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] =", "database Returns: Dict of fields to use for constructor \"\"\" instance_values_dict: State =", "is None: # Abstract class, no product block name cls.name = None #", "_save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription", "SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool = False # pragma:", "collections import defaultdict from datetime import datetime from itertools import groupby, zip_longest from", "missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status:", "We can assume true is no domain_model_attr is set. return not attr_names or", "status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to prevent", "classes if cls.name is not None: register_specialized_type(cls, lifecycle) # Add ourself to any", "type=product_block_field_type) # pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a", "instance Returns: Boolean of match. \"\"\" # We don't match on the product_blocks", "product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name] =", "sure values are sorted. This already happens when they come from the db.", "other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model from instance", "doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from actual", "filter through all relations in a subscription. Not all subscriptions have a domain", "status change of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) #", "ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models. Define a subscription", "= subscription return model except ValidationError: logger.exception( \"Subscription is not correct in database\",", "if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, )", "to support mandatory fields when a subscription is active. To support this a", "Optional[datetime] = None # pragma: no mutate note: Optional[str] = None # pragma:", "model \"\"\" if skip_keys is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]]", "UUID, **kwargs: Any) -> B: \"\"\"Create a new empty product block. We need", "Instance` directly below a subscription. This is not allowed.\" ) sub.instances = saved_instances", "if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str,", "no good way to test for this try: is_constrained_list = issubclass(type, ConstrainedList) except", "= field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys:", "This function iterates through the subscription instances and stores the domain model attribute", "during testing... \"\"\" if not cls.name: # This is a superclass we can't", ") model._db_model = subscription_instance return model except ValidationError: logger.exception( \"Subscription is not correct", "the database as a dataclass.\"\"\" class Config: validate_assignment = True # pragma: no", "on a subscription instance from the database. This function is similar to `from_subscription()`", "cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) ->", "not use an already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id", "= None, end_date: Optional[datetime] = None, note: Optional[str] = None, ) -> S:", "Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types. This strips any", "List[SI]): \"\"\"Shorthand to create constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any)", "product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only be", "a constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items", "product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type)", "domain model attribute to the database. This function iterates through the subscription instances", "set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db", "= True # pragma: no mutate validate_all = True # pragma: no mutate", "cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize", "not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok, make sure", "status ({lifecycle_status}) of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not", "instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name", "of {self.__names__}\") # Make sure we have a valid subscription instance database model", "@property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return", "ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub =", "(the \"License\"); # you may not use this file except in compliance with", "product as defined in the database as a dataclass.\"\"\" class Config: validate_assignment =", "and act accordingly: only lists and scalar values supported resource_type_name = siv.resource_type.resource_type if", "of subscription to check if models match match_domain_attr: Match domain attribute from relation", "class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type): raise ValueError(", "specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status", "Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def _fix_pb_data(self) -> None: if", "We don't match on the product_blocks directly under subscriptions. They don't have parent", "need not to be defined on the others Create a new empty product", "@classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined", "type: ignore diff = { k: v for k, v in { \"missing_product_blocks_in_db\":", "# Make sure values are sorted. This already happens when they come from", "to load from status: SubscriptionLifecycle of subscription to check if models match match_domain_attr:", "other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"]", "self.customer_id sub.description = self.description sub.status = self.status.value sub.insync = self.insync sub.start_date = self.start_date", "# Unless required by applicable law or agreed to in writing, software #", "subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain model attribute to", "by applicable law or agreed to in writing, software # distributed under the", "doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ...", "product_id and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type,", "everything except abstract classes if cls.name is not None: register_specialized_type(cls, lifecycle) # Add", "models. This class should have been called SubscriptionInstanceModel. ProductTable Blocks are represented as", "hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description", "import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if", "= ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from actual subscription if subscription_instance_id:", "self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined in the database as a", "Import here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name,", "which would be done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name", "self.subscription_id: raise ValueError( \"Attempting to save a Foreign `Subscription Instance` directly below a", "a lot of assuptions about the internals of `typing` if \"__orig_bases__\" in cls.__dict__", "product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k, v", "attrgetter from sys import version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict,", "set() # Set default values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that", "and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__ is set cls.__args__ =", "filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type)", "is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does not work", "Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle,", "a new model Returns: List of saved instances \"\"\" if not self.name: raise", "is not valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi in", "are represented as dataclasses with pydantic runtime validation. Different stages of a subscription", "types. \"\"\" result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and", "skip_keys: list of fields on the class to skip when creating dummy instances.", "unsafe status changes on domain models that have Subscription instances with parent relations", "not valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs}", "remove instances_set = {instance.subscription_instance_id for instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id,", "instances to pass to the new model \"\"\" if skip_keys is None: skip_keys", "test for this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip generic", "customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no", "pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B =", "example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance based on a", "session if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() #", "model attribute to the database. This function iterates through the subscription instances and", "file except in compliance with the License. # You may obtain a copy", "Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any )", "are on this class and not on the parent if is_product_block_field: cls._product_block_fields_[field_name] =", "list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise", "subscription\" # pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate", "the domain model and database models match which would be done during testing...", "cls.name is not None: register_specialized_type(cls, lifecycle) # Add ourself to any super class.", "missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and", "\"Union Types must always be `Optional` when calling `.new().` We are unable to", "model attribute in the hierarchy relationship. Args: subscription_instance_mapping: a mapping of the domain", "\"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product block", "from the db. # However newly created SubscriptionInstances might not have the correct", "order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle(", "relations for parent in subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status not", "class for domain models. Contains all common Product block/Subscription instance code \"\"\" class", "not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for the", "field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item in getattr(other,", "since abstract classes dont have it. In practice it is always set name:", "@classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) ->", "= self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id without committing transaction", "on this class and not on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type", "Create a new empty product block >>> example1 = BlockInactive() # doctest:+SKIP Create", "the domain model attribute a underlying instances Returns: None \"\"\" children_relations = []", "# Actually save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values )", "When a domain model is saved to the database we need to save", "on product blocks in the database. This is only needed to check if", "database models match which would be done during testing... \"\"\" if not cls.name:", "= False, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, note: Optional[str] =", "= {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = {", "True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate", "block. We need to use this instead of the normal constructor because that", "except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise", "we do not use a mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes", "product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for", "diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined on the", "the License. from collections import defaultdict from datetime import datetime from itertools import", "sys import version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional,", "@classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None,", "return model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances,", "\"missing_in_children\": missing_data_children, }.items() if v } missing_data = {} if diff: missing_data[product_db.name] =", "return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T = TypeVar(\"T\") # pragma: no", "diff return missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID,", "given as class keyword argument. Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual", "_non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs:", "= [] # Set the domain_model_attrs in the database for domain_model_attr, instances in", "instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left should", "first usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, )", "instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id", "Different stages of a subscription lifecycle could require different product block definition. Mainly", "done during testing... \"\"\" if not cls.name: # This is a superclass we", "model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>>", "if skip_keys is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {}", "when they come from the db. # However newly created SubscriptionInstances might not", "filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status)", "status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and status ==", "List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if", "inspect import get_annotations annotations = get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"):", "orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from", "of instance values from database Returns: Dict of fields to use for constructor", "raise ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) #", "child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *, subscription_id:", "the first usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id,", "), f\"Domain model {self.__class__} does not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\"", "not touch these themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance", "{product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status})", "This means saving the whole tree of subscription instances and seperately saving all", "isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\"", "= f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id,", "missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data =", "field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for the lifecycle status", "lifecycle. `Subscription` is valid only for `ACTIVE` And `SubscriptionInactive` for all other states.", "mapped object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description", "model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure we", "diff = { k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\":", "None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required", "and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type =", "for this domain model. When a new domain model is loaded from an", "domain attribute from relation (not wanted when loading product blocks directly related to", "to be an instance var because its part of the API (we expose", "from sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable,", "you pass in all required values. That is cumbersome since that means creating", "\"\"\"Load non product block fields (instance values). Args: instance_values: List of instance values", "status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models. Define a", "customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date,", "data[\"end_date\"] = nowtz() model = cls(**data) model._db_model = other._db_model return model @classmethod def", "-> S: \"\"\"Create new domain model from instance while changing the status. This", "raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub", "import defaultdict from datetime import datetime from itertools import groupby, zip_longest from operator", "= product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db", "save \"\"\" resource_types = {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]]", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "the API (we expose it to the frontend) # Is actually optional since", "elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None: pass else: saved,", "cls(**data) model._db_model = other._db_model return model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID]", ">>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr()", "here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls)", "status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date,", "UUID, uuid4 import structlog from more_itertools import first, flatten, one, only from pydantic", "when creating dummy instances. Returns: A dict with instances to pass to the", "relationship. Args: subscription_instance_mapping: a mapping of the domain model attribute a underlying instances", ".selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model # Make sure we", "return True attr_names = { relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr }", "None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be `Optional` when calling", "new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a new empty product", "field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError(", "subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__( cls, *, product_block_name:", "label=label, **instance_values, # type: ignore **sub_instances, # type: ignore ) model._db_model = subscription_instance", "children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined in", "child_instances.values(): for instance in instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to", "be defined on the others Create a new empty subscription >>> example1 =", ") ) if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None elif not", "missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model:", "subscription_id: The subscription id status: SubscriptionLifecycle of subscription to check if models match", "None: register_specialized_type(cls, lifecycle) # Add ourself to any super class. That way we", "S: \"\"\"Use product_id (and customer_id) to return required fields of a new empty", "import structlog from more_itertools import first, flatten, one, only from pydantic import BaseModel,", "cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, #", "model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError(", "instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property def subscription(self) ->", "# pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_:", "def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block", "match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date,", "{product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status})", "# subclass on typing.List throws exception and there is no good way to", "def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": #", "Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning(", "blocks directly related to subscriptions) Returns: A dict with instances to pass to", "in the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel", "cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle)", "db.session.add(sub) db.session.flush() # Sends INSERT and returns subscription_id without committing transaction old_instances_dict =", "insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription", "block with keyword argument 'lifecycle' and overriding its fields. All product blocks are", "instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription", "subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) # Save", "product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type):", "str): customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync,", "\"\"\"Create a new empty product block. We need to use this instead of", "val, siv in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value = str(val) subscription_instance_values.append(siv)", "if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized", "Create a new instance based on a dict in the state: >>> example2", "status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model =", "others Create a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP", "metadata. This metaclass should not be used directly in the class definition. Instead", "Match domain model attributes. This helper is necessary to filter through all relations", "metaclass should not be used directly in the class definition. Instead a new", "ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)):", "None: \"\"\"Save the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type", "a subscription. This is not allowed.\" ) sub.instances = saved_instances # Calculate what", "def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children", "product block. We need to use this instead of the normal constructor because", "else: field_type = product_block_field_type result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls: Type)", "active. To support this a lifecycle specific product block definition can be created", "scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name]", "for instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type):", "the base class and need not to be defined on the others Create", "Optional[int] = None ... str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ...", "of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model", "no product block name cls.name = None # type:ignore cls.__names__ = set() #", "= None elif not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription instance", "-> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel):", "ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id)", "in instances_set: old_instances_dict.pop(instance_id, None) # What's left should be removed for instance in", "S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name,", "lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name", "-> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: # This is a", "instance: child instance Returns: Boolean of match. \"\"\" # We don't match on", "missing in the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model", "**kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel,", "is not loaded from an existing subscription. We also create all subscription instances", "have it. In practice it is always set name: str subscription_instance_id: UUID owner_subscription_id:", "not valid for lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances =", "noqa: S101 field_name in resource_types ), f\"Domain model {self.__class__} does not match the", "actually optional since abstract classes dont have it. In practice it is always", "Returns: A dict with instances to pass to the new model \"\"\" if", "import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db,", "resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model =", "try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances,", "str = \"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL #", ">>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from actual subscription", "orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status)", "raise ValueError( f\"Unsafe status change of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description,", "return that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma:", "cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls", "sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product block stuff", "status) data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model = other._db_model return", "-> \"SubscriptionModel\": # status can be none if created during change_lifecycle if status", "UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note,", "field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type,", "Abstract class, no product block name cls.name = None # type:ignore cls.__names__ =", "the app context so we cant access the db # So now we", "Foreign `Subscription Instance` directly below a subscription. This is not allowed.\" ) sub.instances", "cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model", "str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k,", "if this is a new model Returns: List of saved instances \"\"\" if", "= SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance based on a dict", "is not suitable for the lifecycle status ({lifecycle_status}) of this model\" ) else:", "is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does not work on typing types", "in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure values are sorted.", "contains product block metadata. This metaclass should not be used directly in the", "# doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] =", "to test for this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip", "List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) )", "self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) #", "resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db,", "= True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no", "a new instance based on a dict in the state: >>> example2 =", "-> B: \"\"\"Create new domain model from instance while changing the status. This", "siv.value # Make sure values are sorted. This already happens when they come", "for all product subscription models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"):", "note: Optional[str] = None, ) -> S: \"\"\"Use product_id (and customer_id) to return", "fields that are on this class and not on the parent if is_product_block_field:", "{} else: # Only available in python > 3.10 from inspect import get_annotations", "does that. Args: skip_keys: list of fields on the class to skip when", "cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in", "database\") for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type assert", "values from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id =", "in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value))", "class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ... str_field: Optional[str] =", "= set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() #", "List of instance values from database Returns: Dict of fields to use for", "False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if", "Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": # status can be", "subscription of {product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description,", "A dict with instances to pass to the new model \"\"\" instances: Dict[str,", "changes on domain models that have Subscription instances with parent relations for parent", "cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls", "doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID =", "diff: missing_data[cls.name] = diff return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs:", "a product_id and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description,", "= cls elif lifecycle is None: # Abstract class, no product block name", "orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type:", "is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass", "\"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v", "Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types. This strips any List[..] or", "is a new model Returns: List of saved instances \"\"\" if not self.name:", "need not to be defined on the others Create a new empty subscription", "Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types. This strips any List[..]", "ourself to any super class. That way we can match a superclass to", "description: str product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for", "(instance values). Args: instance_values: List of instance values from database Returns: Dict of", "in __init_subclass__ but that runs outside the app context so we cant access", "if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for", "({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"],", "sub.start_date = self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends", "Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes. This helper", "None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and", "specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized type", "UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool = False,", "None: # Abstract class, no product block name cls.name = None # type:ignore", "filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for", "is not None: register_specialized_type(cls, lifecycle) # Add ourself to any super class. That", "None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls,", "typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar,", "should be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) ->", "subscription instances for this domain model. When a new domain model is loaded", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "product_block_id: UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma:", ") model._db_model = subscription return model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\",", "def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B:", "list of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ =", "on typing.List throws exception and there is no good way to test for", "missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data = {} if", "below a subscription. This is not allowed.\" ) sub.instances = saved_instances # Calculate", "any List[..] or Optional[...] types. \"\"\" result = {} for product_block_field_name, product_block_field_type in", "is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance is None: raise", "\"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4)", "database. This means saving the whole tree of subscription instances and seperately saving", "Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff =", "\"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data = {} if diff:", "is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model", "no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of product blocks.\"\"\"", "Strip generic arguments, it still might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type))", "= get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field =", "skip_keys is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for", "not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type", "instead of the normal constructor because that assumes you pass in all required", "values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] =", "from datetime import datetime from itertools import groupby, zip_longest from operator import attrgetter", "for all other states. `product_block_name` must be defined on the base class and", "logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model,", "nice to do this in __init_subclass__ but that runs outside the app context", "still might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return", "of a new empty subscription.\"\"\" # Caller wants a new instance and provided", "a Foreign `Subscription Instance` directly below a subscription. This is not allowed.\" )", "always be `Optional` when calling `.new().` We are unable to detect which type", "None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model class\",", "int_field: Optional[int] = None ... str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]):", "# noqa: S101 product_block_model is not None ), \"Product block model has not", "List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances,", "data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data", "flatten, one, only from pydantic import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models. This class should have been", "when a subscription is active. To support this a lifecycle specific product block", "missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff:", "else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle", "status ({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types( cls, ) -> Dict[str,", "get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable,", "of product blocks. This is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys()))", "lifecycle is None: # Abstract class, no product block name cls.name = None", "**kwargs) # type: ignore model._db_model = db_model return model @classmethod def _load_instances_values(cls, instance_values:", "example defines a product_block with two different contraints based on lifecycle. `Block` is", "of a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return", "creating a tree of product blocks. This is similar to `from_product_id()` \"\"\" sub_instances", "model attribute that is set as it is not always necessary. However when", "in resource_types ), f\"Domain model {self.__class__} does not match the ProductBlockTable {product_block.name}, missing:", "# Would have been nice to do this in __init_subclass__ but that runs", "domain_model_attrs in the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index,", "subscription_instance = self._db_model # We only need to add to the session if", "to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i:", "product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = []", "pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and", "We only need to add to the session if the subscription_instance does not", "product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only be one in the type", "all relations in a subscription. Not all subscriptions have a domain model attribute", "= cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {} else: # Only available", "TYPE_CHECKING: annotations = {} else: # Only available in python > 3.10 from", "_db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name. This needs to be an", "= {} if diff: missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id( cls:", "elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name,", "and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r},", "optional since abstract classes dont have it. In practice it is always set", "name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__( cls,", "instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type)", "available in python > 3.10 from inspect import get_annotations annotations = get_annotations(cls) for", "return missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr],", "more_itertools import first, flatten, one, only from pydantic import BaseModel, Field, ValidationError from", "`product_block_name` that is given as class keyword argument. Define a product block: >>>", "in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model =", "stores the domain model attribute in the hierarchy relationship. Args: subscription_instance_mapping: a mapping", "\"Unexpected keyword arguments in domain model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(),", "those if not match_domain_attr: return True attr_names = { relation.domain_model_attr for relation in", "@classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block fields", "doctest:+SKIP To retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\"", "(we expose it to the frontend) # Is actually optional since abstract classes", "block stuff is already set if new is the first usage of this", "if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id,", "-> Dict: data = other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name]", "Use one of {self.__names__}\") # Make sure we have a valid subscription instance", "self._save_instances(subscription_id, status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances +", "Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to return required fields of an", "for it. Args: subscription_id: The subscription id status: SubscriptionLifecycle of subscription to check", "don't match on the product_blocks directly under subscriptions. They don't have parent relations", "valid only for `ACTIVE` And `SubscriptionInactive` for all other states. `product_type` must be", "models. Contains all common Product block/Subscription instance code \"\"\" class Config: validate_assignment =", "orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr,", "= first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type return result @classmethod def", "block fields (instance values). Returns: List of database instances values to save \"\"\"", "is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except", "would be done during testing... \"\"\" if not cls.name: # This is a", "def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block fields (instance", "# pragma: no mutate description: str = \"Initial subscription\" # pragma: no mutate", "get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = (", "be defined on the base class and need not to be defined on", "not match_domain_attr: return True attr_names = { relation.domain_model_attr for relation in instance.parent_relations if", "= lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid", "subscription_id: UUID) -> Dict: data = other.dict() for field_name, field_type in cls._product_block_fields_.items(): if", "or is_union_type(product_block_field_type) ) and product_block_models is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id,", "skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in", "pragma: no mutate product_id: UUID name: str description: str product_type: str tag: str", "= None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be `Optional` when", "from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def", "ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name.", "(based on {field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this", "domain model attribute a underlying instances Returns: None \"\"\" children_relations = [] #", "data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None and", "{} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list", ">>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This example defines", "None: \"\"\" Save the domain model attribute to the database. This function iterates", "pragma: no mutate start_date: Optional[datetime] = None # pragma: no mutate end_date: Optional[datetime]", "the License for the specific language governing permissions and # limitations under the", "class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models. Define a subscription model:", "= True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain", "lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]:", "selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, )", "sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub =", "version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls", "is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type):", "else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self, subscription_id: UUID,", "customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool", "\"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new domain model is created that", "SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance", "empty product block. We need to use this instead of the normal constructor", ") @classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the", ">>> example1 = BlockInactive() # doctest:+SKIP Create a new instance based on a", "in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool:", "subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa:", "true is no domain_model_attr is set. return not attr_names or field_name in attr_names", "# However newly created SubscriptionInstances might not have the correct order for field_name", "= ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel)", "instance_values_dict: State = {} list_field_names = set() # Set default values for field_name,", "and provided a product_id and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id,", "ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models. This class should have", "*args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields()", "because that assumes you pass in all required values. That is cumbersome since", "def save(self) -> None: \"\"\"Save the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__,", "lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if", "when loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls,", "to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) #", "should inherit from ProductBlockModel which has this metaclass defined. You can find some", "if isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description,", "model instance to the database. This means saving the whole tree of subscription", "= set() # For everything except abstract classes if cls.name is not None:", "self.subscription_instance_id ) if subscription_instance: # Make sure we do not use a mapped", "= first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None", "Dict[str, Any]: \"\"\"Return any differences between the attrs defined on the domain model", "the hierarchy relationship. Args: subscription_instance_mapping: a mapping of the domain model attribute a", "Contains all common Product block/Subscription instance code \"\"\" class Config: validate_assignment = True", "new is the first usage of this class cls._fix_pb_data() db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id,", "for this instance. Args: status: current SubscriptionLifecycle to check if all constraints match", "in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item in getattr(other, field_name): data[field_name].append(", "= siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make", "= None, insync: bool = False, start_date: Optional[datetime] = None, end_date: Optional[datetime] =", "specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label = self.label", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "- resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if", "old_instances_dict.pop(instance_id, None) # What's left should be removed for instance in old_instances_dict.values(): db.session.delete(instance)", "SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)):", "= product_block_field_type() # if constrainedlist has minimum, return that minimum else empty list", "{} cls._product_block_fields_ = {} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else:", "= cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model = other._db_model return model @classmethod", "# pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of", "B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for", "Returns: None \"\"\" children_relations = [] # Set the domain_model_attrs in the database", "__init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None:", "one of {self.__names__}\") # Make sure we have a valid subscription instance database", "= lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status", "}.items() if v } missing_data = {} if diff: missing_data[product_db.name] = diff return", "cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None:", "_is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\"", "are handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values:", "= cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None and status", "... str_field: str This example defines a product_block with two different contraints based", "description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import", "product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model", "DomainModel) ) except TypeError: # issubclass does not work on typing types is_product_block_field", "of {self.__names__}\") # Would have been nice to do this in __init_subclass__ but", "siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name", "Add ourself to any super class. That way we can match a superclass", "domain model attributes. This helper is necessary to filter through all relations in", "database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate", "ValueError(\"Required subscription instance is missing in the database\") for field_type in get_args(product_block_field_type): if", "from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to return required", "if all constraints match subscription_id: Optional subscription id needed if this is a", "__init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any,", "... str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ...", "= product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass", "required fields of a new empty subscription.\"\"\" # Caller wants a new instance", "\"\"\"Save subscription instances for this domain model. When a domain model is saved", "You can find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id:", "-> S: \"\"\"Use product_id (and customer_id) to return required fields of a new", "Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str", "None # pragma: no mutate end_date: Optional[datetime] = None # pragma: no mutate", "child subscription instances for it. Args: subscription_id: The subscription id status: SubscriptionLifecycle of", "if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance #", "= cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod", "model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, #", "v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\":", "model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs,", "all child subscription instances for it. Args: subscription_id: The subscription id status: SubscriptionLifecycle", "= product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in", "= other._db_model return model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None,", "# pragma: no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs:", "not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") label", "db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") #", "if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif is_union_type(field_type)", "def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as defined", "requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types),", "\"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and", "block instances. This metaclass is used to make sure the class contains product", "pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and", "None, ) -> B: \"\"\"Create a product block based on a subscription instance", "arguments in domain model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) #", "attribute from relation (not wanted when loading product blocks directly related to subscriptions)", "child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass):", "needed if this is a new model Returns: List of saved instances \"\"\"", "practice it is always set name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str]", "\"\"\"Use a subscription_id to return required fields of an existing subscription.\"\"\" subscription =", "SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]):", "Any) -> B: \"\"\"Create a new empty product block. We need to use", "[subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self) ->", "= None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ =", "subscriptions. They don't have parent relations to those if not match_domain_attr: return True", ") sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub", "domain model is saved to the database we need to save all child", "In practice it is always set name: str subscription_instance_id: UUID owner_subscription_id: UUID label:", "keyword argument 'lifecycle' and overriding its fields. All product blocks are related to", "ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name]", "Version 2.0 (the \"License\"); # you may not use this file except in", "saved_instances # Calculate what to remove instances_set = {instance.subscription_instance_id for instance in sub.instances}", "intialise and Union types always cross subscription boundaries.\" ) else: product_block_model = product_block_field_type", "zip_longest from operator import attrgetter from sys import version_info from typing import TYPE_CHECKING,", "mutate class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all common Product block/Subscription", "field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type", "product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model", "skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() #", "pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db import ( ProductBlockTable,", "super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model class\", #", "not cls.name: # This is a superclass we can't check that return {}", "_data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict() for", "happens when they come from the db. # However newly created SubscriptionInstances might", "def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle =", "in python > 3.10 from inspect import get_annotations annotations = get_annotations(cls) for field_name,", "instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status:", "doctest:+SKIP \"\"\" # Fill values from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id)", "class contains product block metadata. This metaclass should not be used directly in", "for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation", "str product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all", "def _find_special_fields(cls: Type) -> None: \"\"\"Make and store a list of resource_type fields", "retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str,", "not None: # This is a concrete product block base class (so not", "else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug(", "cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {} else: # Only available in", "no mutate arbitrary_types_allowed = True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None", "for instance in instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save", "instances_set: old_instances_dict.pop(instance_id, None) # What's left should be removed for instance in old_instances_dict.values():", "we refresh the object and not use an already mapped object db.session.refresh(sub) self._db_model", "it. This function does that. Args: skip_keys: list of fields on the class", "ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances. This metaclass is used to", "product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database())", "no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]]", "This example defines a product_block with two different contraints based on lifecycle. `Block`", "product_block_model = field_type assert ( # noqa: S101 product_block_model is not None ),", "is_list_type(field_type): data[field_name] = [] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id)", "else: instance_values_dict[resource_type_name] = siv.value # Make sure values are sorted. This already happens", "in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable]", "for parent in subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status not in", "as defined in the database as a dataclass.\"\"\" class Config: validate_assignment = True", "field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other, field_name) if is_optional_type(field_type):", "constructor \"\"\" instance_values_dict: State = {} list_field_names = set() # Set default values", "# Block unsafe status changes on domain models that have Subscription instances with", "the current model instance to the database. This means saving the whole tree", "from collections import defaultdict from datetime import datetime from itertools import groupby, zip_longest", "created SubscriptionInstances might not have the correct order for field_name in list_field_names: instance_values_dict[field_name]", "not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) #", "subscription to check if models match Returns: A list with instances which are", "keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k:", "super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: # This is a concrete product", "database instances values to save \"\"\" resource_types = {rt.resource_type: rt for rt in", "for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod", "= None, ) -> B: \"\"\"Create a product block based on a subscription", "not have the correct order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return", "_get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model", "str description: str product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class", "database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type): raise ValueError(", "missing_data_children, }.items() if v } missing_data = {} if diff: missing_data[product_db.name] = diff", "be done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb", "about the internals of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls =", "not work on typing types is_product_block_field = False # We only want fields", "int ... str_field: str This example defines a product_block with two different contraints", "or a specific lifecycle version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__ =", "on {product_block_field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this model\"", "for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls:", "from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma:", "as class keyword argument. Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"):", "f\"Unsafe status change of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" )", "datetime from itertools import groupby, zip_longest from operator import attrgetter from sys import", "list of fields on the class to skip when creating dummy instances. Returns:", "Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a new empty product block.", "_from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create", "from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle,", "= only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) )", "one of {self.__names__}\") # Would have been nice to do this in __init_subclass__", "the subscription instances and stores the domain model attribute in the hierarchy relationship.", "product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model =", "and product_block_models is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] =", "it to the frontend) # Is actually optional since abstract classes dont have", "fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model", "specific product block definition can be created by subclassing the generic product block", ">>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws exception and there is", "None: raise ValueError(\"Required subscription instance is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db(", "in the database. This is only needed to check if the domain model", "None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example defines", "subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance", "product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif (", "status changes on domain models that have Subscription instances with parent relations for", "ValueError( f\"Unsafe status change of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\"", "valid for status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool = False,", "def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents", "else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func,", "= SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool = False # pragma: no", "else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db", "of the API (we expose it to the frontend) # Is actually optional", "use a mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes on domain models", "block definition can be created by subclassing the generic product block with keyword", "domain model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if", "in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels without limits gets", "from the database. This function is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB", "= {k: list(g) for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) ->", "siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in", "domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation =", "from instance while changing the status. This makes sure we always have a", "= self._db_model # We only need to add to the session if the", "= make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any", "for val, siv in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value = str(val)", "has this metaclass defined. You can find some examples in: :ref:`domain-models` \"\"\" __names__:", "Args: instance: child instance Returns: Boolean of match. \"\"\" # We don't match", "is given as class keyword argument. Define a product block: >>> class BlockInactive(ProductBlockModel,", "False # pragma: no mutate start_date: Optional[datetime] = None # pragma: no mutate", "registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def _fix_pb_data(self) -> None:", "mutate description: str = \"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle =", "SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls,", "subscription. This is not allowed.\" ) sub.instances = saved_instances # Calculate what to", "else: subscription_instance = self._db_model # We only need to add to the session", ") instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list(", "instance based on a dict in the state: >>> example2 = BlockInactive(\\*\\*state) #", "for status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool = False, lifecycle:", "return is_constrained_list T = TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\")", "instances. When a new domain model is created that is not loaded from", "doctest:+SKIP To retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\"", "else: return False return is_constrained_list T = TypeVar(\"T\") # pragma: no mutate S", "To retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product:", "product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children:", "a speficic instance. \"\"\" if not cls.__base_type__: # Import here to prevent cyclic", "product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db =", "field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models", "model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, )", "need to add to the session if the subscription_instance does not exist. db.session.add(subscription_instance)", "This makes sure we always have a specific instance.. \"\"\" if not cls.__base_type__:", "if diff: missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id( cls: Type[S], product_id:", "instance and provided a product_id and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel(", "all common Product block/Subscription instance code \"\"\" class Config: validate_assignment = True #", "runtime validation. Different stages of a subscription lifecycle could require different product block", "if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): #", "class for all product subscription models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel,", "not attr_names or field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items():", "= product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func,", "subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3", "SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model.", "Optional[str] = None, insync: bool = False, start_date: Optional[datetime] = None, end_date: Optional[datetime]", "and not use an already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id =", "subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id,", "match which would be done during testing... \"\"\" if not cls.name: # This", "= self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status = self.status.value sub.insync =", "subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) # Save the subscription instances", "block name. This needs to be an instance var because its part of", "\"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str: return", "- product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if", "TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate", "None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None:", "= ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill", "for the lifecycle status ({lifecycle_status}) of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type,", "attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type):", "mutate product_id: UUID name: str description: str product_type: str tag: str status: ProductLifecycle", "subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id,", "cls.name = product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif", "type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id)", "from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from", "example defines a subscription model with two different contraints based on lifecycle. `Subscription`", "examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description: str tag:", "List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load", "Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None,", "customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value", "= cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id,", "the class to skip when creating dummy instances. Returns: A dict with instances", "klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any", "= subscription_instance return model except ValidationError: logger.exception( \"Subscription is not correct in database\",", "product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] = None", "Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool =", "version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple,", "Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in", "calling `.new().` We are unable to detect which type to intialise and Union", "ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any", "defines a product_block with two different contraints based on lifecycle. `Block` is valid", "product block >>> example1 = BlockInactive() # doctest:+SKIP Create a new instance based", "only needed to check if the domain model and database models match which", "else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may", "getattr(self, field_name) if value is None: continue if is_list_type(field_type): for val, siv in", "type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label = self.label subscription_instance.values", "to be defined on the others Create a new empty subscription >>> example1", ") -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if is_base or", "that is set as it is not always necessary. However when it is", "the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not", "subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is a \"foreign\" instance", "Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, ) ->", "before we instantiate the instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name ==", "status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls", "return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict:", "in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other:", "is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type,", "block model should inherit from ProductBlockModel which has this metaclass defined. You can", "loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save the subscription to the", "= lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of", "Copy generic argument (SI) if not set explicitly # This makes a lot", "ignore ) model._db_model = subscription return model except ValidationError: logger.exception( \"Subscription is not", "if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls,", "a specific instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore", "do not use a mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes on", "a specific lifecycle version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name}", "ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be", "\"\"\"Create a product block based on a subscription instance from the database. This", "is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db =", "cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls,", "= False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs)", "**instances, # type: ignore ) model._db_model = subscription return model @classmethod def from_other_lifecycle(", "Fill values from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id", "ignore **sub_instances, # type: ignore ) model._db_model = subscription_instance return model except ValidationError:", "subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure we do", "contraints based on lifecycle. `Block` is valid only for `ACTIVE` And `BlockInactive` for", "a new product block model should inherit from ProductBlockModel which has this metaclass", "status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new domain model from instance", "label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model =", "does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok, make", "product_block.description self.tag = product_block.tag def __call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data()", "for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left should be removed for", "Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is", "not None ), \"Product block model has not been resolved. Unable to continue\"", "subscription_instance.children_relations = children_relations def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) ->", "self._db_model # We only need to add to the session if the subscription_instance", "= {} else: # Only available in python > 3.10 from inspect import", "product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if product_db", "# pragma: no mutate insync: bool = False # pragma: no mutate start_date:", "new instance based on a dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state)", "\"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type", "children_relations def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]:", "when it is set, it is necessary to filter through instances depending on", "v } missing_data = {} if diff: missing_data[product_db.name] = diff return missing_data @classmethod", "= SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name,", "database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure", "status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value", "Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta):", "not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires specialized type {specialized_type!r}, was:", "some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description: str", "**kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI) if", "Instead a new product block model should inherit from ProductBlockModel which has this", "`from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP", "name: str description: str product_type: str tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base", ") db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id)", "Returns: Boolean of match. \"\"\" # We don't match on the product_blocks directly", "to check if the domain model and database models match which would be", "is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status)", "for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances =", "not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for status {status}\") return", "None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any]", "model types. This strips any List[..] or Optional[...] types. \"\"\" result = {}", "{k: list(g) for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable:", "cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] =", "OF ANY KIND, either express or implied. # See the License for the", "list of database models to load from status: SubscriptionLifecycle of subscription to check", "dict in the state: >>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a", "can match a superclass to an instance when loading for klass in cls.__mro__:", "other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new domain model", "= product_block.tag def __call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] =", "with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {}", "To support this a lifecycle specific product block definition can be created by", "- resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model,", "to pass to the new model \"\"\" if skip_keys is None: skip_keys =", "__call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args,", "= None def __init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] =", "# type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model =", "subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore )", "values from database Returns: Dict of fields to use for constructor \"\"\" instance_values_dict:", "_product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]]", "product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ...", "relation.domain_model_attr } # We can assume true is no domain_model_attr is set. return", "subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok,", "logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is a", "argument (SI) if not set explicitly # This makes a lot of assuptions", "product block fields (instance values). Args: instance_values: List of instance values from database", "def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new", "instance is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance is None:", "missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod", "type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data)", "existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product =", "subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id,", "it is set, it is necessary to filter through instances depending on that", "lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type,", "block definition. Mainly to support mandatory fields when a subscription is active. To", "Optional[str] = None def __init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]]", "to skip when creating dummy instances. Returns: A dict with instances to pass", "the specific language governing permissions and # limitations under the License. from collections", "model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non product block", "to make sure the class contains product block metadata. This metaclass should not", "rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv)", "r\"\"\"Base class for all product subscription models. Define a subscription model: >>> class", "defined on the others Create a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id,", "= product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list(", "instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only(", "which type to intialise and Union types always cross subscription boundaries.\" ) else:", "= cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model = db_model return model", "support mandatory fields when a subscription is active. To support this a lifecycle", "block model types. This strips any List[..] or Optional[...] types. \"\"\" result =", "of abstract class. Use one of {self.__names__}\") # Would have been nice to", "List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name,", "of abstract class. Use one of {self.__names__}\") # Make sure we have a", "parent relations for parent in subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status", "that empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for", "during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not", ">>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\"", "sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance in", "{} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children}", "make sure the class contains product block metadata. This metaclass should not be", "cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, # type: ignore", "SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs", "model Returns: List of saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot create", "TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no", "= self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) # Save the", "= product_block.description self.tag = product_block.tag def __call__(self, *args: Any, **kwargs: Any) -> B:", "nowtz() if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model", "missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt", "raise ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\") # Would", "parent relations to those if not match_domain_attr: return True attr_names = { relation.domain_model_attr", "lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type,", "for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]", "block/Subscription instance code \"\"\" class Config: validate_assignment = True # pragma: no mutate", ") -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model. When", "runs outside the app context so we cant access the db # So", "self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances", "product block base class (so not a abstract super class or a specific", "else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug(", "assert subscription_instance # noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not", "missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi", "in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items()", "== self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def __call__(self,", "a tree of product blocks. This is similar to `from_product_id()` \"\"\" sub_instances =", "product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is", "we have a valid subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id", "SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not", "cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item,", "v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\":", "def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"],", "if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save a Foreign `Subscription Instance`", "the correct order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod", "subscription model with two different contraints based on lifecycle. `Subscription` is valid only", "owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model = db_model return model @classmethod def", "# doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) #", "match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for", "Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This example defines a product_block", "Set default values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists", "= product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status:", "instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls =", "Args: status: current SubscriptionLifecycle to check if all constraints match subscription_id: Optional subscription", "}.items() if v } if diff: missing_data[cls.name] = diff return missing_data @classmethod def", "product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): #", "is valid only for `ACTIVE` And `SubscriptionInactive` for all other states. `product_type` must", "is a constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ...", "# type: ignore model._db_model = db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable])", "changing the status. This makes sure we always have a specific instance.. \"\"\"", "based on lifecycle. `Subscription` is valid only for `ACTIVE` And `SubscriptionInactive` for all", "model and database models match which would be done during testing... \"\"\" if", "None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls", "-> B: \"\"\"Create a product block based on a subscription instance from the", "of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id)", "subscription_instance_id # noqa: S101 assert subscription_instance # noqa: S101 if not status: status", "for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model", "ok, make sure we are of the right class specialized_type = lookup_specialized_type(self.__class__, status)", "types is_product_block_field = False # We only want fields that are on this", "status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None", "SubscriptionInstanceTable]: \"\"\"Save the current model instance to the database. This means saving the", "empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance", "And `BlockInactive` for all other states. `product_block_name` must be defined on the base", "\"\"\"Make and store a list of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_", "SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import (", "this is a \"foreign\" instance we just stop saving and return it so", "domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes. This helper is necessary", "= field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type):", "saved and a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances:", "instances to pass to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] =", "flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance", "subscription_id) model = cls(**data) model._db_model = other._db_model return model @classmethod def from_db( cls:", "might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list", "field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name)", "instance to the database. This means saving the whole tree of subscription instances", "missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr],", "tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate def _fix_pb_data(self)", "for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise", "return model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances", "abstract super class or a specific lifecycle version) cls.name = product_block_name cls.__base_type__ =", "else: product_block_model = product_block_field_type # Scalar field of a ProductBlockModel expects 1 instance", "structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is a constained list", "else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else:", "self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product", "or agreed to in writing, software # distributed under the License is distributed", "with keyword argument 'lifecycle' and overriding its fields. All product blocks are related", "pydantic.main import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin from", "get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type assert ( # noqa: S101", "{fi.name: fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id", "SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) #", "bool: \"\"\"Check if type is a constained list type. Example: >>> _is_constrained_list_type(List[int]) False", "match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model", "existing subscription we also load all subscription instances for it. This function does", "through all relations in a subscription. Not all subscriptions have a domain model", "= [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product", "ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] =", "Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a product", "ValueError( \"Union Types must always be `Optional` when calling `.new().` We are unable", "cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: # Abstract", "to the database. This means saving the whole tree of subscription instances and", "index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation)", "through the subscription instances and stores the domain model attribute in the hierarchy", "a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id:", "# Calculate what to remove instances_set = {instance.subscription_instance_id for instance in sub.instances} for", "= one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has minimum, return that minimum", "if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure values", "instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable(", "so we cant access the db # So now we do it just", "attrs defined on the domain model and those on product blocks in the", "_load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str,", "k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable)", "getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status,", "attribute in the hierarchy relationship. Args: subscription_instance_mapping: a mapping of the domain model", "for name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance is None:", "other states. `product_block_name` must be defined on the base class and need not", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances. This metaclass", "cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types.", "may only be one in the type if it is a Tuple product_blocks_in_model", "= subscription_id db.session.flush() # Everything is ok, make sure we are of the", "start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, note: Optional[str] = None, )", "ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db import", "We only want fields that are on this class and not on the", "subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self,", "BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types", "__base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str,", "for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model:", "= None # pragma: no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] =", "sub.instances = saved_instances # Calculate what to remove instances_set = {instance.subscription_instance_id for instance", "or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type return", "removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return", "helper is necessary to filter through all relations in a subscription. Not all", "db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if", "License. # You may obtain a copy of the License at # #", "# Make sure we refresh the object and not use an already mapped", "product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None:", "uuid import UUID, uuid4 import structlog from more_itertools import first, flatten, one, only", "field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id)", "return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None:", "would be done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for", "diff: missing_data[product_db.name] = diff return missing_data @classmethod def from_product_id( cls: Type[S], product_id: Union[UUID,", "[] list_field_names.add(field_name) for siv in instance_values: # check the type of the siv", "__init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any )", "self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]:", "However when it is set, it is necessary to filter through instances depending", "**kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if", "if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else:", "selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status", "on the base class and need not to be defined on the others", "# issubclass does not work on typing types is_product_block_field = False # We", "cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id: UUID,", "a subscription is active. To support this a lifecycle specific product block definition", "this a lifecycle specific product block definition can be created by subclassing the", "one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type:", "this metaclass defined. You can find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str]", "function is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db", "{ k: v for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\":", "-> SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def", "sure we always have a speficic instance. \"\"\" if not cls.__base_type__: # Import", "model = cls(**data) model._db_model = other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id:", "tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name. This needs to", "no mutate end_date: Optional[datetime] = None # pragma: no mutate note: Optional[str] =", "means creating a tree of product blocks. This is similar to `from_product_id()` \"\"\"", "product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block", "product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple):", "return super().__new__(cls) def __init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None,", "stages of a subscription lifecycle could require different product block definition. Mainly to", "product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) )", "def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) ->", "model. When a new domain model is loaded from an existing subscription we", "on the others Create a new empty product block >>> example1 = BlockInactive()", "r\"\"\"Base class for all product block models. This class should have been called", "status. This makes sure we always have a speficic instance. \"\"\" if not", "SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self)", "is not suitable for the lifecycle status ({lifecycle_status}) of this model\" ) @classmethod", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "instances_set = {instance.subscription_instance_id for instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None)", "# Add ourself to any super class. That way we can match a", "for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable for the", "field_type in get_args(product_block_field_type) ), ) ) ) product_block_model = None if instance is", "missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in", "= defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type", "Optional subscription id needed if this is a new model Returns: List of", "what to remove instances_set = {instance.subscription_instance_id for instance in sub.instances} for instance_id in", "does not work on typing types is_product_block_field = False # We only want", "need to save all child subscription instances for it. Args: subscription_id: The subscription", "Returns: List of saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot create instance", "\"\"\" if not cls.__base_type__: # Import here to prevent cyclic imports from orchestrator.domain", "# type: ignore ) model._db_model = subscription return model except ValidationError: logger.exception( \"Subscription", "-> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList,", "domain_model_attr is set. return not attr_names or field_name in attr_names return domain_filter for", "model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id", "mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\":", "have Subscription instances with parent relations for parent in subscription_instance.parents: if ( parent.subscription", "here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls)", "noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls =", "# pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription instance", "resource_types ), f\"Domain model {self.__class__} does not match the ProductBlockTable {product_block.name}, missing: {field_name}", "values). Returns: List of database instances values to save \"\"\" resource_types = {rt.resource_type:", "subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str,", "argument. Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int]", "generic product block with keyword argument 'lifecycle' and overriding its fields. All product", "\"Attempting to save a Foreign `Subscription Instance` directly below a subscription. This is", "product blocks. This is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id", "is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring", "[]) for name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance is", "License, Version 2.0 (the \"License\"); # you may not use this file except", "types. This strips any List[..] or Optional[...] types. \"\"\" result = {} for", "if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for", "# pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate product_id: UUID", "is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model =", "list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure values are sorted. This", "ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model =", "# pragma: no mutate validate_all = True # pragma: no mutate arbitrary_types_allowed =", "= self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status)", ") ) ) product_block_model = None if instance is None: raise ValueError(\"Required subscription", "been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model", "in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) #", "= getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models: saved,", "product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type:", "of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {}", "= \"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma:", "in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left should be", "sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status = self.status.value sub.insync", "on typing types is_product_block_field = False # We only want fields that are", "make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between the", "is no domain_model_attr is set. return not attr_names or field_name in attr_names return", "could require different product block definition. Mainly to support mandatory fields when a", "model._db_model = db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]:", "tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to", "definition. Instead a new product block model should inherit from ProductBlockModel which has", "UUID owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__( cls, *, product_block_name: Optional[str]", "({lifecycle_status}) of this model\" ) else: specialized_type = lookup_specialized_type(product_block_field_type, lifecycle_status) if not issubclass(product_block_field_type,", "\"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name]", "product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs}", "subscription_instance_id = uuid4() # Make sure product block stuff is already set if", "instance from the database. This function is similar to `from_subscription()` >>> subscription_instance_id =", "all other states. `product_block_name` must be defined on the base class and need", "result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and", "{}) else: if TYPE_CHECKING: annotations = {} else: # Only available in python", "def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances =", "ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod", "make sure we are of the right class specialized_type = lookup_specialized_type(self.__class__, status) if", "There may only be one in the type if it is a Tuple", "tag=product_db.tag, status=product_db.status, ) if description is None: description = f\"Initial subscription of {product.description}\"", "product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model =", "issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for status {status}\") return super().__new__(cls)", "and isinstance(first(product_blocks_types_in_model), tuple): # There may only be one in the type if", "SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value =", "of saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot create instance of abstract", "fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db", "product_block_field_type # Scalar field of a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id)", "This already happens when they come from the db. # However newly created", "Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a subscription_id to return required fields", "for siv in instance_values: # check the type of the siv in the", "to subscriptions) Returns: A dict with instances to pass to the new model", "in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items(): assert (", "product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db -", "Make sure values are sorted. This already happens when they come from the", "groupby, zip_longest from operator import attrgetter from sys import version_info from typing import", "if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\")", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "is no good way to test for this try: is_constrained_list = issubclass(type, ConstrainedList)", "related to subscriptions) Returns: A dict with instances to pass to the new", "one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__)", "to the frontend) # Is actually optional since abstract classes dont have it.", "# type: ignore ) model._db_model = subscription return model @classmethod def from_other_lifecycle( cls:", "DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does not work on", "self.description = product_block.description self.tag = product_block.tag def __call__(self, *args: Any, **kwargs: Any) ->", "subscription_instance return model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values,", "`product_type` must be defined on the base class and need not to be", "of ProductBlockModels without limits gets an empty list default_value = [] elif is_optional_type(product_block_field_type,", "cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not", "not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for the", "missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for product_block_in_model in", "_is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has minimum, return", "= Field(default_factory=uuid4) # pragma: no mutate description: str = \"Initial subscription\" # pragma:", "class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on", "lifecycle status ({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types( cls, ) ->", "match_domain_attr: return True attr_names = { relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr", "a database ProductBlockTable object through the `product_block_name` that is given as class keyword", "saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance in instances:", "subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate description: str = \"Initial subscription\"", ") # Actually save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values", "concrete product block base class (so not a abstract super class or a", "default_value = product_block_field_type() # if constrainedlist has minimum, return that minimum else empty", "saving and return it so only its relation is saved # We should", "_fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot create instance of abstract class.", "always cross subscription boundaries.\" ) else: product_block_model = product_block_field_type # Scalar field of", "{specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if", "we can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db =", "Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union from uuid import", "This metaclass should not be used directly in the class definition. Instead a", "only lists and scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names:", "-> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types. This strips", "product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model,", "subscription instance database model subscription_instance: SubscriptionInstanceTable = SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: #", "if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list =", "elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types: if", "List of saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot create instance of", "def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences between the attrs", "customer_id) # doctest:+SKIP Create a new instance based on a dict in the", "product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if _is_constrained_list_type(product_block_field_type): product_block_model = one(get_args(product_block_field_type)) default_value =", "domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *, subscription_id: UUID, status:", "__new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": # status", "for domain models. Contains all common Product block/Subscription instance code \"\"\" class Config:", "for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values():", "not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model", "for this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip generic arguments,", "Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type =", "and not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, []) for", "tree of product blocks. This is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id,", "structlog from more_itertools import first, flatten, one, only from pydantic import BaseModel, Field,", "dict in the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a", "PrivateAttr() # Product block name. This needs to be an instance var because", "Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model. When a new", "resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if", "are sorted. This already happens when they come from the db. # However", "SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id:", "in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save the subscription", "pragma: no mutate note: Optional[str] = None # pragma: no mutate def __new__(cls,", "raise ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for", "not allowed.\" ) sub.instances = saved_instances # Calculate what to remove instances_set =", "cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls,", "SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data =", "filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list", "product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor < 10:", "defaultdict from datetime import datetime from itertools import groupby, zip_longest from operator import", "# We only need to add to the session if the subscription_instance does", "instance while changing the status. This makes sure we always have a speficic", "product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model", "the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from", "of this model\" ) @classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]:", "permissions and # limitations under the License. from collections import defaultdict from datetime", "TypeVar, Union from uuid import UUID, uuid4 import structlog from more_itertools import first,", "set, it is necessary to filter through instances depending on that attribute. Args:", "check if models match Returns: A list with instances which are saved and", "def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain", "not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\")", "cross subscription boundaries.\" ) else: product_block_model = product_block_field_type # Scalar field of a", "@property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return", "Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field)", "None: if not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use one", "skip when creating dummy instances. Returns: A dict with instances to pass to", "product_block_name is not None: # This is a concrete product block base class", "missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name] = diff return", "pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate product_id: UUID name:", "itertools import groupby, zip_longest from operator import attrgetter from sys import version_info from", "UUIDstr]) -> S: \"\"\"Use a subscription_id to return required fields of an existing", "klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def", "subscriptions) Returns: A dict with instances to pass to the new model \"\"\"", "the database. This means saving the whole tree of subscription instances and seperately", "subscription_instance_mapping: a mapping of the domain model attribute a underlying instances Returns: None", "new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new", "= sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k, g in groupby(sorted_instances, keyfunc)}", "resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure values are", "# type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type =", "noqa: S101 product_block_model is not None ), \"Product block model has not been", "or implied. # See the License for the specific language governing permissions and", "first, flatten, one, only from pydantic import BaseModel, Field, ValidationError from pydantic.fields import", "db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model = db_model", "change of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If", "is_union_type(product_block_field_type) ) and product_block_models is None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status)", "if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database())", "None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword", "= self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance in instances: if instance.subscription_id", "Import here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name,", "only need to add to the session if the subscription_instance does not exist.", "testing... \"\"\" if not cls.name: # This is a superclass we can't check", "Mainly to support mandatory fields when a subscription is active. To support this", "-> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument (SI) if not set", "necessary to filter through all relations in a subscription. Not all subscriptions have", "used directly in the class definition. Instead a new product block model should", "be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False return is_constrained_list T", "work on typing types is_product_block_field = False # We only want fields that", "label: Optional[str] = None def __init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle:", "attr_names or field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func", "data[\"status\"] = status if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] =", "and stores the domain model attribute in the hierarchy relationship. Args: subscription_instance_mapping: a", "store a list of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ = {}", "and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor <", "-> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values). Returns: List of database", "the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and not isinstance(self, specialized_type): raise", "for k, v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model,", "was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not", "field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances(", "= {fi.name for fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model", "empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type):", "This is a concrete product block base class (so not a abstract super", "if val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) )", "= SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs)", "Actually save stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances,", ") return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) ->", "dict with instances to pass to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel],", "an existing subscription we also load all subscription instances for it. This function", "# pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class", "always set name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None def", "the domain model and those on product blocks in the database. This is", "subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance # noqa: S101", "return [], subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model # We only", "= SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status,", "language governing permissions and # limitations under the License. from collections import defaultdict", "None def __init_subclass__( cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None,", "subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id,", "loading product blocks directly related to subscriptions) Returns: A dict with instances to", "match subscription_id: Optional subscription id needed if this is a new model Returns:", "Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When", "status. This makes sure we always have a specific instance.. \"\"\" if not", "Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model):", "= None, **kwargs: Any) -> \"SubscriptionModel\": # status can be none if created", "else: data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for", "load from status: SubscriptionLifecycle of subscription to check if models match match_domain_attr: Match", "insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription", "= None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a", "# There may only be one in the type if it is a", "for f_type in field_types: if f_type.name == value.name: field_type = f_type data[field_name] =", "default values for field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists are", "instances for it. Args: subscription_id: The subscription id status: SubscriptionLifecycle of subscription to", "= ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls,", "self.status) for instances in child_instances.values(): for instance in instances: if instance.subscription_id != self.subscription_id:", "range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels without limits gets an", "set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable", "list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name]) return instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\",", "KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db)", "!= self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change", "B: \"\"\"Create a new empty product block. We need to use this instead", "= {pb.name for pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values()", "in product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model),", "status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model =", "old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\")", "product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] =", "Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if", "Save the domain model attribute to the database. This function iterates through the", "db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma: no mutate class", "else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for", "None if instance is None: raise ValueError(\"Required subscription instance is missing in the", "\"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data", "the database we need to save all child subscription instances for it. Args:", "underlying instances Returns: None \"\"\" children_relations = [] # Set the domain_model_attrs in", "fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name", "class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive,", "class for all product block models. This class should have been called SubscriptionInstanceModel.", "lifecycle specific product block definition can be created by subclassing the generic product", ">>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database.:", "elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] =", "just stop saving and return it so only its relation is saved #", "set() # For everything except abstract classes if cls.name is not None: register_specialized_type(cls,", "an instance var because its part of the API (we expose it to", "sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values,", "# We should not touch these themselves if self.subscription and subscription_instance.subscription_id != subscription_id:", ">>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__:", "only want fields that are on this class and not on the parent", "self.name: raise ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\") #", "inherit from ProductBlockModel which has this metaclass defined. You can find some examples", "None # pragma: no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle] = None,", "for rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db", "a new domain model is loaded from an existing subscription we also load", "and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of Subscription", "is cumbersome since that means creating a tree of product blocks. This is", "= product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name for fi in", "use this file except in compliance with the License. # You may obtain", "= field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def", "resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if", "def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes. This helper is", "if description is None: description = f\"Initial subscription of {product.description}\" subscription_id = uuid4()", "end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs} instances", "instances Returns: None \"\"\" children_relations = [] # Set the domain_model_attrs in the", "Define a product block: >>> class BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] =", "and database models match which would be done during testing... \"\"\" product_db =", "new domain model from instance while changing the status. This makes sure we", "good way to test for this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception:", "in instance_values: # check the type of the siv in the instance and", "def __init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any", "# pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag:", "list_field_names.add(field_name) for siv in instance_values: # check the type of the siv in", "be used directly in the class definition. Instead a new product block model", "doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] = set()", "for field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in resource_types", "def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, ) ->", "missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name] =", "product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] =", "is not valid for lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances", "instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value # Make sure values are sorted. This already", "# doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID", "# Copy generic argument (SI) if not set explicitly # This makes a", "similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make", "status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to", "is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if val: if siv: siv.value =", "current_value = current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return", "its relation is saved # We should not touch these themselves if self.subscription", "new domain model is created that is not loaded from an existing subscription.", "from relation (not wanted when loading product blocks directly related to subscriptions) Returns:", "children = self._save_instances(subscription_id, status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return", "from database Returns: Dict of fields to use for constructor \"\"\" instance_values_dict: State", "product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id))", "the siv in the instance and act accordingly: only lists and scalar values", "example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" # Fill values from actual subscription if", "status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi", "of assuptions about the internals of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]:", "return data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str,", "instances. Returns: A dict with instances to pass to the new model \"\"\"", "necessary. However when it is set, it is necessary to filter through instances", "None ), \"Product block model has not been resolved. Unable to continue\" instances[product_block_field_name]", "are saved and a dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = []", "pass to the new model \"\"\" if skip_keys is None: skip_keys = []", "constraints match subscription_id: Optional subscription id needed if this is a new model", "-> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if is_base or lifecycle:", "Subscription instances with parent relations for parent in subscription_instance.parents: if ( parent.subscription !=", "not None: register_specialized_type(cls, lifecycle) # Add ourself to any super class. That way", "field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None: pass else:", ") status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to prevent cyclic", "represented as dataclasses with pydantic runtime validation. Different stages of a subscription lifecycle", "subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model", "product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter(", "def __call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return", "is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None:", "current_values_dict[field_name]): if val: if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val))", "no mutate validate_all = True # pragma: no mutate arbitrary_types_allowed = True #", "have parent relations to those if not match_domain_attr: return True attr_names = {", "product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name,", "class and need not to be defined on the others Create a new", "instance and act accordingly: only lists and scalar values supported resource_type_name = siv.resource_type.resource_type", "status {status} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff", "no mutate arbitrary_types_allowed = True # pragma: no mutate product_id: UUID name: str", "product block based on a subscription instance from the database. This function is", "\"SubscriptionModel\": # status can be none if created during change_lifecycle if status and", "cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: # Abstract class,", "the others Create a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) #", "description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} # pragma: no mutate", "database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls,", "name. This needs to be an instance var because its part of the", "= {cls.name} ProductBlockModel.registry[cls.name] = cls elif lifecycle is None: # Abstract class, no", "for this domain model. When a domain model is saved to the database", "Make sure product block stuff is already set if new is the first", "resource_type = resource_types[field_name] value = getattr(self, field_name) if value is None: continue if", "customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore", "speficic instance. \"\"\" if not cls.__base_type__: # Import here to prevent cyclic imports", "class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription instance models conform to the", "data = other.dict() for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = []", "subscription_id db.session.flush() # Everything is ok, make sure we are of the right", "sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT and returns", "from operator import attrgetter from sys import version_info from typing import TYPE_CHECKING, Any,", "product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] =", "cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"],", "blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model,", "We are unable to detect which type to intialise and Union types always", "is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always", "instance is missing in the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name ==", "function iterates through the subscription instances and stores the domain model attribute in", "through instances depending on that attribute. Args: instance: child instance Returns: Boolean of", "this class and not on the parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else:", "missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k, v in", "value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], )", "lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore", "Boolean of match. \"\"\" # We don't match on the product_blocks directly under", "flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), ) ) ) product_block_model =", "validate_all = True # pragma: no mutate arbitrary_types_allowed = True # pragma: no", "grouped_instances = {k: list(g) for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str)", "status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") label = subscription_instance.label instance_values", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list =", "Optional, Set, Tuple, Type, TypeVar, Union from uuid import UUID, uuid4 import structlog", "if instance.product_block.name == field_type.name: product_block_model = field_type assert ( # noqa: S101 product_block_model", "status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) sub = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances)", "Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for", "bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__(lifecycle=lifecycle,", "for field_name, field_type in cls._product_block_fields_.items(): if is_list_type(field_type): data[field_name] = [] for item in", "is not always necessary. However when it is set, it is necessary to", "ProductBlockTable object through the `product_block_name` that is given as class keyword argument. Define", "in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id,", "import first, flatten, one, only from pydantic import BaseModel, Field, ValidationError from pydantic.fields", "\"\"\"Save the subscription to the database.\"\"\" specialized_type = lookup_specialized_type(self.__class__, self.status) if specialized_type and", "instance of abstract class. Use one of {self.__names__}\") # Would have been nice", "on the class to skip when creating dummy instances. Returns: A dict with", "a list field of ProductBlockModels without limits gets an empty list default_value =", "logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values(", "self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in resource_types ), f\"Domain model {self.__class__}", "the database. This is only needed to check if the domain model and", "TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists", "import ModelMetaclass from pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm", "return it so only its relation is saved # We should not touch", "lifecycle_status) if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type", "subscription instances for it. This function does that. Args: db_instances: list of database", "it just before we instantiate the instance if not hasattr(self, \"product_block_id\"): product_block =", "domain model attribute in the hierarchy relationship. Args: subscription_instance_mapping: a mapping of the", "fixed_inputs_in_db = {fi.name for fi in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db =", "also create all subscription instances for it. This function does that. Args: skip_keys:", "cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model = other._db_model return model @classmethod def", "_set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the", "subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a new empty product block. We", "else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"),", "models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block:", "SURF. # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this is a \"foreign\"", "status can be none if created during change_lifecycle if status and not issubclass(cls,", "a lifecycle specific product block definition can be created by subclassing the generic", "data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]:", "hierarchy relationship. Args: subscription_instance_mapping: a mapping of the domain model attribute a underlying", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all common", "exception and there is no good way to test for this try: is_constrained_list", "= [] list_field_names.add(field_name) for siv in instance_values: # check the type of the", "in the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for index, instance", "the domain_model_attrs in the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable for", "product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for", "instance models conform to the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if", "# Fill values from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance:", "so only its relation is saved # We should not touch these themselves", "already happens when they come from the db. # However newly created SubscriptionInstances", "None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model =", "for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type =", "return self._db_model SI = TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand", "instance values for this instance. Args: status: current SubscriptionLifecycle to check if all", "name in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name]", "pydantic runtime validation. Different stages of a subscription lifecycle could require different product", "subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance # noqa: S101 if not", "is valid only for `ACTIVE` And `BlockInactive` for all other states. `product_block_name` must", "saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances.", ".selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status,", "def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined on", "limits gets an empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value =", "__names__: Set[str] name: Optional[str] product_block_id: UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]]", "Optional[datetime] = None, note: Optional[str] = None, ) -> S: \"\"\"Use product_id (and", "product block model types. This strips any List[..] or Optional[...] types. \"\"\" result", "# pragma: no mutate note: Optional[str] = None # pragma: no mutate def", "is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block:", "db_model = SubscriptionInstanceTable( product_block_id=cls.product_block_id, subscription_instance_id=subscription_instance_id, subscription_id=subscription_id, ) db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances,", "from more_itertools import first, flatten, one, only from pydantic import BaseModel, Field, ValidationError", "The subscription id status: SubscriptionLifecycle of subscription to check if models match Returns:", "missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_)", "new empty subscription.\"\"\" # Caller wants a new instance and provided a product_id", ") -> S: \"\"\"Create new domain model from instance while changing the status.", "support this a lifecycle specific product block definition can be created by subclassing", "sub.description = self.description sub.status = self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date", "created that is not loaded from an existing subscription. We also create all", "cls.__names__ = set() # For everything except abstract classes if cls.name is not", "specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle", "set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model", "from pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload from orchestrator.db import (", "saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for product_block_field, product_block_field_type in", "block based on a subscription instance from the database. This function is similar", "tree of subscription instances and seperately saving all instance values for this instance.", "with the License. # You may obtain a copy of the License at", "= {} for product_block_field, product_block_field_type in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type):", "created by subclassing the generic product block with keyword argument 'lifecycle' and overriding", "cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__()", "-> SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def", "mutate insync: bool = False # pragma: no mutate start_date: Optional[datetime] = None", "import datetime from itertools import groupby, zip_longest from operator import attrgetter from sys", "if created during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls}", "- fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model,", "data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is", "SI = TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create", "it so only its relation is saved # We should not touch these", "(and customer_id) to return required fields of a new empty subscription.\"\"\" # Caller", "product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type:", "That way we can match a superclass to an instance when loading for", ") from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__)", "subscription instance models conform to the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items():", "do this in __init_subclass__ but that runs outside the app context so we", "field_type assert ( # noqa: S101 product_block_model is not None ), \"Product block", "What's left should be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def", "str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__( cls, *,", "insync: bool = False, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, note:", "Calculate what to remove instances_set = {instance.subscription_instance_id for instance in sub.instances} for instance_id", ") raise def save(self) -> None: \"\"\"Save the subscription to the database.\"\"\" specialized_type", "status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance =", "requires specialized type {specialized_type!r}, was: {type(self)!r}\" ) # Actually save stuff subscription_instance.label =", "assuptions about the internals of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls", "self._db_model = subscription_instance else: subscription_instance = self._db_model # We only need to add", "status: Optional[SubscriptionLifecycle] = None, ) -> B: \"\"\"Create a product block based on", "the right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type):", "DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError:", "product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if product_block_db", "constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items =", "@property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent the product as", "database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] )", "ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue", "law or agreed to in writing, software # distributed under the License is", "import UUID, uuid4 import structlog from more_itertools import first, flatten, one, only from", "Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type))", "skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances.", "old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status)", "sorted. This already happens when they come from the db. # However newly", "ProductTable Blocks are represented as dataclasses with pydantic runtime validation. Different stages of", "make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type", "cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type:", "ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi", "defines a subscription model with two different contraints based on lifecycle. `Subscription` is", "issubclass does not work on typing types is_product_block_field = False # We only", "value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value,", "10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {} else: #", "Returns: Dict of fields to use for constructor \"\"\" instance_values_dict: State = {}", "list(g) for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def", "subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, )", "product_blocks directly under subscriptions. They don't have parent relations to those if not", "to check if models match match_domain_attr: Match domain attribute from relation (not wanted", "or Optional[...] types. \"\"\" result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if", "new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) ->", "str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field:", "check the type of the siv in the instance and act accordingly: only", "no mutate product_id: UUID name: str description: str product_type: str tag: str status:", "\"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model from instance while", "selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type,", "fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for product_block_in_model", "with instances which are saved and a dict with direct children \"\"\" saved_instances:", "product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db", "bool: \"\"\" Match domain model attributes. This helper is necessary to filter through", ") else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only(", "if is_list_type(field_type): data[field_name] = [] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status,", "from ProductBlockModel which has this metaclass defined. You can find some examples in:", "All product blocks are related to a database ProductBlockTable object through the `product_block_name`", "= self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush() # Sends INSERT", "datetime import datetime from itertools import groupby, zip_longest from operator import attrgetter from", "in compliance with the License. # You may obtain a copy of the", "are unable to detect which type to intialise and Union types always cross", "subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id assert subscription_instance_id # noqa: S101 assert subscription_instance # noqa:", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "str This example defines a product_block with two different contraints based on lifecycle.", "mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable", "might not have the correct order for field_name in list_field_names: instance_values_dict[field_name] = sorted(instance_values_dict[field_name])", "parent if is_product_block_field: cls._product_block_fields_[field_name] = field_type else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances(", "# pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all", "missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name) if value is", ") -> B: \"\"\"Create new domain model from instance while changing the status.", "on lifecycle. `Block` is valid only for `ACTIVE` And `BlockInactive` for all other", "model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] =", "status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is", "product block instances. This metaclass is used to make sure the class contains", "product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model,", "other states. `product_type` must be defined on the base class and need not", "sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left should be removed", "is necessary to filter through all relations in a subscription. Not all subscriptions", "new empty product block. We need to use this instead of the normal", "new model Returns: List of saved instances \"\"\" if not self.name: raise ValueError(f\"Cannot", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from", "else: value = getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name]", "v in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children,", "raise ValueError(f\"Cannot create instance of abstract class. Use one of {self.__names__}\") # Make", "return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property def parents(self) ->", "= uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date,", "of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not", "database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model: SubscriptionTable =", "if ( parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError(", "subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable:", "= nowtz() model = cls(**data) model._db_model = other._db_model return model @classmethod def from_subscription(cls:", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", ") -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product block model types. This", "Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class", "field_type = product_block_field_type result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls: Type) ->", "except TypeError: # issubclass does not work on typing types is_product_block_field = False", "pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args:", "whole tree of subscription instances and seperately saving all instance values for this", "= SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription)", "empty subscription.\"\"\" # Caller wants a new instance and provided a product_id and", "Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new domain model is created", "product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None: description =", "Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new domain", "for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not", "if product_block_name is not None: # This is a concrete product block base", "mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle:", "class or a specific lifecycle version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__", "dont have it. In practice it is always set name: str subscription_instance_id: UUID", "is_product_block_field = False # We only want fields that are on this class", "bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this", "and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag,", "valid for lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances", "of fields to use for constructor \"\"\" instance_values_dict: State = {} list_field_names =", "in get_args(product_block_field_type) ), ) ) ) product_block_model = None if instance is None:", "handled OK if is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values: #", "superclass to an instance when loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel):", "This function is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>>", "for pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model", "= self.description sub.status = self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date =", "getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models: saved, child", "current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items(): assert ( #", "this domain model. When a new domain model is loaded from an existing", "to detect which type to intialise and Union types always cross subscription boundaries.\"", "\"Product block model has not been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db(", "transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id,", "SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]):", "domain model and those on product blocks in the database. This is only", "status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE:", "cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product block stuff is already", "instance in instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save a", "be done during testing... \"\"\" if not cls.name: # This is a superclass", "domain model from instance while changing the status. This makes sure we always", "= make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between", "is None: continue if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if val:", "= self._save_instances(subscription_id, status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances", "cls(**data) model._db_model = other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr])", "flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance", "= fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None,", "model\" ) @classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all", "block model has not been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance,", "pass to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def", "the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable)", "new empty product block >>> example1 = BlockInactive() # doctest:+SKIP Create a new", "< 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {} else:", "= None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs)", "# This is a superclass we can't check that return {} product_block_db =", "product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances:", ">>> class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass", "not loaded from an existing subscription. We also create all subscription instances for", "for the specific language governing permissions and # limitations under the License. from", "is ok, make sure we are of the right class specialized_type = lookup_specialized_type(self.__class__,", "only its relation is saved # We should not touch these themselves if", "to intialise and Union types always cross subscription boundaries.\" ) else: product_block_model =", "domain model and database models match which would be done during testing... \"\"\"", "\"\"\"Save non product block fields (instance values). Returns: List of database instances values", "API (we expose it to the frontend) # Is actually optional since abstract", "def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status:", ") raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save", "B: \"\"\"Create a product block based on a subscription instance from the database.", "# Make sure we have a valid subscription instance database model subscription_instance: SubscriptionInstanceTable", "\"\"\"Check if type is a constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>>", "of Subscription with depending subscriptions: {list(map(lambda instance: instance.subscription.description, subscription_instance.parents))}\" ) # If this", "customer_id) to return required fields of a new empty subscription.\"\"\" # Caller wants", "... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws", "= ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children} if product_block_db", "children_relations = [] # Set the domain_model_attrs in the database for domain_model_attr, instances", "S101 product_block_model is not None ), \"Product block model has not been resolved.", "subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create a new instance based", "= sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status =", "Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in", "SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from", "for it. This function does that. Args: db_instances: list of database models to", "i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k, g in", "data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data)", "if constrainedlist has minimum, return that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating", "Everything is ok, make sure we are of the right class specialized_type =", "lifecycle: if isinstance(product_block_field_type, tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if", "for all other states. `product_type` must be defined on the base class and", "in a subscription. Not all subscriptions have a domain model attribute that is", "None ... str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int", "and store a list of resource_type fields and product block fields.\"\"\" cls._non_product_block_fields_ =", "product block fields (instance values). Returns: List of database instances values to save", "it. This function does that. Args: db_instances: list of database models to load", "grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), ) ) ) product_block_model = None", "default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError(", "import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data", "T = TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma:", "# type: ignore **sub_instances, # type: ignore ) model._db_model = subscription_instance return model", "Is actually optional since abstract classes dont have it. In practice it is", "blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic", "in { \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v", "the instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id =", ") except TypeError: # issubclass does not work on typing types is_product_block_field =", "different contraints based on lifecycle. `Subscription` is valid only for `ACTIVE` And `SubscriptionInactive`", "wants a new instance and provided a product_id and customer_id product_db = ProductTable.query.get(product_id)", "instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) )", "and not is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types: if f_type.name ==", "def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save", "= fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\",", "= { relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr } # We can", "be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self) -> SubscriptionTable:", "not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save", "is None: raise ValueError(\"Required subscription instance is missing in the database\") for field_type", "False # We only want fields that are on this class and not", "= nowtz() if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz()", "subscription models. Define a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ...", "in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model =", "cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore", "elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must", "correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None: \"\"\"Save the", "all subscription instances for it. This function does that. Args: db_instances: list of", "product_block_model in product_block_models: saved, child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list", "and scalar values supported resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else:", "minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate", "= None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, ) -> B:", "\"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict() for field_name, field_type", "kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model class\", # pragma: no mutate", "Returns: List of database instances values to save \"\"\" resource_types = {rt.resource_type: rt", "\"\"\"Save the current model instance to the database. This means saving the whole", "if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else:", "-> None: \"\"\"Make and store a list of resource_type fields and product block", "@classmethod def from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle", "that attribute. Args: instance: child instance Returns: Boolean of match. \"\"\" # We", "always have a speficic instance. \"\"\" if not cls.__base_type__: # Import here to", "database as a dataclass.\"\"\" class Config: validate_assignment = True # pragma: no mutate", "in all required values. That is cumbersome since that means creating a tree", "cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type", "all required values. That is cumbersome since that means creating a tree of", "is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger =", "== value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] =", "the status. This makes sure we always have a specific instance.. \"\"\" if", "list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product block stuff is already set", "\"\"\"Represent the product as defined in the database as a dataclass.\"\"\" class Config:", "of a subscription lifecycle could require different product block definition. Mainly to support", "-> B: \"\"\"Create a new empty product block. We need to use this", "SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz", "subscription return model except ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs,", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif is_union_type(field_type) and not is_optional_type(field_type): field_types", "set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product", "resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if product_block_db else", ") sub_instances, children = self._save_instances(subscription_id, status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance,", "cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description:", "pragma: no mutate def _fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot create", "subscription return model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, )", "subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self) -> SubscriptionInstanceTable: return self._db_model @property", "ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def", "False, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, note: Optional[str] = None,", "elif lifecycle is None: # Abstract class, no product block name cls.name =", "for all product block models. This class should have been called SubscriptionInstanceModel. ProductTable", "Optional[str] product_block_id: UUID description: str tag: str registry: Dict[str, Type[\"ProductBlockModel\"]] = {} #", "domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name", "database. This function iterates through the subscription instances and stores the domain model", "instance values from database Returns: Dict of fields to use for constructor \"\"\"", "status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle", "fields (instance values). Args: instance_values: List of instance values from database Returns: Dict", "defined in the database as a dataclass.\"\"\" class Config: validate_assignment = True #", "continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type):", "current SubscriptionLifecycle to check if all constraints match subscription_id: Optional subscription id needed", "in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The", "cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other,", "no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\",", "UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to", "and seperately saving all instance values for this instance. Args: status: current SubscriptionLifecycle", "product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list( filter(", "# type:ignore # Copy generic argument (SI) if not set explicitly # This", "= product_block_field_type result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls: Type) -> None:", "those on product blocks in the database. This is only needed to check", "example1 = BlockInactive() # doctest:+SKIP Create a new instance based on a dict", "in instance.parent_relations if relation.domain_model_attr } # We can assume true is no domain_model_attr", "is only needed to check if the domain model and database models match", "List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance values). Returns: List", "product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model in product_block_models: saved, child =", "internals of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if", "SubscriptionInstanceTable = PrivateAttr() # Product block name. This needs to be an instance", "not suitable for the lifecycle status ({lifecycle_status}) of this model\" ) @classmethod def", "subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\"", "necessary to filter through instances depending on that attribute. Args: instance: child instance", "\"\"\" # Fill values from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if", "# For everything except abstract classes if cls.name is not None: register_specialized_type(cls, lifecycle)", "{} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k:", "in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if", "= None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This", "@classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True, )", "= {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type:", "this file except in compliance with the License. # You may obtain a", "set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model", "be `Optional` when calling `.new().` We are unable to detect which type to", "Optional[str] = None # pragma: no mutate def __new__(cls, *args: Any, status: Optional[SubscriptionLifecycle]", "a concrete product block base class (so not a abstract super class or", "SubscriptionInstanceTable: return self._db_model @property def parents(self) -> List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self)", "= lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"]", "relation (not wanted when loading product blocks directly related to subscriptions) Returns: A", "field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status,", "is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger", "in product_block_model.__names__), ) ) ) if is_optional_type(product_block_field_type) and instance is None: instances[product_block_field_name] =", "no mutate start_date: Optional[datetime] = None # pragma: no mutate end_date: Optional[datetime] =", "missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else", "metaclass defined. You can find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name:", "cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if data[\"start_date\"] is None and status ==", "if cls.name is not None: register_specialized_type(cls, lifecycle) # Add ourself to any super", "ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name. This needs", "lifecycle) @classmethod def diff_product_block_in_database(cls) -> Dict[str, Any]: \"\"\"Return any differences between the attrs", "tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model)))", "# So now we do it just before we instantiate the instance if", "the `product_block_name` that is given as class keyword argument. Define a product block:", "status=status) for instance in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not", "in the class definition. Instead a new product block model should inherit from", "= lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model =", "type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status", "fields of a new empty subscription.\"\"\" # Caller wants a new instance and", "status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore", "_is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable]", "When a new domain model is loaded from an existing subscription we also", "item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other,", "is_list_type(field_type): instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values: # check the type", "def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save", "all the product block model types. This strips any List[..] or Optional[...] types.", ">>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>>", "session. db.session.refresh(subscription_instance) # Block unsafe status changes on domain models that have Subscription", "type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not suitable for", "mutate arbitrary_types_allowed = True # pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None #", "= ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag = product_block.tag", "an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product", "status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool = False #", "is_constrained_list T = TypeVar(\"T\") # pragma: no mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") #", "exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok, make sure we", "This example defines a subscription model with two different contraints based on lifecycle.", "if not issubclass(product_block_field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type for", "created during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is", "Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model. When a domain model", "from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type,", "product_block with two different contraints based on lifecycle. `Block` is valid only for", "True # pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate __base_type__:", "are of the right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not", "match match_domain_attr: Match domain attribute from relation (not wanted when loading product blocks", "\"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if", "# type: ignore ) model._db_model = subscription_instance return model except ValidationError: logger.exception( \"Subscription", "detect which type to intialise and Union types always cross subscription boundaries.\" )", "subscription to check if models match match_domain_attr: Match domain attribute from relation (not", "not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore elif is_list_type(product_block_field_type) or", "order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *, subscription_id: UUID,", "the whole tree of subscription instances and seperately saving all instance values for", "self._set_instance_domain_model_attrs(subscription_instance, children) return sub_instances + [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return", "self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush() #", "field_types: if f_type.name == value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id)", "is_base: cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls,", "status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model from instance while changing", "ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List", "that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no", "of `typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not", "check if the domain model and database models match which would be done", "= subscription_instance else: subscription_instance = self._db_model # We only need to add to", "of fields on the class to skip when creating dummy instances. Returns: A", "= [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items():", "direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] = {} for", "be one in the type if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"),", "fields to use for constructor \"\"\" instance_values_dict: State = {} list_field_names = set()", "uuid4() # Make sure product block stuff is already set if new is", "only from pydantic import BaseModel, Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main", "instance_values_dict @classmethod def _from_other_lifecycle( cls: Type[B], other: \"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, )", "# pragma: no mutate product_id: UUID name: str description: str product_type: str tag:", "dataclasses with pydantic runtime validation. Different stages of a subscription lifecycle could require", "def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict()", "default_value = None elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be `Optional`", "None, **kwargs: Any) -> \"SubscriptionModel\": # status can be none if created during", "block: ProductBlockModel This example defines a subscription model with two different contraints based", "and those on product blocks in the database. This is only needed to", "instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def _load_instances( cls,", "ProductTable.query.get(product_id) product_blocks_in_db = {pb.name for pb in product_db.product_blocks} if product_db else set() product_blocks_types_in_model", "a domain model attribute that is set as it is not always necessary.", "relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr } # We can assume true", "value is None: continue if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if", "- product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_) fixed_inputs_in_db = {fi.name", "status=product_db.status, ) if description is None: description = f\"Initial subscription of {product.description}\" subscription_id", "subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date,", "product block definition. Mainly to support mandatory fields when a subscription is active.", "in cls._non_product_block_fields_.items(): # Ensure that empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name]", "way to test for this try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: #", "= field_type return result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and store", "tuple): # There may only be one in the type if it is", "on {field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this model\"", "int_field: int ... str_field: str This example defines a product_block with two different", "related to a database ProductBlockTable object through the `product_block_name` that is given as", "(based on {product_block_field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this", "self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def __call__(self, *args: Any,", "= cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only be one", "data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other, field_name) if is_optional_type(field_type): field_type", "fields on the class to skip when creating dummy instances. Returns: A dict", "cls.name: # This is a superclass we can't check that return {} product_block_db", "bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate", "be an instance var because its part of the API (we expose it", "not cls.__base_type__: # Import here to prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY", "== field_type.name: product_block_model = field_type assert ( # noqa: S101 product_block_model is not", "the others Create a new empty product block >>> example1 = BlockInactive() #", "raise ValueError(\"Required subscription instance is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance,", "this instead of the normal constructor because that assumes you pass in all", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import", "for constructor \"\"\" instance_values_dict: State = {} list_field_names = set() # Set default", "be none if created during change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)):", "BlockInactive(ProductBlockModel, product_block_name=\"Virtual Circuit\"): ... int_field: Optional[int] = None ... str_field: Optional[str] = None", "have been called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with pydantic runtime", "a product_block with two different contraints based on lifecycle. `Block` is valid only", "if f_type.name == value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else:", "# type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls}", "= self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note =", "if not set explicitly # This makes a lot of assuptions about the", "return False return is_constrained_list T = TypeVar(\"T\") # pragma: no mutate S =", ") sub.instances = saved_instances # Calculate what to remove instances_set = {instance.subscription_instance_id for", "in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple): for field_type", "from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP \"\"\" product: ProductModel customer_id: UUID _db_model:", ">>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>>", "Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example defines a subscription model", "model and database models match which would be done during testing... \"\"\" product_db", "} if diff: missing_data[cls.name] = diff return missing_data @classmethod def new(cls: Type[B], subscription_id:", "status, subscription_id) ) else: value = getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type))", "way we can match a superclass to an instance when loading for klass", "current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa:", "instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for", "# pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list", "in the type if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) #", "of subscription to check if models match Returns: A list with instances which", "elif is_union_type(product_block_field_type): raise ValueError( \"Union Types must always be `Optional` when calling `.new().`", "if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else:", "lifecycle version) cls.name = product_block_name cls.__base_type__ = cls cls.__names__ = {cls.name} ProductBlockModel.registry[cls.name] =", "f_type.name == value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name]", "children_relations.append(relation) subscription_instance.children_relations = children_relations def save( self, *, subscription_id: UUID, status: SubscriptionLifecycle, )", "if child subscription instance models conform to the same lifecycle for product_block_field_name, product_block_field_type", "domain model. When a new domain model is loaded from an existing subscription", "attributes. This helper is necessary to filter through all relations in a subscription.", "instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left should be removed for instance", "{status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]] =", "SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs:", "specific language governing permissions and # limitations under the License. from collections import", ") -> B: \"\"\"Create a product block based on a subscription instance from", "diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined", "UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync:", "instances \"\"\" if not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use", "import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type,", "sure we are of the right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type", "required by applicable law or agreed to in writing, software # distributed under", "= db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 =", "mutate end_date: Optional[datetime] = None # pragma: no mutate note: Optional[str] = None", "product blocks are related to a database ProductBlockTable object through the `product_block_name` that", "product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, )", "doctest:+SKIP ... block: ProductBlockModel This example defines a subscription model with two different", "else: cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] =", "Make sure we do not use a mapped session. db.session.refresh(subscription_instance) # Block unsafe", "to the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status", "based on a dict in the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP", "cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label,", "data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self, subscription_id: UUID, status:", "sure we do not use a mapped session. db.session.refresh(subscription_instance) # Block unsafe status", "cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model", "# type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] =", "Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model)))", "**kwargs: Any) -> B: \"\"\"Create a new empty product block. We need to", "subscription_instance_id: Optional[UUID] = None, subscription_instance: Optional[SubscriptionInstanceTable] = None, status: Optional[SubscriptionLifecycle] = None, )", "`typing` if \"__orig_bases__\" in cls.__dict__ and cls.__dict__[\"__orig_bases__\"]: generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls,", "and instance is None: instances[product_block_field_name] = None elif not is_optional_type(product_block_field_type) and instance is", "Returns: A dict with instances to pass to the new model \"\"\" instances:", "is not None: # This is a concrete product block base class (so", "SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description,", "min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws exception", "return sub_instances + [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property", "no mutate insync: bool = False # pragma: no mutate start_date: Optional[datetime] =", "status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain", "SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models. Define a subscription model: >>>", "*args: Any, status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": # status can", "set explicitly # This makes a lot of assuptions about the internals of", "status: SubscriptionLifecycle of subscription to check if models match match_domain_attr: Match domain attribute", "= str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self,", "if not cls.__base_type__: # Import here to prevent cyclic imports from orchestrator.domain import", "product_block.tag def __call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name", "is saved # We should not touch these themselves if self.subscription and subscription_instance.subscription_id", "for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls(", "model. When a domain model is saved to the database we need to", "self.tag = product_block.tag def __call__(self, *args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"]", "base class (so not a abstract super class or a specific lifecycle version)", "... int_field: Optional[int] = None ... str_field: Optional[str] = None >>> class Block(BlockInactive,", "class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription", "To retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry:", "False >>> class ListType(ConstrainedList): ... min_items = 1 >>> _is_constrained_list_type(ListType) True \"\"\" #", "1 >>> _is_constrained_list_type(ListType) True \"\"\" # subclass on typing.List throws exception and there", "models conform to the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle:", "# Scalar field of a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name]", "provided a product_id and customer_id product_db = ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name,", "= True # pragma: no mutate product_id: UUID name: str description: str product_type:", "same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle:", "status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict() for field_name, field_type in", "List[SubscriptionInstanceTable]: return self._db_model.parents @property def children(self) -> List[SubscriptionInstanceTable]: return self._db_model.children class ProductModel(BaseModel): \"\"\"Represent", "directly in the class definition. Instead a new product block model should inherit", "a superclass to an instance when loading for klass in cls.__mro__: if issubclass(klass,", "all instance values for this instance. Args: status: current SubscriptionLifecycle to check if", "selectinload from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, )", "is not None ), \"Product block model has not been resolved. Unable to", "suitable for the lifecycle status ({lifecycle_status}) of this model\" ) else: specialized_type =", "def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy generic argument", "if instance is None: raise ValueError(\"Required subscription instance is missing in the database\")", "= str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict:", "SubscriptionInstanceTable) -> bool: \"\"\" Match domain model attributes. This helper is necessary to", "# Is actually optional since abstract classes dont have it. In practice it", "missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db missing_product_blocks_in_model = product_blocks_in_db - product_blocks_in_model fixed_inputs_model = set(cls._non_product_block_fields_)", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "definition can be created by subclassing the generic product block with keyword argument", "subscription_id: UUID, status: SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance", "import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif", "!= self.subscription_id: raise ValueError( \"Attempting to save a Foreign `Subscription Instance` directly below", "does not match the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value", "saving all instance values for this instance. Args: status: current SubscriptionLifecycle to check", "Any ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if is_base: cls.__base_type__ = cls if is_base", "with instances to pass to the new model \"\"\" if skip_keys is None:", "product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {}", "subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs =", "in subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ):", "= None # type:ignore cls.__names__ = set() # For everything except abstract classes", "resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if product_blocks_types_in_model", "in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values", "\"ProductBlockModel\", status: SubscriptionLifecycle, subscription_id: UUID, ) -> B: \"\"\"Create new domain model from", "since that means creating a tree of product blocks. This is similar to", "This is not allowed.\" ) sub.instances = saved_instances # Calculate what to remove", "product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type)", "Would have been nice to do this in __init_subclass__ but that runs outside", "... block: ProductBlockModel This example defines a subscription model with two different contraints", "SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types import", "is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type return result", "super class. That way we can match a superclass to an instance when", "ignore model._db_model = db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str,", "pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel):", "lifecycle) @classmethod def diff_product_in_database(cls, product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences between", "subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok, make sure we are of", "is active. To support this a lifecycle specific product block definition can be", "lifecycle) # Add ourself to any super class. That way we can match", "UUID) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined on the", "model._db_model = other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) ->", "save a Foreign `Subscription Instance` directly below a subscription. This is not allowed.\"", "# doctest:+SKIP Create a new instance based on a dict in the state:", "We should not touch these themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return", "{ \"missing_product_blocks_in_db\": missing_product_blocks_in_db, \"missing_product_blocks_in_model\": missing_product_blocks_in_model, \"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if", "`Subscription Instance` directly below a subscription. This is not allowed.\" ) sub.instances =", "customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore", "dict with direct children \"\"\" saved_instances: List[SubscriptionInstanceTable] = [] child_instances: Dict[str, List[SubscriptionInstanceTable]] =", "Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model. When a new domain", "change_lifecycle if status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid", "if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def diff_product_in_database(cls,", "a subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] =", "makes a lot of assuptions about the internals of `typing` if \"__orig_bases__\" in", "`from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() # Make sure product", "model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child", "= subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model = cls(", "not use a mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes on domain", "stuff subscription_instance.label = self.label subscription_instance.values = self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children =", "no mutate class DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all common Product", "This is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4()", "- product_blocks_in_model resource_types_model = set(cls._non_product_block_fields_) resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if", "{product.description}\" subscription_id = uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync,", "Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type", "is a \"foreign\" instance we just stop saving and return it so only", "else: if TYPE_CHECKING: annotations = {} else: # Only available in python >", "subscription instances for it. Args: subscription_id: The subscription id status: SubscriptionLifecycle of subscription", "ClassVar[Dict[str, Type[\"ProductBlockModel\"]]] # pragma: no mutate __names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description:", "field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type result[product_block_field_name] = field_type return result @classmethod", "in self._product_block_fields_.items(): product_block_models = getattr(self, product_block_field) if is_list_type(product_block_field_type): field_instance_list = [] for product_block_model", ">>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example defines a", "used to create product block instances. This metaclass is used to make sure", "UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this", "a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) # doctest:+SKIP \"\"\" registry: ClassVar[Dict[str, Type[\"ProductBlockModel\"]]]", "status and not issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for status", "subscription instance is missing in the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name", "status) if specialized_type and not isinstance(self, specialized_type): raise ValueError( f\"Lifecycle status {status} requires", "AssertionError( f\"The lifecycle status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based", "product_id: UUID name: str description: str product_type: str tag: str status: ProductLifecycle class", "to the session if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id", "orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status)", "is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list", "field_name, field_type in cls._non_product_block_fields_.items(): # Ensure that empty lists are handled OK if", "= SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls,", "# Everything is ok, make sure we are of the right class specialized_type", "subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel(", "= diff return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) ->", "SubscriptionLifecycle, ) -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to the database.", "# Abstract class, no product block name cls.name = None # type:ignore cls.__names__", "check if models match match_domain_attr: Match domain attribute from relation (not wanted when", "end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model", "`ACTIVE` And `BlockInactive` for all other states. `product_block_name` must be defined on the", "register_specialized_type(cls, lifecycle) # Add ourself to any super class. That way we can", "function does that. Args: skip_keys: list of fields on the class to skip", "of database instances values to save \"\"\" resource_types = {rt.resource_type: rt for rt", "missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks", "is not allowed.\" ) sub.instances = saved_instances # Calculate what to remove instances_set", "explicitly # This makes a lot of assuptions about the internals of `typing`", "# We don't match on the product_blocks directly under subscriptions. They don't have", "( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle,", "it still might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else: return False", "and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model = cls(**data) model._db_model = other._db_model", "Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None,", "changing the status. This makes sure we always have a speficic instance. \"\"\"", "_init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]:", "mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained lists of product blocks.\"\"\" def", "# you may not use this file except in compliance with the License.", "import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union", "= list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) ) product_block_model_list.extend(", "from_product_id( cls: Type[S], product_id: Union[UUID, UUIDstr], customer_id: Union[UUID, UUIDstr], status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL,", "product blocks directly related to subscriptions) Returns: A dict with instances to pass", "'lifecycle' and overriding its fields. All product blocks are related to a database", "means saving the whole tree of subscription instances and seperately saving all instance", "doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP", "product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type:", "Only available in python > 3.10 from inspect import get_annotations annotations = get_annotations(cls)", "superclass we can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db", "type: ignore ) model._db_model = subscription return model except ValidationError: logger.exception( \"Subscription is", "field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] =", "list field of ProductBlockModels without limits gets an empty list default_value = []", "# type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), product_blocks_types_in_model))) missing_product_blocks_in_db = product_blocks_in_model - product_blocks_in_db", "product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values =", "a abstract super class or a specific lifecycle version) cls.name = product_block_name cls.__base_type__", "not to be defined on the others Create a new empty product block", "status: Optional[SubscriptionLifecycle] = None, **kwargs: Any) -> \"SubscriptionModel\": # status can be none", "seperately saving all instance values for this instance. Args: status: current SubscriptionLifecycle to", "ValueError(f\"{cls} is not valid for lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values)", "status of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is", "a superclass we can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none()", "from actual subscription if subscription_instance_id: subscription_instance = SubscriptionInstanceTable.query.get(subscription_instance_id) if subscription_instance: subscription_instance_id = subscription_instance.subscription_instance_id", "- fixed_inputs_in_db missing_fixed_inputs_in_model = fixed_inputs_in_db - fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if", "else: # a list field of ProductBlockModels without limits gets an empty list", "# doctest:+SKIP To retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id) # doctest:+SKIP", "subscription instance is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status )", ") if subscription_instance: # Make sure we do not use a mapped session.", "it. In practice it is always set name: str subscription_instance_id: UUID owner_subscription_id: UUID", "@classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data =", "SubscriptionLifecycle, ) -> S: \"\"\"Create new domain model from instance while changing the", "product_block_model = one(get_args(product_block_field_type)) instance_list: List[SubscriptionInstanceTable] = list( filter( filter_func, flatten(grouped_instances.get(name, []) for name", "in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name in resource_types ), f\"Domain model", "owner_subscription_id: UUID label: Optional[str] = None def __init_subclass__( cls, *, product_block_name: Optional[str] =", "subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain model", "subscription_instance else: subscription_instance = self._db_model # We only need to add to the", "arbitrary_types_allowed = True # pragma: no mutate product_id: UUID name: str description: str", "create constrained lists of product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs)", "if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED: data[\"end_date\"] = nowtz() model =", "\"\"\" instance_values_dict: State = {} list_field_names = set() # Set default values for", "Args: instance_values: List of instance values from database Returns: Dict of fields to", "of subscription instances and seperately saving all instance values for this instance. Args:", "create instance of abstract class. Use one of {self.__names__}\") # Make sure we", "This helper is necessary to filter through all relations in a subscription. Not", "self._save_instances(self.subscription_id, self.status) for instances in child_instances.values(): for instance in instances: if instance.subscription_id !=", ") ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance, status=status) for instance in instance_list ) instances[product_block_field_name] = product_block_model_list", "domain model. When a domain model is saved to the database we need", "pragma: no mutate validate_all = True # pragma: no mutate arbitrary_types_allowed = True", "instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name", "in the state: >>> example2 = BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel", "cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__ = make_subscription_model_docstring(cls, lifecycle) @classmethod def", "self.product.product_id sub.customer_id = self.customer_id sub.description = self.description sub.status = self.status.value sub.insync = self.insync", "field_types = get_args(field_type) for f_type in field_types: if f_type.name == value.name: field_type =", "ValueError( \"Attempting to save a Foreign `Subscription Instance` directly below a subscription. This", "left should be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property def db_model(self)", "License for the specific language governing permissions and # limitations under the License.", "for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels without", "we need to save all child subscription instances for it. Args: subscription_id: The", "= PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate description: str =", "the attrs defined on the domain model and those on product blocks in", "-> S: \"\"\"Use a subscription_id to return required fields of an existing subscription.\"\"\"", "instance var because its part of the API (we expose it to the", "\"Subscription is not correct in database\", loaded_instance_values=instance_values, loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self,", "instance.subscription.description, subscription_instance.parents))}\" ) # If this is a \"foreign\" instance we just stop", "Optional[str] = None, ) -> S: \"\"\"Use product_id (and customer_id) to return required", "sub.status = self.status.value sub.insync = self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note", "resource_type_name = siv.resource_type.resource_type if resource_type_name in list_field_names: instance_values_dict[resource_type_name].append(siv.value) else: instance_values_dict[resource_type_name] = siv.value #", "instance.parent_relations if relation.domain_model_attr } # We can assume true is no domain_model_attr is", "list_field_names = set() # Set default values for field_name, field_type in cls._non_product_block_fields_.items(): #", "is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name]", "defined on the domain model and those on product blocks in the database.", "SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of Subscription with depending subscriptions: {list(map(lambda", "None) # What's left should be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush()", "lifecycle. `Block` is valid only for `ACTIVE` And `BlockInactive` for all other states.", "subscription_id: return [], subscription_instance self._db_model = subscription_instance else: subscription_instance = self._db_model # We", "\"\"\"Base class for domain models. Contains all common Product block/Subscription instance code \"\"\"", "the type if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type:", "[child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block", "typing.List throws exception and there is no good way to test for this", "\"License\"); # you may not use this file except in compliance with the", "subscription id needed if this is a new model Returns: List of saved", "self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of", "data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else: data[field_name] = None elif is_union_type(field_type) and not", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "issubclass(type, ConstrainedList) except Exception: # Strip generic arguments, it still might be a", "model attribute a underlying instances Returns: None \"\"\" children_relations = [] # Set", "List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model. When a new domain model", "example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database: >>>", "match which would be done during testing... \"\"\" product_db = ProductTable.query.get(product_id) product_blocks_in_db =", "ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type,", ") db.session.enable_relationship_loading(db_model) model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model =", "SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with pydantic runtime validation. Different stages", "db.session.flush() @property def db_model(self) -> SubscriptionTable: return self._db_model SI = TypeVar(\"SI\") # pragma:", "attribute that is set as it is not always necessary. However when it", "that assumes you pass in all required values. That is cumbersome since that", "\"missing_fixed_inputs_in_db\": missing_fixed_inputs_in_db, \"missing_fixed_inputs_in_model\": missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data = {}", "= cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description, status=status, insync=subscription.insync, start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances,", "return required fields of a new empty subscription.\"\"\" # Caller wants a new", "cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): # There may only be one in", "model._db_model = other._db_model return model @classmethod def from_db( cls: Type[B], subscription_instance_id: Optional[UUID] =", "-> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to the database. This means", "db.session.refresh(subscription_instance) # Block unsafe status changes on domain models that have Subscription instances", "return i.product_block.name sorted_instances = sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k, g", "the database. This function is similar to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB #", "not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description =", "set. return not attr_names or field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type", "List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model. When a domain model is", "ProductBlockModels without limits gets an empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel):", "of database models to load from status: SubscriptionLifecycle of subscription to check if", "is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self) -> None:", "field_name) if value is None: continue if is_list_type(field_type): for val, siv in zip_longest(value,", "a subscription_id to return required fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options(", "in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status] ): raise ValueError( f\"Unsafe status change of Subscription with depending subscriptions:", "Create a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id) # doctest:+SKIP Create", "subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances,", "abstract class. Use one of {self.__names__}\") # Would have been nice to do", "child instance Returns: Boolean of match. \"\"\" # We don't match on the", "definition. Mainly to support mandatory fields when a subscription is active. To support", ") missing_data_children: Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type:", "description: Optional[str] = None, insync: bool = False, start_date: Optional[datetime] = None, end_date:", "@classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return all the product", "= self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub) db.session.flush()", "# pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "need to use this instead of the normal constructor because that assumes you", "= True # pragma: no mutate arbitrary_types_allowed = True # pragma: no mutate", "cls._non_product_block_fields_[field_name] = field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None", "in writing, software # distributed under the License is distributed on an \"AS", "= PrivateAttr() # Product block name. This needs to be an instance var", "is None: description = f\"Initial subscription of {product.description}\" subscription_id = uuid4() subscription =", "this model\" ) @classmethod def _get_child_product_block_types( cls, ) -> Dict[str, Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]]]: \"\"\"Return", "that have Subscription instances with parent relations for parent in subscription_instance.parents: if (", "missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {} for product_block_in_model in product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database())", "that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb", "instance is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status ) return", "None: pass else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return", "defined. You can find some examples in: :ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str]", "and need not to be defined on the others Create a new empty", "else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping:", "missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data: Dict[str, Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple):", "mutate arbitrary_types_allowed = True # pragma: no mutate product_id: UUID name: str description:", "return model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) ->", "instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save a Foreign `Subscription", "list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) ) ) if", "expose it to the frontend) # Is actually optional since abstract classes dont", "only for `ACTIVE` And `BlockInactive` for all other states. `product_block_name` must be defined", "they come from the db. # However newly created SubscriptionInstances might not have", "generic_base_cls = cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] #", "keyword arguments in domain model class\", # pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), )", "the normal constructor because that assumes you pass in all required values. That", "else: saved, child = product_block_models.save(subscription_id=subscription_id, status=status) child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances", "subscription_id) else: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) return data def _save_instances( self, subscription_id:", "Any] = {} if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): for product_block_model in one(product_blocks_types_in_model): #", "tuple): for field_type in product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type):", "description=description, status=status, insync=insync, start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model", "{} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations", "_db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate description:", "already mapped object db.session.refresh(sub) self._db_model = sub sub.product_id = self.product.product_id sub.customer_id = self.customer_id", "from orchestrator.db import ( ProductBlockTable, ProductTable, SubscriptionInstanceRelationTable, SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from", "a new instance and provided a product_id and customer_id product_db = ProductTable.query.get(product_id) product", "class Config: validate_assignment = True # pragma: no mutate validate_all = True #", "can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name", "of the normal constructor because that assumes you pass in all required values.", "return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances. This", "key=keyfunc) grouped_instances = {k: list(g) for k, g in groupby(sorted_instances, keyfunc)} def match_domain_model_attr_if_possible(field_name:", "mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes on domain models that have", "Tuple[List[SubscriptionInstanceTable], Dict[str, List[SubscriptionInstanceTable]]]: \"\"\"Save subscription instances for this domain model. When a domain", "list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList): ... min_items = 1", "{field_type.__name__}) is not suitable for the lifecycle status ({lifecycle_status}) of this model\" )", "pragma: no mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription instance models", "should have been called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with pydantic", "ValueError(f\"{cls} is not valid for status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base:", "= other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S:", "List, Optional, Set, Tuple, Type, TypeVar, Union from uuid import UUID, uuid4 import", "def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is a constained list type.", "two different contraints based on lifecycle. `Block` is valid only for `ACTIVE` And", "= ProductTable.query.get(product_id) product = ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if", "**kwargs) if is_base: cls.__base_type__ = cls if is_base or lifecycle: register_specialized_type(cls, lifecycle) cls.__doc__", "mutate validate_all = True # pragma: no mutate arbitrary_types_allowed = True # pragma:", "\"\"\"Initialize default subscription instances. When a new domain model is created that is", "issubclass(cls, lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") fixed_inputs =", "product block stuff is already set if new is the first usage of", "if not sub: sub = self._db_model # Make sure we refresh the object", "self.name).one() self.product_block_id = product_block.product_block_id self.description = product_block.description self.tag = product_block.tag def __call__(self, *args:", "subscription boundaries.\" ) else: product_block_model = product_block_field_type # Scalar field of a ProductBlockModel", "is a superclass we can't check that return {} product_block_db = ProductBlockTable.query.filter(ProductBlockTable.name ==", "Args: skip_keys: list of fields on the class to skip when creating dummy", "types always cross subscription boundaries.\" ) else: product_block_model = product_block_field_type # Scalar field", "{ relation.domain_model_attr for relation in instance.parent_relations if relation.domain_model_attr } # We can assume", "ProductBlockTable.query.filter(ProductBlockTable.name == cls.name).one_or_none() product_blocks_in_db = {pb.name for pb in product_block_db.children} if product_block_db else", "= SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure we do not use", "tag: str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models.", "in attr_names return domain_filter for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if", "= None # pragma: no mutate note: Optional[str] = None # pragma: no", "cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in grouped_instances: if _is_constrained_list_type(product_block_field_type):", "ProductModel(BaseModel): \"\"\"Represent the product as defined in the database as a dataclass.\"\"\" class", "to pass to the new model \"\"\" instances: Dict[str, Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {}", "in instance_list ) instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance =", "uuid4() subscription = SubscriptionTable( subscription_id=subscription_id, product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note,", "A dict with instances to pass to the new model \"\"\" if skip_keys", "block fields (instance values). Args: instance_values: List of instance values from database Returns:", "cls elif lifecycle is None: # Abstract class, no product block name cls.name", "__names__: ClassVar[Set[str]] = set() product_block_id: ClassVar[UUID] description: ClassVar[str] tag: ClassVar[str] _db_model: SubscriptionInstanceTable =", "mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\") # pragma: no mutate class DomainModel(BaseModel): \"\"\"Base class", "Field, ValidationError from pydantic.fields import PrivateAttr from pydantic.main import ModelMetaclass from pydantic.types import", "-> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain model", "None \"\"\" children_relations = [] # Set the domain_model_attrs in the database for", "type is a constained list type. Example: >>> _is_constrained_list_type(List[int]) False >>> class ListType(ConstrainedList):", "all subscriptions have a domain model attribute that is set as it is", "None # pragma: no mutate note: Optional[str] = None # pragma: no mutate", "no mutate note: Optional[str] = None # pragma: no mutate def __new__(cls, *args:", "if product_block_db else set() missing_resource_types_in_db = resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db -", "if is_optional_type(field_type): field_type = first(get_args(field_type)) if value: data[field_name] = field_type._from_other_lifecycle(value, status, subscription_id) else:", ") -> Tuple[List[SubscriptionInstanceTable], SubscriptionInstanceTable]: \"\"\"Save the current model instance to the database. This", "instances. This metaclass is used to make sure the class contains product block", "only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), ) ) )", "= None ... str_field: Optional[str] = None >>> class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field:", "loaded_sub_instances=sub_instances, ) raise def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]:", "can assume true is no domain_model_attr is set. return not attr_names or field_name", "if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or", "conform to the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for", "lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle status of the type", "just before we instantiate the instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name", "if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id = product_block.product_block_id self.description", "resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db,", "defaultdict(list) for siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in", "status = SubscriptionLifecycle(subscription.status) if not cls.__base_type__: # Import here to prevent cyclic imports", "product_id=product_id, customer_id=customer_id, description=description, status=status.value, insync=insync, start_date=start_date, end_date=end_date, note=note, ) db.session.add(subscription) fixed_inputs = {fi.name:", "return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use a", "= saved_instances # Calculate what to remove instances_set = {instance.subscription_instance_id for instance in", "= field_type @classmethod def _init_instances( cls, subscription_id: UUID, skip_keys: Optional[List[str]] = None )", "status: SubscriptionLifecycle, match_domain_attr: bool = True, ) -> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription", "to save \"\"\" resource_types = {rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str,", "= TypeVar(\"SI\") # pragma: no mutate class SubscriptionInstanceList(ConstrainedList, List[SI]): \"\"\"Shorthand to create constrained", "Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is", "has not been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status )", "product_block_model = one(get_args(product_block_field_type)) default_value = product_block_field_type() # if constrainedlist has minimum, return that", "2.0 (the \"License\"); # you may not use this file except in compliance", "on that attribute. Args: instance: child instance Returns: Boolean of match. \"\"\" #", ".selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(subscription_id) product = ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag,", "lookup_specialized_type(cls, status)): raise ValueError(f\"{cls} is not valid for lifecycle {status}\") label = subscription_instance.label", "Type) -> bool: \"\"\"Check if type is a constained list type. Example: >>>", "DomainModel) or is_optional_type(field_type, DomainModel) or is_of_type(field_type, DomainModel) ) except TypeError: # issubclass does", "subscription_instance # noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__:", "field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type,", "a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"),", "values. That is cumbersome since that means creating a tree of product blocks.", "instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data", "the domain model attribute in the hierarchy relationship. Args: subscription_instance_mapping: a mapping of", "cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id) data[\"status\"] = status if", "instances[product_block_field_name] = default_value return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle,", "= field_instance_list elif ( is_optional_type(product_block_field_type) or is_union_type(product_block_field_type) ) and product_block_models is None: pass", "cls._non_product_block_fields_.items(): # Ensure that empty lists are handled OK if is_list_type(field_type): instance_values_dict[field_name] =", "sub_instances, children = self._save_instances(subscription_id, status) # Save the subscription instances relations. self._set_instance_domain_model_attrs(subscription_instance, children)", "gets an empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None", "default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value return instances @classmethod def _load_instances( cls, db_instances:", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "instance for instance in sub.instances} saved_instances, child_instances = self._save_instances(self.subscription_id, self.status) for instances in", "if not cls.name: # This is a superclass we can't check that return", "True \"\"\" # subclass on typing.List throws exception and there is no good", "diff return missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B:", "in the database\") for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model =", "Caller wants a new instance and provided a product_id and customer_id product_db =", "SubscriptionInstances might not have the correct order for field_name in list_field_names: instance_values_dict[field_name] =", "if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"]", "logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def save(self)", "# # Unless required by applicable law or agreed to in writing, software", "come from the db. # However newly created SubscriptionInstances might not have the", "Dict, List, Optional, Set, Tuple, Type, TypeVar, Union from uuid import UUID, uuid4", "== SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz() if data[\"end_date\"] is None and status == SubscriptionLifecycle.TERMINATED:", "get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__ is set cls.__args__ = (cls.item_type,)", "not a abstract super class or a specific lifecycle version) cls.name = product_block_name", "express or implied. # See the License for the specific language governing permissions", "grouped_instances: if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type))", "{rt.resource_type: rt for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv", "logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model,", "Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new domain model is", "child = product_block_model.save(subscription_id=subscription_id, status=status) field_instance_list.append(child) saved_instances.extend(saved) child_instances[product_block_field] = field_instance_list elif ( is_optional_type(product_block_field_type) or", "subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict: current_value =", "subscription instances and seperately saving all instance values for this instance. Args: status:", ") -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected keyword arguments in domain", "# Caller wants a new instance and provided a product_id and customer_id product_db", "Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union from uuid", "# Set the domain_model_attrs in the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance:", "A list with instances which are saved and a dict with direct children", "data[field_name] = [] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) )", "fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id, str): customer_id = UUID(customer_id) model", "SUBSCRIPTION_MODEL_REGISTRY.get(other.product.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, other.subscription_id)", "child_instances[product_block_field] = [child] saved_instances.extend(saved) return saved_instances, child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create", "instance_values_dict[resource_type_name] = siv.value # Make sure values are sorted. This already happens when", "either express or implied. # See the License for the specific language governing", "subscription instances and stores the domain model attribute in the hierarchy relationship. Args:", "# doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP", "for lifecycle {status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status)", "= None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This example", "if value is None: continue if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]):", "if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls)", "right class specialized_type = lookup_specialized_type(self.__class__, status) if specialized_type and not isinstance(self, specialized_type): raise", "Optional[ProductBlockModelInactive] = None >>> class Subscription(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): # doctest:+SKIP ... block: ProductBlockModel This", "ConstrainedList) except Exception: # Strip generic arguments, it still might be a subclass", "Circuit\"): ... int_field: Optional[int] = None ... str_field: Optional[str] = None >>> class", "product_block_field_type() # if constrainedlist has minimum, return that minimum else empty list if", "an empty list default_value = [] elif is_optional_type(product_block_field_type, ProductBlockModel): default_value = None elif", "loading for klass in cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle)", "# noqa: S101 if not status: status = SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls", "instance we just stop saving and return it so only its relation is", "to any super class. That way we can match a superclass to an", "[] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if", "prevent cyclic imports from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore", "it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type: ignore else: product_blocks_in_model", "None elif is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types:", "pragma: no mutate description: str = \"Initial subscription\" # pragma: no mutate status:", "annotations = get_annotations(cls) for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field", "of the type for the field: {product_block_field_name}, {specialized_type.__name__} (based on {product_block_field_type.__name__}) is not", "kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all", "and there is no good way to test for this try: is_constrained_list =", "start_date=subscription.start_date, end_date=subscription.end_date, note=subscription.note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return", "return instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool =", "= siv.value # Make sure values are sorted. This already happens when they", "# doctest:+SKIP \"\"\" # Fill values from actual subscription if subscription_instance_id: subscription_instance =", "create all subscription instances for it. This function does that. Args: skip_keys: list", "product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for", "self._save_instance_values( subscription_instance.product_block, subscription_instance.values ) sub_instances, children = self._save_instances(subscription_id, status) # Save the subscription", "and instance is None: raise ValueError(\"Required subscription instance is missing in database\") else:", "subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0] current_value.value", "because its part of the API (we expose it to the frontend) #", "status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool = False, start_date:", "the License. # You may obtain a copy of the License at #", "field_type return result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make and store a", "can be created by subclassing the generic product block with keyword argument 'lifecycle'", "be defined on the others Create a new empty product block >>> example1", "be created by subclassing the generic product block with keyword argument 'lifecycle' and", "as it is not always necessary. However when it is set, it is", "**instance_values, # type: ignore **sub_instances, # type: ignore ) model._db_model = subscription_instance return", "# This makes a lot of assuptions about the internals of `typing` if", "in the instance and act accordingly: only lists and scalar values supported resource_type_name", "{self.__names__}\") # Make sure we have a valid subscription instance database model subscription_instance:", "id status: SubscriptionLifecycle of subscription to check if models match Returns: A list", "else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list(", "for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v", "the class contains product block metadata. This metaclass should not be used directly", "product_block_field_type: specialized_type = lookup_specialized_type(field_type, lifecycle_status) if not issubclass(field_type, specialized_type): raise AssertionError( f\"The lifecycle", "product_block_model.from_db( subscription_instance=instance, status=status ) else: product_block_model = product_block_field_type if is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model))", "in field_types: if f_type.name == value.name: field_type = f_type data[field_name] = field_type._from_other_lifecycle(value, status,", "new instance and provided a product_id and customer_id product_db = ProductTable.query.get(product_id) product =", "= cls(**data) model._db_model = other._db_model return model @classmethod def from_db( cls: Type[B], subscription_instance_id:", "on the others Create a new empty subscription >>> example1 = SubscriptionInactive.from_product_id(product_id, customer_id)", "only be one in the type if it is a Tuple product_blocks_in_model =", "None, end_date: Optional[datetime] = None, note: Optional[str] = None, ) -> S: \"\"\"Use", "# type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore", "si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) # doctest:+SKIP >>> example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4", "ignore ) model._db_model = subscription return model @classmethod def from_other_lifecycle( cls: Type[S], other:", "Any) -> \"SubscriptionModel\": # status can be none if created during change_lifecycle if", "( # noqa: S101 field_name in resource_types ), f\"Domain model {self.__class__} does not", "# Make sure we do not use a mapped session. db.session.refresh(subscription_instance) # Block", "\"missing_resource_types_in_db\": missing_resource_types_in_db, \"missing_resource_types_in_model\": missing_resource_types_in_model, }.items() if v } if diff: missing_data[cls.name] = diff", "-> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base", "Args: db_instances: list of database models to load from status: SubscriptionLifecycle of subscription", "fixed_inputs_model logger.debug( \"ProductTable blocks diff\", product_block_db=product_db.name if product_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db,", "ValidationError: logger.exception( \"Subscription is not correct in database\", loaded_fixed_inputs=fixed_inputs, loaded_instances=instances ) raise def", "class. Use one of {self.__names__}\") # Would have been nice to do this", "and returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in", "no mutate description: str = \"Initial subscription\" # pragma: no mutate status: SubscriptionLifecycle", "the field: {product_block_field_name}, {specialized_type.__name__} (based on {field_type.__name__}) is not suitable for the lifecycle", "= resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name if product_block_db else None,", "product_block_field_type result[product_block_field_name] = field_type return result @classmethod def _find_special_fields(cls: Type) -> None: \"\"\"Make", "**sub_instances, **kwargs) # type: ignore model._db_model = db_model return model @classmethod def _load_instances_values(cls,", "\"\"\" if not self.name: raise ValueError(f\"Cannot create instance of abstract class. Use one", "parent in subscription_instance.parents: if ( parent.subscription != self.subscription and parent.subscription.status not in SAFE_PARENT_TRANSITIONS_FOR_STATUS[status]", "the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is", "subscription_id: UUID, skip_keys: Optional[List[str]] = None ) -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default", "= None, **kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not", "instantiate the instance if not hasattr(self, \"product_block_id\"): product_block = ProductBlockTable.query.filter(ProductBlockTable.name == self.name).one() self.product_block_id", "new model \"\"\" if skip_keys is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel],", "None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: # This is a concrete", "kwargs=kwargs.keys(), ) # Check if child subscription instance models conform to the same", "for pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model", "been called SubscriptionInstanceModel. ProductTable Blocks are represented as dataclasses with pydantic runtime validation.", "product_block_model.from_db( subscription_instance=instance, status=status ) return instances @classmethod def _data_from_lifecycle(cls, other: \"DomainModel\", status: SubscriptionLifecycle,", "product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields (instance", "new instance based on a dict in the state: >>> example2 = BlockInactive(\\*\\*state)", "without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance in sub.instances} saved_instances, child_instances", "= ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status,", "class to skip when creating dummy instances. Returns: A dict with instances to", "They don't have parent relations to those if not match_domain_attr: return True attr_names", "ClassVar[str] _db_model: SubscriptionInstanceTable = PrivateAttr() # Product block name. This needs to be", "to use this instead of the normal constructor because that assumes you pass", "model = cls(subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_id, **sub_instances, **kwargs) # type: ignore model._db_model = db_model return", "list with instances which are saved and a dict with direct children \"\"\"", "model from instance while changing the status. This makes sure we always have", "UUID label: Optional[str] = None def __init_subclass__( cls, *, product_block_name: Optional[str] = None,", "uuid4 import structlog from more_itertools import first, flatten, one, only from pydantic import", "if the subscription_instance does not exist. db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything", "missing_data @classmethod def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a", "specific instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls", "product_blocks_in_model=product_blocks_in_model, fixed_inputs_in_db=fixed_inputs_in_db, fixed_inputs_model=fixed_inputs_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_fixed_inputs_in_db=missing_fixed_inputs_in_db, missing_fixed_inputs_in_model=missing_fixed_inputs_in_model, ) missing_data_children: Dict[str, Any] = {}", "TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Optional, Set, Tuple, Type, TypeVar, Union from", "product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in lifecycle: if isinstance(product_block_field_type, tuple):", "cls.__mro__: if issubclass(klass, ProductBlockModel): klass.__names__.add(cls.name) cls.__doc__ = make_product_block_docstring(cls, lifecycle) @classmethod def diff_product_block_in_database(cls) ->", "def _save_instance_values( self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product", ") else: value = getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if value:", "themselves if self.subscription and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model = subscription_instance", "cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor < 10: annotations = cls.__dict__.get(\"__annotations__\",", "\"\"\" class Config: validate_assignment = True # pragma: no mutate validate_all = True", "db.session.add(subscription_instance) subscription_instance.subscription_id = subscription_id db.session.flush() # Everything is ok, make sure we are", "# check the type of the siv in the instance and act accordingly:", "mutate S = TypeVar(\"S\", bound=\"SubscriptionModel\") # pragma: no mutate B = TypeVar(\"B\", bound=\"ProductBlockModel\")", "blocks in the database. This is only needed to check if the domain", "sub.insync = self.insync sub.start_date = self.start_date sub.end_date = self.end_date sub.note = self.note db.session.add(sub)", "try: is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip generic arguments, it still", "for the lifecycle status ({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types( cls,", "selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model # Make", "blocks. This is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id =", "[] for item in getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value", "type to intialise and Union types always cross subscription boundaries.\" ) else: product_block_model", "subscription_id) return data def _save_instances( self, subscription_id: UUID, status: SubscriptionLifecycle ) -> Tuple[List[SubscriptionInstanceTable],", "# pragma: no mutate end_date: Optional[datetime] = None # pragma: no mutate note:", "in instances: if instance.subscription_id != self.subscription_id: raise ValueError( \"Attempting to save a Foreign", "= subscription return model @classmethod def from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle,", "mutate def _fix_pb_data(self) -> None: if not self.name: raise ValueError(f\"Cannot create instance of", "product blocks.\"\"\" def __init_subclass__(cls, **kwargs: Any) -> None: super().__init_subclass__(**kwargs) # type:ignore # Copy", "from sys import version_info from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, List,", "= SubscriptionLifecycle(subscription_instance.subscription.status) if not cls.__base_type__: cls = ProductBlockModel.registry.get(subscription_instance.product_block.name, cls) # type:ignore cls =", "match_domain_attr: Match domain attribute from relation (not wanted when loading product blocks directly", "from orchestrator.types import ( SAFE_PARENT_TRANSITIONS_FOR_STATUS, State, SubscriptionLifecycle, UUIDstr, is_list_type, is_of_type, is_optional_type, is_union_type, )", "model and those on product blocks in the database. This is only needed", "pragma: no mutate end_date: Optional[datetime] = None # pragma: no mutate note: Optional[str]", ") -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: # This is", "return not attr_names or field_name in attr_names return domain_filter for product_block_field_name, product_block_field_type in", "# What's left should be removed for instance in old_instances_dict.values(): db.session.delete(instance) db.session.flush() @property", "instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product, customer_id=subscription.customer_id, subscription_id=subscription.subscription_id, description=subscription.description,", "Union[Optional[ProductBlockModel], List[ProductBlockModel]]] = {} def keyfunc(i: SubscriptionInstanceTable) -> str: return i.product_block.name sorted_instances =", "specialized_type): raise ValueError( f\"Lifecycle status {self.status.value} requires specialized type {specialized_type!r}, was: {type(self)!r}\" )", "SubscriptionInstanceTable, SubscriptionInstanceValueTable, SubscriptionTable, db, ) from orchestrator.domain.lifecycle import ProductLifecycle, lookup_specialized_type, register_specialized_type from orchestrator.types", "product block with keyword argument 'lifecycle' and overriding its fields. All product blocks", "type: ignore elif is_list_type(product_block_field_type) or is_optional_type(product_block_field_type): field_type = first(get_args(product_block_field_type)) else: field_type = product_block_field_type", "for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if product_block_field_name in skip_keys: continue if is_list_type(product_block_field_type): if", "`product_block_name` must be defined on the base class and need not to be", "this domain model. When a domain model is saved to the database we", "\"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make sure __args__ is set cls.__args__", "if _is_constrained_list_type(product_block_field_type): product_block_model_list = product_block_field_type() else: product_block_model_list = [] product_block_model = one(get_args(product_block_field_type)) instance_list:", "pydantic.types import ConstrainedList from pydantic.typing import get_args, get_origin from sqlalchemy.orm import selectinload from", "is_constrained_list = issubclass(type, ConstrainedList) except Exception: # Strip generic arguments, it still might", "abstract class. Use one of {self.__names__}\") # Make sure we have a valid", "a mapped session. db.session.refresh(subscription_instance) # Block unsafe status changes on domain models that", "= False # We only want fields that are on this class and", "product: ProductModel customer_id: UUID _db_model: SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) #", "model should inherit from ProductBlockModel which has this metaclass defined. You can find", "{product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name) if value", "= cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, #", ") -> Dict[str, Union[List[\"ProductBlockModel\"], \"ProductBlockModel\"]]: \"\"\"Initialize default subscription instances. When a new domain", "other: \"DomainModel\", status: SubscriptionLifecycle, subscription_id: UUID) -> Dict: data = other.dict() for field_name,", "no mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool =", "is always set name: str subscription_instance_id: UUID owner_subscription_id: UUID label: Optional[str] = None", "of match. \"\"\" # We don't match on the product_blocks directly under subscriptions.", "for instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) # What's left", "continue try: is_product_block_field = ( is_union_type(field_type, DomainModel) or is_list_type(field_type, DomainModel) or is_optional_type(field_type, DomainModel)", "for field_type in get_args(product_block_field_type): if instance.product_block.name == field_type.name: product_block_model = field_type assert (", "isinstance(customer_id, str): customer_id = UUID(customer_id) model = cls( product=product, customer_id=customer_id, subscription_id=subscription_id, description=description, status=status,", "SubscriptionTable = PrivateAttr() subscription_id: UUID = Field(default_factory=uuid4) # pragma: no mutate description: str", "used to make sure the class contains product block metadata. This metaclass should", "if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) # pragma: no mutate for _ in range(product_block_field_type.min_items):", "ProductBlockModel which has this metaclass defined. You can find some examples in: :ref:`domain-models`", "dict with instances to pass to the new model \"\"\" if skip_keys is", "is_optional_type(product_block_field_type): product_block_model = first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for", "product blocks in the database. This is only needed to check if the", "else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k:", "= resource_types[field_name] value = getattr(self, field_name) if value is None: continue if is_list_type(field_type):", "from_other_lifecycle( cls: Type[S], other: \"SubscriptionModel\", status: SubscriptionLifecycle, ) -> S: \"\"\"Create new domain", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "lookup_specialized_type(cls, status) data = cls._data_from_lifecycle(other, status, subscription_id) model = cls(**data) model._db_model = other._db_model", "# Only available in python > 3.10 from inspect import get_annotations annotations =", ".selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values), ).get(self.subscription_id) if not sub: sub = self._db_model # Make sure", "subscription_instance: # Make sure we do not use a mapped session. db.session.refresh(subscription_instance) #", "fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs} instances = cls._init_instances(subscription_id) if isinstance(customer_id,", "make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) -> bool: \"\"\"Check if type is", "subscription_id: Optional subscription id needed if this is a new model Returns: List", "= None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def", "pragma: no mutate for _ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field", "block fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor < 10: annotations", "to those if not match_domain_attr: return True attr_names = { relation.domain_model_attr for relation", "= None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys(): logger.warning( \"Unexpected", ") return subscription_instance_values def _set_instance_domain_model_attrs( self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) ->", "{status}\") label = subscription_instance.label instance_values = cls._load_instances_values(subscription_instance.values) sub_instances = cls._load_instances(subscription_instance.children, status) try: model", "elif not is_optional_type(product_block_field_type) and instance is None: raise ValueError(\"Required subscription instance is missing", "= cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type: ignore **sub_instances, # type:", "field of a ProductBlockModel expects 1 instance default_value = product_block_model.new(subscription_id=subscription_id) instances[product_block_field_name] = default_value", "subscription_id) ) else: value = getattr(other, field_name) if is_optional_type(field_type): field_type = first(get_args(field_type)) if", "nowtz from orchestrator.utils.docs import make_product_block_docstring, make_subscription_model_docstring logger = structlog.get_logger(__name__) def _is_constrained_list_type(type: Type) ->", "\"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name, cls) # type:ignore cls = lookup_specialized_type(cls,", "current_values_dict[field_name][0] current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def", "all constraints match subscription_id: Optional subscription id needed if this is a new", "to save a Foreign `Subscription Instance` directly below a subscription. This is not", "governing permissions and # limitations under the License. from collections import defaultdict from", "not is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types: if f_type.name == value.name:", "is similar to `from_product_id()` \"\"\" sub_instances = cls._init_instances(subscription_id, list(kwargs.keys())) subscription_instance_id = uuid4() #", "product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): filter_func = match_domain_model_attr_if_possible(product_block_field_name) if is_list_type(product_block_field_type): if product_block_field_name not in", "ValueError(\"Required subscription instance is missing in database\") else: instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status", "= product_block_field_type # Scalar field of a ProductBlockModel expects 1 instance default_value =", "SubscriptionInstanceTable.query.get( self.subscription_instance_id ) if subscription_instance: # Make sure we do not use a", "limitations under the License. from collections import defaultdict from datetime import datetime from", "-> Dict[str, Union[Optional[\"ProductBlockModel\"], List[\"ProductBlockModel\"]]]: \"\"\"Load subscription instances for this domain model. When a", "instances @classmethod def _load_instances( cls, db_instances: List[SubscriptionInstanceTable], status: SubscriptionLifecycle, match_domain_attr: bool = True,", "generic arguments, it still might be a subclass if get_origin(type): return _is_constrained_list_type(get_origin(type)) else:", "on domain models that have Subscription instances with parent relations for parent in", "\"\"\" if skip_keys is None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] =", "product_blocks_in_db = {pb.name for pb in product_block_db.children} if product_block_db else set() product_blocks_types_in_model =", "product_id: UUID) -> Dict[str, Any]: \"\"\"Return any differences between the attrs defined on", "SubscriptionLifecycle.INITIAL, description: Optional[str] = None, insync: bool = False, start_date: Optional[datetime] = None,", "`ACTIVE` And `SubscriptionInactive` for all other states. `product_type` must be defined on the", "valid only for `ACTIVE` And `BlockInactive` for all other states. `product_block_name` must be", "mapping of the domain model attribute a underlying instances Returns: None \"\"\" children_relations", "to use for constructor \"\"\" instance_values_dict: State = {} list_field_names = set() #", "= status if data[\"start_date\"] is None and status == SubscriptionLifecycle.ACTIVE: data[\"start_date\"] = nowtz()", "resource_types_model - resource_types_db missing_resource_types_in_model = resource_types_db - resource_types_model logger.debug( \"ProductBlockTable blocks diff\", product_block_db=product_block_db.name", "{} list_field_names = set() # Set default values for field_name, field_type in cls._non_product_block_fields_.items():", "+ [subscription_instance], subscription_instance @property def subscription(self) -> SubscriptionTable: return self.db_model.subscription @property def db_model(self)", "instances for this domain model. When a domain model is saved to the", "\"\"\" result = {} for product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not", "that is not loaded from an existing subscription. We also create all subscription", "resource_types_db = {rt.resource_type for rt in product_block_db.resource_types} if product_block_db else set() missing_resource_types_in_db =", "subscription model: >>> class SubscriptionInactive(SubscriptionModel, product_type=\"SP\"): # doctest:+SKIP ... block: Optional[ProductBlockModelInactive] = None", "in product_db.fixed_inputs} if product_db else set() missing_fixed_inputs_in_db = fixed_inputs_model - fixed_inputs_in_db missing_fixed_inputs_in_model =", "for `ACTIVE` And `SubscriptionInactive` for all other states. `product_type` must be defined on", "the product_blocks directly under subscriptions. They don't have parent relations to those if", "subscription is active. To support this a lifecycle specific product block definition can", "non product block fields (instance values). Returns: List of database instances values to", "class Block(BlockInactive, lifecycle=[SubscriptionLifecycle.ACTIVE]): ... int_field: int ... str_field: str This example defines a", "instances[product_block_field_name] = product_block_model_list elif is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list( filter(", "suitable for the lifecycle status ({lifecycle_status}) of this model\" ) @classmethod def _get_child_product_block_types(", "cls) # type:ignore cls = lookup_specialized_type(cls, status) elif not issubclass(cls, lookup_specialized_type(cls, status)): raise", "**fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return model @classmethod def", "assume true is no domain_model_attr is set. return not attr_names or field_name in", "minimum, return that minimum else empty list if product_block_field_type.min_items: logger.debug(\"creating min_items\", type=product_block_field_type) #", "class (so not a abstract super class or a specific lifecycle version) cls.name", "instance is None: raise ValueError(\"Required subscription instance is missing in database\") else: instances[product_block_field_name]", "self, subscription_instance: SubscriptionInstanceTable, subscription_instance_mapping: Dict[str, List[SubscriptionInstanceTable]], ) -> None: \"\"\" Save the domain", "`SubscriptionInactive` for all other states. `product_type` must be defined on the base class", "one in the type if it is a Tuple product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model))))", "with pydantic runtime validation. Different stages of a subscription lifecycle could require different", "mutate class_name=cls.__name__, kwargs=kwargs.keys(), ) # Check if child subscription instance models conform to", "lifecycle {status}\") fixed_inputs = {fi.name: fi.value for fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances,", "status {status}\") return super().__new__(cls) def __init_subclass__( cls, is_base: bool = False, lifecycle: Optional[List[SubscriptionLifecycle]]", "def new(cls: Type[B], subscription_id: UUID, **kwargs: Any) -> B: \"\"\"Create a new empty", "except in compliance with the License. # You may obtain a copy of", "instance in enumerate(instances): relation = SubscriptionInstanceRelationTable( parent_id=subscription_instance.subscription_instance_id, child_id=instance.subscription_instance_id, order_id=index, domain_model_attr=domain_model_attr, ) children_relations.append(relation) subscription_instance.children_relations", "**kwargs: Any, ) -> None: super().__init_subclass__(lifecycle=lifecycle, **kwargs) if product_block_name is not None: #", "cls._load_instances(subscription_instance.children, status) try: model = cls( subscription_instance_id=subscription_instance_id, owner_subscription_id=subscription_instance.subscription_id, subscription=subscription_instance.subscription, label=label, **instance_values, # type:", "DomainModel(BaseModel): \"\"\"Base class for domain models. Contains all common Product block/Subscription instance code", "*args: Any, **kwargs: Any) -> B: self._fix_pb_data() kwargs[\"name\"] = self.name return super().__call__(*args, **kwargs)", "list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__) ) ) product_block_model_list.extend( product_block_model.from_db(subscription_instance=instance,", "None: skip_keys = [] instances: Dict[str, Union[List[ProductBlockModel], ProductBlockModel]] = {} for product_block_field_name, product_block_field_type", "= [] for field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101 field_name", "current_value.value = str(value) subscription_instance_values.append(current_value) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(value)) ) return subscription_instance_values def _set_instance_domain_model_attrs(", "filter_func, flatten( grouped_instances.get(field_type.name, []) for field_type in get_args(product_block_field_type) ), ) ) ) product_block_model", "INSERT and returns subscription_id without committing transaction old_instances_dict = {instance.subscription_instance_id: instance for instance", "Config: validate_assignment = True # pragma: no mutate validate_all = True # pragma:", "child_instances class ProductBlockModelMeta(ModelMetaclass): \"\"\"Metaclass used to create product block instances. This metaclass is", "resource_types[field_name] value = getattr(self, field_name) if value is None: continue if is_list_type(field_type): for", "# Strip generic arguments, it still might be a subclass if get_origin(type): return", "needed to check if the domain model and database models match which would", "mutate status: SubscriptionLifecycle = SubscriptionLifecycle.INITIAL # pragma: no mutate insync: bool = False", "subscription. Not all subscriptions have a domain model attribute that is set as", "Copyright 2019-2020 SURF. # Licensed under the Apache License, Version 2.0 (the \"License\");", "is_list_type, is_of_type, is_optional_type, is_union_type, ) from orchestrator.utils.datetime import nowtz from orchestrator.utils.docs import make_product_block_docstring,", "if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] = get_args(product_block_field_type) # type: ignore", "sorted(db_instances, key=keyfunc) grouped_instances = {k: list(g) for k, g in groupby(sorted_instances, keyfunc)} def", "name cls.name = None # type:ignore cls.__names__ = set() # For everything except", "self, product_block: ProductBlockTable, current_values: List[SubscriptionInstanceValueTable] ) -> List[SubscriptionInstanceValueTable]: \"\"\"Save non product block fields", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "abstract classes dont have it. In practice it is always set name: str", "the product as defined in the database as a dataclass.\"\"\" class Config: validate_assignment", "product_blocks_types_in_model: missing_data_children.update(product_block_in_model.diff_product_block_in_database()) # type: ignore diff = { k: v for k, v", "in product_block_db.children} if product_block_db else set() product_blocks_types_in_model = cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model),", "from orchestrator.domain import SUBSCRIPTION_MODEL_REGISTRY cls = SUBSCRIPTION_MODEL_REGISTRY.get(subscription.product.name, cls) # type:ignore cls = lookup_specialized_type(cls,", "Set the domain_model_attrs in the database for domain_model_attr, instances in subscription_instance_mapping.items(): instance: SubscriptionInstanceTable", "that is given as class keyword argument. Define a product block: >>> class", "subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items(): assert ( # noqa: S101", "type: ignore model._db_model = db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) ->", "cls, *, product_block_name: Optional[str] = None, lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any, )", ") -> None: \"\"\" Save the domain model attribute to the database. This", "is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): instance = only( list( filter( filter_func, flatten( grouped_instances.get(field_type.name, [])", "continue if is_list_type(field_type): for val, siv in zip_longest(value, current_values_dict[field_name]): if val: if siv:", "model has not been resolved. Unable to continue\" instances[product_block_field_name] = product_block_model.from_db( subscription_instance=instance, status=status", "= SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database: >>> SubscriptionInactive.from_subscription(subscription_id)", "lifecycle: Optional[List[SubscriptionLifecycle]] = None, **kwargs: Any ) -> None: super().__init_subclass__() cls._find_special_fields() if kwargs.keys():", "other._db_model return model @classmethod def from_subscription(cls: Type[S], subscription_id: Union[UUID, UUIDstr]) -> S: \"\"\"Use", "for field_name, field_type in annotations.items(): if field_name.startswith(\"_\"): continue try: is_product_block_field = ( is_union_type(field_type,", "it is necessary to filter through instances depending on that attribute. Args: instance:", "for rt in product_block.resource_types} current_values_dict: Dict[str, List[SubscriptionInstanceValueTable]] = defaultdict(list) for siv in current_values:", "ProductModel( product_id=subscription.product.product_id, name=subscription.product.name, description=subscription.product.description, product_type=subscription.product.product_type, tag=subscription.product.tag, status=subscription.product.status, ) status = SubscriptionLifecycle(subscription.status) if not", "# type:ignore cls.__names__ = set() # For everything except abstract classes if cls.name", "from itertools import groupby, zip_longest from operator import attrgetter from sys import version_info", "and subscription_instance.subscription_id != subscription_id: return [], subscription_instance self._db_model = subscription_instance else: subscription_instance =", "sub: sub = self._db_model # Make sure we refresh the object and not", "annotations = cls.__dict__.get(\"__annotations__\", {}) else: if TYPE_CHECKING: annotations = {} else: # Only", "the new model \"\"\" if skip_keys is None: skip_keys = [] instances: Dict[str,", "keyfunc)} def match_domain_model_attr_if_possible(field_name: str) -> Callable: def domain_filter(instance: SubscriptionInstanceTable) -> bool: \"\"\" Match", "instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name in product_block_model.__names__), )", "default subscription instances. When a new domain model is created that is not", "base class and need not to be defined on the others Create a", "fields. All product blocks are related to a database ProductBlockTable object through the", "loaded from an existing subscription we also load all subscription instances for it.", "product_block_model = first(get_args(product_block_model)) instance = only( list( filter( filter_func, flatten(grouped_instances.get(name, []) for name", "the same lifecycle for product_block_field_name, product_block_field_type in cls._get_child_product_block_types().items(): if lifecycle: for lifecycle_status in", ":ref:`domain-models` \"\"\" __names__: Set[str] name: Optional[str] product_block_id: UUID description: str tag: str registry:", "**kwargs) class ProductBlockModel(DomainModel, metaclass=ProductBlockModelMeta): r\"\"\"Base class for all product block models. This class", "we always have a specific instance.. \"\"\" if not cls.__base_type__: cls = ProductBlockModel.registry.get(other.name,", "in one(product_blocks_types_in_model): # type: ignore missing_data.update(product_block_model.diff_product_block_in_database()) else: for product_block_in_model in product_blocks_types_in_model: missing_data.update(product_block_in_model.diff_product_block_in_database()) #", "= {} list_field_names = set() # Set default values for field_name, field_type in", ">>> example2 = SubscriptionInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database:", "pragma: no mutate __base_type__: ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str,", "is_union_type(field_type) and not is_optional_type(field_type): field_types = get_args(field_type) for f_type in field_types: if f_type.name", "Args: subscription_instance_mapping: a mapping of the domain model attribute a underlying instances Returns:", "bool = False, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, note: Optional[str]", ") -> S: \"\"\"Use product_id (and customer_id) to return required fields of a", "to the database we need to save all child subscription instances for it.", "= cls._get_child_product_block_types().values() if product_blocks_types_in_model and isinstance(first(product_blocks_types_in_model), tuple): product_blocks_in_model = set(flatten(map(attrgetter(\"__names__\"), one(product_blocks_types_in_model)))) # type:", "raise ValueError(\"Required subscription instance is missing in the database\") for field_type in get_args(product_block_field_type):", "raise def save(self) -> None: \"\"\"Save the subscription to the database.\"\"\" specialized_type =", "BlockInactive(\\*\\*state) # doctest:+SKIP To retrieve a ProductBlockModel from the database.: >>> BlockInactive.from_db(subscription_instance_id) #", "allowed.\" ) sub.instances = saved_instances # Calculate what to remove instances_set = {instance.subscription_instance_id", "example3 = ProductBlockModel.from_db(subscription_instance=si_from_db) # doctest:+SKIP >>> example4 = ProductBlockModel.from_db(subscription_instance_id=subscription_instance_id) # doctest:+SKIP \"\"\" #", "ProductModel( product_id=product_db.product_id, name=product_db.name, description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None: description", "else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if field_name in current_values_dict: current_value = current_values_dict[field_name][0]", "description=product_db.description, product_type=product_db.product_type, tag=product_db.tag, status=product_db.status, ) if description is None: description = f\"Initial subscription", "note=note, ) db.session.add(subscription) fixed_inputs = {fi.name: fi.value for fi in product_db.fixed_inputs} instances =", "For everything except abstract classes if cls.name is not None: register_specialized_type(cls, lifecycle) #", "models match match_domain_attr: Match domain attribute from relation (not wanted when loading product", "str status: ProductLifecycle class SubscriptionModel(DomainModel): r\"\"\"Base class for all product subscription models. Define", "= cls.__dict__[\"__orig_bases__\"][0] if not hasattr(generic_base_cls, \"item_type\") and get_args(generic_base_cls): cls.item_type = get_args(generic_base_cls)[0] # Make", "values are sorted. This already happens when they come from the db. #", "fi in subscription.product.fixed_inputs} instances = cls._load_instances(subscription.instances, status, match_domain_attr=False) try: model = cls( product=product,", "to `from_subscription()` >>> subscription_instance_id = KNOWN_UUID_IN_DB # doctest:+SKIP >>> si_from_db = db.SubscriptionInstanceTable.query.get(subscription_instance_id) #", "ClassVar[Optional[Type[\"DomainModel\"]]] = None # pragma: no mutate _product_block_fields_: ClassVar[Dict[str, Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]]", "_ in range(product_block_field_type.min_items): default_value.append(product_block_model.new(subscription_id=subscription_id)) else: # a list field of ProductBlockModels without limits", "\"\"\" Match domain model attributes. This helper is necessary to filter through all", "siv in current_values: current_values_dict[siv.resource_type.resource_type].append(siv) subscription_instance_values = [] for field_name, field_type in self._non_product_block_fields_.items(): assert", "fields of an existing subscription.\"\"\" subscription = SubscriptionTable.query.options( selectinload(SubscriptionTable.instances) .selectinload(SubscriptionInstanceTable.product_block) .selectinload(ProductBlockTable.resource_types), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.parent_relations), selectinload(SubscriptionTable.instances).selectinload(SubscriptionInstanceTable.values),", "start_date=start_date, end_date=end_date, note=note, **fixed_inputs, **instances, # type: ignore ) model._db_model = subscription return", "the ProductBlockTable {product_block.name}, missing: {field_name} {resource_types}\" resource_type = resource_types[field_name] value = getattr(self, field_name)", "db_model return model @classmethod def _load_instances_values(cls, instance_values: List[SubscriptionInstanceValueTable]) -> Dict[str, str]: \"\"\"Load non", "= None, ) -> S: \"\"\"Use product_id (and customer_id) to return required fields", "if siv: siv.value = str(val) subscription_instance_values.append(siv) else: subscription_instance_values.append( SubscriptionInstanceValueTable(resource_type=resource_type, value=str(val)) ) else: if", "getattr(other, field_name): data[field_name].append( one(get_args(field_type))._from_other_lifecycle(item, status, subscription_id) ) else: value = getattr(other, field_name) if", "SubscriptionLifecycle of subscription to check if models match match_domain_attr: Match domain attribute from", "block models. This class should have been called SubscriptionInstanceModel. ProductTable Blocks are represented", "product_block_db else None, product_blocks_in_db=product_blocks_in_db, product_blocks_in_model=product_blocks_in_model, resource_types_db=resource_types_db, resource_types_model=resource_types_model, missing_product_blocks_in_db=missing_product_blocks_in_db, missing_product_blocks_in_model=missing_product_blocks_in_model, missing_resource_types_in_db=missing_resource_types_in_db, missing_resource_types_in_model=missing_resource_types_in_model, ) missing_data:", "fields.\"\"\" cls._non_product_block_fields_ = {} cls._product_block_fields_ = {} if version_info.minor < 10: annotations =", "domain models that have Subscription instances with parent relations for parent in subscription_instance.parents:", "Type]] _non_product_block_fields_: ClassVar[Dict[str, Type]] def __init_subclass__( cls, *args: Any, lifecycle: Optional[List[SubscriptionLifecycle]] = None,", "= {instance.subscription_instance_id for instance in sub.instances} for instance_id in instances_set: old_instances_dict.pop(instance_id, None) #", "product_block_model = None if instance is None: raise ValueError(\"Required subscription instance is missing", "Blocks are represented as dataclasses with pydantic runtime validation. Different stages of a", "product_block_field_name, product_block_field_type in cls._product_block_fields_.items(): if is_union_type(product_block_field_type) and not is_optional_type(product_block_field_type): field_type: Union[Type[\"ProductBlockModel\"], Tuple[Type[\"ProductBlockModel\"]]] =", "note: Optional[str] = None # pragma: no mutate def __new__(cls, *args: Any, status:", "missing_fixed_inputs_in_model, \"missing_in_children\": missing_data_children, }.items() if v } missing_data = {} if diff: missing_data[product_db.name]", "instance_values_dict[field_name] = [] list_field_names.add(field_name) for siv in instance_values: # check the type of", "already set if new is the first usage of this class cls._fix_pb_data() db_model", "lifecycle could require different product block definition. Mainly to support mandatory fields when" ]
[ "will remove URLS and HTML tags before trying to match emoticons. Some references", "of features that indicate both the presence and emotional flavour of the emoticon.", "remove URLS and HTML tags before trying to match emoticons. Some references used", "of text, and whether those emoticons represent one of the more common emotions.", ".process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\")", "remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or", "and unescaped version of the text that is expecte to have been generated", "kiss + happycry + laugh + cheeky neg = crying + sad +", "= 1 if set(matches).intersection( crys ): crying = 1 if set(matches).intersection( winks ):", "and add a set of features that indicate both the presence and emotional", "load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\")", "kiss = 1 if set(matches).intersection( sads ): sad = 1 if set(matches).intersection( shocks", "of false positive matches in text containing brackets For example emoticons: 8) or", "if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ): smiley", "I have deliberately ignored certain emoticons because of the likelihood of false positive", "HTML tags before trying to match emoticons. Some references used when considering which", "+ kiss + happycry + laugh + cheeky neg = crying + sad", "common emotions. NOTE: In developing these regexes I have deliberately ignored certain emoticons", ".process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys", "are emoticons in certain columns of text, and whether those emoticons represent one", "set(matches).intersection( shocks ): shock = 1 if set(matches).intersection( sceptics ): sceptic = 1", "emoticons. Some references used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939", "to a dataframe that indivate whether there are emoticons in certain columns of", "laugh + cheeky neg = crying + sad + shock + sceptic sent", "indicate both the presence and emotional flavour of the emoticon. \"\"\" def cal_features(x,", "This will remove URLS and HTML tags before trying to match emoticons. Some", "numpy as np import codecs import re from .process import load_word_list from .process", "codecs import re from .process import load_word_list from .process import load_word_pattern from .process", "avoid matching characters inside document markup language tags there is a rudimentary regex", "wink + kiss + happycry + laugh + cheeky neg = crying +", "as np import codecs import re from .process import load_word_list from .process import", "= 0 shock = 0 sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags(", "there are emoticons in certain columns of text, and whether those emoticons represent", "unescaped version of the text that is expecte to have been generated in", "if set(matches).intersection( sads ): sad = 1 if set(matches).intersection( shocks ): shock =", "crying = 0 sad = 0 shock = 0 sceptic = 0 if", "np import codecs import re from .process import load_word_list from .process import load_word_pattern", "the emoticon. \"\"\" def cal_features(x, col): emos = 0 smiley = 0 wink", "bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection(", "pandas dataframe and a column name. Check for emoticons in the column and", "Recognition Text Features The functions in this library will add columns to a", "col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and", "): crying = 1 if set(matches).intersection( winks ): wink = 1 if set(matches).intersection(", "matching characters inside document markup language tags there is a rudimentary regex based", "matches in text containing brackets For example emoticons: 8) or (B will not", "load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\")", "tag removal and unescaped version of the text that is expecte to have", "https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas", "of the likelihood of false positive matches in text containing brackets For example", "import re from .process import load_word_list from .process import load_word_pattern from .process import", "= load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys =", "cal_features(x, col): emos = 0 smiley = 0 wink = 0 kiss =", "): sad = 1 if set(matches).intersection( shocks ): shock = 1 if set(matches).intersection(", "1 pos = smiley + wink + kiss + happycry + laugh +", "= 1 if set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection( cheekys ):", "= load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses =", "-*- coding: utf-8 -*- import pandas as pd import numpy as np import", "false positive matches in text containing brackets For example emoticons: 8) or (B", "of the emoticon. \"\"\" def cal_features(x, col): emos = 0 smiley = 0", "= add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas", "removal and unescaped version of the text that is expecte to have been", "= load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re =", "\"\"\" def cal_features(x, col): emos = 0 smiley = 0 wink = 0", "= load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re =", "columns: rez = add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given", "that indicate both the presence and emotional flavour of the emoticon. \"\"\" def", "remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks =", "the intial simple text function run by the program. This will remove URLS", "containing brackets For example emoticons: 8) or (B will not be matched. To", "df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col):", "in certain columns of text, and whether those emoticons represent one of the", "shock = 1 if set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection( laughs", "or (B will not be matched. To avoid matching characters inside document markup", "positive matches in text containing brackets For example emoticons: 8) or (B will", "sad + shock + sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[", "regex based tag removal and unescaped version of the text that is expecte", "set of features that indicate both the presence and emotional flavour of the", "happycry + laugh + cheeky neg = crying + sad + shock +", "= load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex =", "emotions. NOTE: In developing these regexes I have deliberately ignored certain emoticons because", "https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a", "include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\"", "smiley + wink + kiss + happycry + laugh + cheeky neg =", "): happycry = 1 pos = smiley + wink + kiss + happycry", "load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\")", "emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def", "in the intial simple text function run by the program. This will remove", "presence and emotional flavour of the emoticon. \"\"\" def cal_features(x, col): emos =", "Text Features The functions in this library will add columns to a dataframe", "cheeky = 0 crying = 0 sad = 0 shock = 0 sceptic", "crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex", "Features The functions in this library will add columns to a dataframe that", "emoticons. \"\"\" rez = df.copy() for col in columns: rez = add_emoticon_features(rez, col)", "= 0 wink = 0 kiss = 0 happycry = 0 laugh =", "bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The", "8) or (B will not be matched. To avoid matching characters inside document", "add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and a set of column names.", "a rudimentary regex based tag removal and unescaped version of the text that", "markup language tags there is a rudimentary regex based tag removal and unescaped", "flavour of the emoticon. \"\"\" def cal_features(x, col): emos = 0 smiley =", "empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df,", "col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad', col+'_emo_shock', col+'_emo_sceptic', col+'_emo_pos', col+'_emo_neg', col+'_emo_sentiment']", "and a column name. Check for emoticons in the column and add a", "= load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics =", "To avoid matching characters inside document markup language tags there is a rudimentary", "rez = add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a", "cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads", "pandas dataframe and a set of column names. Add features that detect the", "= 1 pos = smiley + wink + kiss + happycry + laugh", "of emoticons. \"\"\" rez = df.copy() for col in columns: rez = add_emoticon_features(rez,", "wink = 0 kiss = 0 happycry = 0 laugh = 0 cheeky", "set of column names. Add features that detect the presence of emoticons. \"\"\"", "shock = 0 sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col]", "): kiss = 1 if set(matches).intersection( sads ): sad = 1 if set(matches).intersection(", "of the text that is expecte to have been generated in the intial", "1 if set(matches).intersection( winks ): wink = 1 if set(matches).intersection( kisses ): kiss", "= df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley',", "re from .process import load_word_list from .process import load_word_pattern from .process import remove_urls_and_tags", "both the presence and emotional flavour of the emoticon. \"\"\" def cal_features(x, col):", "in columns: rez = add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\"", "+ wink + kiss + happycry + laugh + cheeky neg = crying", "text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text)", "= 1 if set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection( laughs ):", "pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\")", "shocks ): shock = 1 if set(matches).intersection( sceptics ): sceptic = 1 if", "utf-8 -*- import pandas as pd import numpy as np import codecs import", "len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ): smiley =", "developing these regexes I have deliberately ignored certain emoticons because of the likelihood", "import pandas as pd import numpy as np import codecs import re from", "emoticon. \"\"\" def cal_features(x, col): emos = 0 smiley = 0 wink =", "rez = df.copy() for col in columns: rez = add_emoticon_features(rez, col) return rez", "from .process import load_word_list from .process import load_word_pattern from .process import remove_urls_and_tags from", "sad = 1 if set(matches).intersection( shocks ): shock = 1 if set(matches).intersection( sceptics", "in text containing brackets For example emoticons: 8) or (B will not be", "emotional flavour of the emoticon. \"\"\" def cal_features(x, col): emos = 0 smiley", "set(matches).intersection( crys ): crying = 1 if set(matches).intersection( winks ): wink = 1", "set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection( sads ): sad = 1", "\"\"\" Given a pandas dataframe and a set of column names. Add features", "expecte to have been generated in the intial simple text function run by", "= 0 sad = 0 shock = 0 sceptic = 0 if x[col]==x[col]:", "######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and a set of", "before trying to match emoticons. Some references used when considering which empticons to", "certain columns of text, and whether those emoticons represent one of the more", "col in columns: rez = add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col):", "- neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return", "columns of text, and whether those emoticons represent one of the more common", "as pd import numpy as np import codecs import re from .process import", "if set(matches).intersection( happycrys ): happycry = 1 pos = smiley + wink +", "def cal_features(x, col): emos = 0 smiley = 0 wink = 0 kiss", "\"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and a set", "set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection( happycrys ): happycry = 1", "trying to match emoticons. Some references used when considering which empticons to include:", "texturizer.emoticons: Emoticon Recognition Text Features The functions in this library will add columns", "intial simple text function run by the program. This will remove URLS and", "get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return", "= 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches =", "names. Add features that detect the presence of emoticons. \"\"\" rez = df.copy()", "to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns):", "and a set of column names. Add features that detect the presence of", "= len(matches) if set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection( crys ):", "whether those emoticons represent one of the more common emotions. NOTE: In developing", "-*- import pandas as pd import numpy as np import codecs import re", "re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions in this library will", "if set(matches).intersection( winks ): wink = 1 if set(matches).intersection( kisses ): kiss =", "0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text)", "language tags there is a rudimentary regex based tag removal and unescaped version", "def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and a column name. Check", "one of the more common emotions. NOTE: In developing these regexes I have", "matched. To avoid matching characters inside document markup language tags there is a", "pd import numpy as np import codecs import re from .process import load_word_list", "from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\")", "is expecte to have been generated in the intial simple text function run", "set(matches).intersection( happycrys ): happycry = 1 pos = smiley + wink + kiss", "tags before trying to match emoticons. Some references used when considering which empticons", "a dataframe that indivate whether there are emoticons in certain columns of text,", "https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and a", "load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex)", "\"\"\" rez = df.copy() for col in columns: rez = add_emoticon_features(rez, col) return", "axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry',", "happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics", "add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and a column name. Check for", "0 laugh = 0 cheeky = 0 crying = 0 sad = 0", "been generated in the intial simple text function run by the program. This", "by the program. This will remove URLS and HTML tags before trying to", "ignored certain emoticons because of the likelihood of false positive matches in text", "\"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions in", "col): \"\"\" Given a pandas dataframe and a column name. Check for emoticons", "# -*- coding: utf-8 -*- import pandas as pd import numpy as np", "######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and a column name.", "emoticons: 8) or (B will not be matched. To avoid matching characters inside", "cheekys ): cheeky = 1 if set(matches).intersection( happycrys ): happycry = 1 pos", "sceptics ): sceptic = 1 if set(matches).intersection( laughs ): laugh = 1 if", "df.copy() for col in columns: rez = add_emoticon_features(rez, col) return rez ######################################################################################## def", "= 0 cheeky = 0 crying = 0 sad = 0 shock =", "columns to a dataframe that indivate whether there are emoticons in certain columns", "set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection( laughs ): laugh = 1", "shock + sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ]", "len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ): smiley = 1 if", "the presence of emoticons. \"\"\" rez = df.copy() for col in columns: rez", "version of the text that is expecte to have been generated in the", "and emotional flavour of the emoticon. \"\"\" def cal_features(x, col): emos = 0", "= 0 sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] )", "add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe", "kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks", "characters inside document markup language tags there is a rudimentary regex based tag", "load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\")", "sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re", "emos = 0 smiley = 0 wink = 0 kiss = 0 happycry", "whether there are emoticons in certain columns of text, and whether those emoticons", "text containing brackets For example emoticons: 8) or (B will not be matched.", "dataframe and a column name. Check for emoticons in the column and add", "references used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391", "= \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions", "= \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons:", "1 if set(matches).intersection( shocks ): shock = 1 if set(matches).intersection( sceptics ): sceptic", "######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad',", "0 wink = 0 kiss = 0 happycry = 0 laugh = 0", "emoticons in the column and add a set of features that indicate both", "\"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon", "neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df", "a set of features that indicate both the presence and emotional flavour of", "smiley = 0 wink = 0 kiss = 0 happycry = 0 laugh", "from .process import load_word_pattern from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles", "re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features", "1 if set(matches).intersection( sads ): sad = 1 if set(matches).intersection( shocks ): shock", "1 if set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection( laughs ): laugh", "the presence and emotional flavour of the emoticon. \"\"\" def cal_features(x, col): emos", "result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh',", "sads ): sad = 1 if set(matches).intersection( shocks ): shock = 1 if", "col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss',", "and whether those emoticons represent one of the more common emotions. NOTE: In", "pos = smiley + wink + kiss + happycry + laugh + cheeky", "= pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1,", "import codecs import re from .process import load_word_list from .process import load_word_pattern from", "Emoticon Recognition Text Features The functions in this library will add columns to", "Given a pandas dataframe and a set of column names. Add features that", "of the more common emotions. NOTE: In developing these regexes I have deliberately", "or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ): smiley = 1", ".process import load_word_pattern from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles =", "for emoticons in the column and add a set of features that indicate", "x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches =", "for col in columns: rez = add_emoticon_features(rez, col) return rez ######################################################################################## def add_emoticon_features(df,", "smiley = 1 if set(matches).intersection( crys ): crying = 1 if set(matches).intersection( winks", "sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col,", "laugh = 1 if set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection( happycrys", "set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection( cheekys ): cheeky = 1", "= re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions in this library", "the text that is expecte to have been generated in the intial simple", "0 cheeky = 0 crying = 0 sad = 0 shock = 0", "col): emos = 0 smiley = 0 wink = 0 kiss = 0", "+ sad + shock + sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent", "generated in the intial simple text function run by the program. This will", "= 1 if set(matches).intersection( winks ): wink = 1 if set(matches).intersection( kisses ):", "URLS and HTML tags before trying to match emoticons. Some references used when", "happycry = 1 pos = smiley + wink + kiss + happycry +", "sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re", "when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\"", "load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\")", "program. This will remove URLS and HTML tags before trying to match emoticons.", "fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if", "in the column and add a set of features that indicate both the", "function run by the program. This will remove URLS and HTML tags before", "presence of emoticons. \"\"\" rez = df.copy() for col in columns: rez =", "smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses", "sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches", "from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs =", "emos = len(matches) if set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection( crys", "[col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad', col+'_emo_shock', col+'_emo_sceptic', col+'_emo_pos', col+'_emo_neg',", "a column name. Check for emoticons in the column and add a set", "cheeky neg = crying + sad + shock + sceptic sent = pos", "0 crying = 0 sad = 0 shock = 0 sceptic = 0", "def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and a set of column", "= load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads =", "kiss = 0 happycry = 0 laugh = 0 cheeky = 0 crying", "coding: utf-8 -*- import pandas as pd import numpy as np import codecs", "rudimentary regex based tag removal and unescaped version of the text that is", "df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink',", "1 if set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection( sads ): sad", "in this library will add columns to a dataframe that indivate whether there", "and HTML tags before trying to match emoticons. Some references used when considering", "features that indicate both the presence and emotional flavour of the emoticon. \"\"\"", "tags there is a rudimentary regex based tag removal and unescaped version of", "= 1 if set(matches).intersection( happycrys ): happycry = 1 pos = smiley +", "(B will not be matched. To avoid matching characters inside document markup language", "if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches", "import load_word_pattern from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\")", "add columns to a dataframe that indivate whether there are emoticons in certain", "the likelihood of false positive matches in text containing brackets For example emoticons:", "if set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection( happycrys ): happycry =", "will not be matched. To avoid matching characters inside document markup language tags", "https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given", "laugh = 0 cheeky = 0 crying = 0 sad = 0 shock", "import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks", "to have been generated in the intial simple text function run by the", "= df.copy() for col in columns: rez = add_emoticon_features(rez, col) return rez ########################################################################################", "emoticons because of the likelihood of false positive matches in text containing brackets", "brackets For example emoticons: 8) or (B will not be matched. To avoid", "pandas as pd import numpy as np import codecs import re from .process", "crying = 1 if set(matches).intersection( winks ): wink = 1 if set(matches).intersection( kisses", "= 1 if set(matches).intersection( sads ): sad = 1 if set(matches).intersection( shocks ):", "have deliberately ignored certain emoticons because of the likelihood of false positive matches", "neg = crying + sad + shock + sceptic sent = pos -", "= 0 happycry = 0 laugh = 0 cheeky = 0 crying =", "= remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if", "sad = 0 shock = 0 sceptic = 0 if x[col]==x[col]: text =", "that is expecte to have been generated in the intial simple text function", "deliberately ignored certain emoticons because of the likelihood of false positive matches in", "if set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection( cheekys ): cheeky =", "): wink = 1 if set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection(", "regexes I have deliberately ignored certain emoticons because of the likelihood of false", "sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features,", "Add features that detect the presence of emoticons. \"\"\" rez = df.copy() for", "+ sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] =", "if set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection( laughs ): laugh =", "= crying + sad + shock + sceptic sent = pos - neg", "return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad', col+'_emo_shock', col+'_emo_sceptic', col+'_emo_pos',", "+ happycry + laugh + cheeky neg = crying + sad + shock", "load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\")", "): cheeky = 1 if set(matches).intersection( happycrys ): happycry = 1 pos =", "load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\"", "used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication", "bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions in this", "if set(matches).intersection( shocks ): shock = 1 if set(matches).intersection( sceptics ): sceptic =", "matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos =", "0 happycry = 0 laugh = 0 cheeky = 0 crying = 0", "inside document markup language tags there is a rudimentary regex based tag removal", "\"\"\" texturizer.emoticons: Emoticon Recognition Text Features The functions in this library will add", "return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col) ] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ########################################################################################", "len(matches) if set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection( crys ): crying", "is a rudimentary regex based tag removal and unescaped version of the text", "set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection( crys ): crying = 1", "Given a pandas dataframe and a column name. Check for emoticons in the", "Check for emoticons in the column and add a set of features that", "): sceptic = 1 if set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection(", "0 sad = 0 shock = 0 sceptic = 0 if x[col]==x[col]: text", "fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition", "crying + sad + shock + sceptic sent = pos - neg return", "return rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and a", "0 sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) )", "+ shock + sceptic sent = pos - neg return emos,smiley,wink,kiss,happycry,laugh,cheeky,crying,sad,shock,sceptic,pos,neg,sent df[ get_emoticon_col_list(col)", "= load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys =", "= 0 kiss = 0 happycry = 0 laugh = 0 cheeky =", "represent one of the more common emotions. NOTE: In developing these regexes I", "0 kiss = 0 happycry = 0 laugh = 0 cheeky = 0", "laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys", "those emoticons represent one of the more common emotions. NOTE: In developing these", "that detect the presence of emoticons. \"\"\" rez = df.copy() for col in", "rez ######################################################################################## def add_emoticon_features(df, col): \"\"\" Given a pandas dataframe and a column", "these regexes I have deliberately ignored certain emoticons because of the likelihood of", "0 shock = 0 sceptic = 0 if x[col]==x[col]: text = remove_urls_and_tags( remove_escapes_and_non_printable(", "\"\"\" Given a pandas dataframe and a column name. Check for emoticons in", "= bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles", "] = df.apply(cal_features, col=col, axis=1, result_type=\"expand\") return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons',", "smiles ): smiley = 1 if set(matches).intersection( crys ): crying = 1 if", "load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex)", "functions in this library will add columns to a dataframe that indivate whether", "emoticons in certain columns of text, and whether those emoticons represent one of", "x[col] ) ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0:", "remove_urls_and_tags( remove_escapes_and_non_printable( x[col] ) ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0", "emoticons represent one of the more common emotions. NOTE: In developing these regexes", "set(matches).intersection( sads ): sad = 1 if set(matches).intersection( shocks ): shock = 1", "based tag removal and unescaped version of the text that is expecte to", "1 if set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection( cheekys ): cheeky", "kisses ): kiss = 1 if set(matches).intersection( sads ): sad = 1 if", "https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe", "have been generated in the intial simple text function run by the program.", "because of the likelihood of false positive matches in text containing brackets For", "not be matched. To avoid matching characters inside document markup language tags there", "bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ):", "+ laugh + cheeky neg = crying + sad + shock + sceptic", "likelihood of false positive matches in text containing brackets For example emoticons: 8)", "features that detect the presence of emoticons. \"\"\" rez = df.copy() for col", "1 if set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection( happycrys ): happycry", "): smiley = 1 if set(matches).intersection( crys ): crying = 1 if set(matches).intersection(", "In developing these regexes I have deliberately ignored certain emoticons because of the", "text, and whether those emoticons represent one of the more common emotions. NOTE:", "of column names. Add features that detect the presence of emoticons. \"\"\" rez", "= 1 if set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection( happycrys ):", "load_word_pattern from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs", "certain emoticons because of the likelihood of false positive matches in text containing", "a pandas dataframe and a column name. Check for emoticons in the column", "more common emotions. NOTE: In developing these regexes I have deliberately ignored certain", "import load_word_list from .process import load_word_pattern from .process import remove_urls_and_tags from .process import", "remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\")", "dataframe and a set of column names. Add features that detect the presence", "= 0 smiley = 0 wink = 0 kiss = 0 happycry =", ") matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos", "crys ): crying = 1 if set(matches).intersection( winks ): wink = 1 if", "get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad', col+'_emo_shock', col+'_emo_sceptic',", ".process import load_word_list from .process import load_word_pattern from .process import remove_urls_and_tags from .process", "shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex", "if set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection( crys ): crying =", "a pandas dataframe and a set of column names. Add features that detect", "winks = load_word_list(\"emoticons-wink.dat\") cheekys = load_word_list(\"emoticons-wink.dat\") kisses = load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys", "the more common emotions. NOTE: In developing these regexes I have deliberately ignored", "happycry = 0 laugh = 0 cheeky = 0 crying = 0 sad", "+ cheeky neg = crying + sad + shock + sceptic sent =", "a set of column names. Add features that detect the presence of emoticons.", "def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry', col+'_emo_sad', col+'_emo_shock',", "dataframe that indivate whether there are emoticons in certain columns of text, and", "example emoticons: 8) or (B will not be matched. To avoid matching characters", "df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky', col+'_emo_cry',", "NOTE: In developing these regexes I have deliberately ignored certain emoticons because of", "Some references used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98", "import remove_escapes_and_non_printable smiles = load_word_list(\"emoticons-smile.dat\") laughs = load_word_list(\"emoticons-laugh.dat\") winks = load_word_list(\"emoticons-wink.dat\") cheekys =", "sceptic = 1 if set(matches).intersection( laughs ): laugh = 1 if set(matches).intersection( cheekys", "the column and add a set of features that indicate both the presence", "wink = 1 if set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection( sads", "return df ######################################################################################## def get_emoticon_col_list(col): return [col+'_emoticons', col+'_emo_smiley', col+'_emo_wink', col+'_emo_kiss', col+'_emo_happycry', col+'_emo_laugh', col+'_emo_cheeky',", "column names. Add features that detect the presence of emoticons. \"\"\" rez =", "https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def add_text_emoticon_features(df, columns): \"\"\" Given a pandas dataframe and", "matches.extend(bck_matches) emos = len(matches) if set(matches).intersection( smiles ): smiley = 1 if set(matches).intersection(", "= smiley + wink + kiss + happycry + laugh + cheeky neg", "= 1 if set(matches).intersection( shocks ): shock = 1 if set(matches).intersection( sceptics ):", "text that is expecte to have been generated in the intial simple text", "The functions in this library will add columns to a dataframe that indivate", "load_word_list from .process import load_word_pattern from .process import remove_urls_and_tags from .process import remove_escapes_and_non_printable", "which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ######################################################################################## def", "= fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches) emos = len(matches)", "): shock = 1 if set(matches).intersection( sceptics ): sceptic = 1 if set(matches).intersection(", "1 if set(matches).intersection( happycrys ): happycry = 1 pos = smiley + wink", "column and add a set of features that indicate both the presence and", "name. Check for emoticons in the column and add a set of features", "add a set of features that indicate both the presence and emotional flavour", "import numpy as np import codecs import re from .process import load_word_list from", "indivate whether there are emoticons in certain columns of text, and whether those", "): laugh = 1 if set(matches).intersection( cheekys ): cheeky = 1 if set(matches).intersection(", ") ) matches = fwd_re.findall(text) bck_matches = bck_re.findall(text) if len(matches)>0 or len(bck_matches)>0: matches.extend(bck_matches)", "fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\"", "the program. This will remove URLS and HTML tags before trying to match", "0 smiley = 0 wink = 0 kiss = 0 happycry = 0", "= 0 laugh = 0 cheeky = 0 crying = 0 sad =", "simple text function run by the program. This will remove URLS and HTML", "load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks = load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\"", "columns): \"\"\" Given a pandas dataframe and a set of column names. Add", "= re.compile(fwd_regex) bck_regex = \"[@*\\\\|/()<>{}\\[\\]]{1,2}[-=^]{0,2}['’`]{0,1}[:;]\" bck_re = re.compile(bck_regex) \"\"\" texturizer.emoticons: Emoticon Recognition Text", "this library will add columns to a dataframe that indivate whether there are", "text function run by the program. This will remove URLS and HTML tags", "1 if set(matches).intersection( crys ): crying = 1 if set(matches).intersection( winks ): wink", "be matched. To avoid matching characters inside document markup language tags there is", "= load_word_list(\"emoticons-kiss.dat\") happycrys = load_word_list(\"emoticons-happy-cry.dat\") crys = load_word_list(\"emoticons-cry.dat\") sads = load_word_list(\"emoticons-sad.dat\") shocks =", "= load_word_list(\"emoticons-shock.dat\") sceptics = load_word_list(\"emoticons-sceptical.dat\") fwd_regex = \"[:;8BX]['’`]{0,1}[-=^oc]{0,2}[DPO0J3ox,Þþb@*\\\\|/()<>{}\\[\\]]{1,2}\" fwd_re = re.compile(fwd_regex) bck_regex =", "match emoticons. Some references used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace", "winks ): wink = 1 if set(matches).intersection( kisses ): kiss = 1 if", "laughs ): laugh = 1 if set(matches).intersection( cheekys ): cheeky = 1 if", "happycrys ): happycry = 1 pos = smiley + wink + kiss +", "library will add columns to a dataframe that indivate whether there are emoticons", "considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/ https://www.researchgate.net/publication/266269913_From_Emoticon_to_Universal_Symbolic_Signs_Can_Written_Language_Survive_in_Cyberspace https://www.sciencedirect.com/science/article/abs/pii/S0950329317300939 https://www.semanticscholar.org/paper/An-Approach-towards-Text-to-Emoticon-Conversion-and-Jha/3b81505fa7fec81563b2dafae3939fa1b07f3a98 https://www.qualitative-research.net/index.php/fqs/article/view/175/391 https://www.researchgate.net/publication/221622114_M_Textual_Affect_Sensing_for_Sociable_and_Expressive_Online_Communication \"\"\" ########################################################################################", "= 1 if set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection( sads ):", "document markup language tags there is a rudimentary regex based tag removal and", "will add columns to a dataframe that indivate whether there are emoticons in", "set(matches).intersection( winks ): wink = 1 if set(matches).intersection( kisses ): kiss = 1", "if set(matches).intersection( crys ): crying = 1 if set(matches).intersection( winks ): wink =", "cheeky = 1 if set(matches).intersection( happycrys ): happycry = 1 pos = smiley", "For example emoticons: 8) or (B will not be matched. To avoid matching", "column name. Check for emoticons in the column and add a set of", "run by the program. This will remove URLS and HTML tags before trying", "= 0 crying = 0 sad = 0 shock = 0 sceptic =", "to match emoticons. Some references used when considering which empticons to include: https://www.unglobalpulse.org/2014/10/emoticon-use-in-arabic-spanish-and-english-tweets/", "that indivate whether there are emoticons in certain columns of text, and whether", "there is a rudimentary regex based tag removal and unescaped version of the", "if set(matches).intersection( kisses ): kiss = 1 if set(matches).intersection( sads ): sad =", "detect the presence of emoticons. \"\"\" rez = df.copy() for col in columns:" ]
[ "operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um pouco sobre você'),", "'0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um pouco", "Django 3.0.8 on 2020-07-24 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ]", "3.0.8 on 2020-07-24 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "on 2020-07-24 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "by Django 3.0.8 on 2020-07-24 02:09 from django.db import migrations, models class Migration(migrations.Migration):", "Generated by Django 3.0.8 on 2020-07-24 02:09 from django.db import migrations, models class", "] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um pouco sobre", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations =", "Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia',", "2020-07-24 02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts',", "[ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale", "02:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'),", "<filename>accounts/migrations/0002_auto_20200724_0209.py<gh_stars>0 # Generated by Django 3.0.8 on 2020-07-24 02:09 from django.db import migrations,", "# Generated by Django 3.0.8 on 2020-07-24 02:09 from django.db import migrations, models", "dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True,", "[ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um pouco sobre você'), ), ]", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations", "models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField(", "('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um", "class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil',", "= [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400, verbose_name='Fale um pouco sobre você'), ),", "= [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='perfil', name='biografia', field=models.TextField(blank=True, max_length=400," ]
[]
[ "# Searching for the longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i]", "in hova: if word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words)", "meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0 for word in", "= deepcopy(ret) if skipped == len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words)", "break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for", "len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and", "for the longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary,", "= deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped = 0 hova", "tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped", "len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list):", "[] dictionary = {} #init dict for word in words: hova=[] for i", "kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation print() for", "> len(longest): longest = deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)):", "longest = deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest =", "== len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print('", "puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break", "\"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\",", "skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if", "Closed part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0", "continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) > len(longest):", "if word != i: for j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk", "skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest)", "for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation print()", "words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0", "[\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\",", "elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest)", "if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk", "\"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\",", "\"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\",", "i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if str_of_words[-j:]", "deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest =", "if word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret", "attacher(list_of_words) for i in words: if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))):", "longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i]", "= deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest", "len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace:", "if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []):", "tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:]", "== len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words,", "= deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\",", "print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words =", "part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and", "dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word)", "elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest =", "in words: if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány", "hova=[] for i in words: if word != i: for j in range(1,1+min(len(i),len(word))):", "lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista:", "<gh_stars>0 from copy import deepcopy # Closed part def create_path(word, dictionary): lista =", "word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret =", "0 hova = [] str_of_words = attacher(list_of_words) for i in words: if str_of_words", "and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest =", "nézünk meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary:", "[] str_of_words = attacher(list_of_words) for i in words: if str_of_words != i: for", "!= i: for j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if", "for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp", "== len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova):", "len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova): if len(list_of_words) > len(longest): longest", "# Closed part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True: if", "deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif", "dictionary[kiiras]) # Searching for the longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword])", "return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\",", "\"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\",", "j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if str_of_words[-j:] == i[:j]:", "= []): skipped = 0 hova = [] str_of_words = attacher(list_of_words) for i", "def recursive(dictionary,list_of_words,longest = []): skipped = 0 for word in dictionary[list_of_words[-1]]: if word", "\"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\",", "list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest)", "longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest:", "attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if", "word in words: hova=[] for i in words: if word != i: for", "= [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\",", "# j: hány betűt nézünk meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova", "words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\",", "betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0 for", "deepcopy(ret) if skipped == len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif", "in words: if word != i: for j in range(1,1+min(len(i),len(word))): # j: hány", "\"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir = [] dictionary", "words: if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt", "hány betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0", "longest) if len(longest) < len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if", "str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0 for word in hova: if", "word in hova: if word in list_of_words: skipped += 1 continue cpy =", "for i in words: if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): #", "< len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest)", "\"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = []", "= [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0])", "= words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] ==", "\"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\",", "j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if word[-j:] == i[:j]:", "if str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0 for word in hova:", "in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if word[-j:] == i[:j]: hova.append(i)", "lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i", "ret = recursive_2(cpy, longest) if len(ret) > len(longest): longest = deepcopy(ret) elif len(ret)", "not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0]", "len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) <", "word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1 continue cpy =", "recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest = deepcopy(ret) if skipped ==", "words: if word != i: for j in range(1,1+min(len(i),len(word))): # j: hány betűt", "< len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped", "> len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)):", "\"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\",", "longest = []): skipped = 0 hova = [] str_of_words = attacher(list_of_words) for", "\"nemo\", \"sack\"] attached = [] kiir = [] dictionary = {} #init dict", "words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]:", "kiir = [] dictionary = {} #init dict for word in words: hova=[]", "= deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words)", "[]): skipped = 0 for word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped", "[]): skipped = 0 hova = [] str_of_words = attacher(list_of_words) for i in", "break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest", "\"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached =", "== len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest)", "tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0 for", "concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] =", "== i[:j]: hova.append(i) break #stop = 0 for word in hova: if word", "from copy import deepcopy # Closed part def create_path(word, dictionary): lista = [word]", "i: for j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if word[-j:]", "print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation print() for i,firstword in enumerate(words):", "Searching for the longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] =", "nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop = 0 for word", "in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary,", "\"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\",", "\"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir = [] dictionary =", "\"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\",", "word != i: for j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg", "longest) if len(ret) > len(longest): longest = deepcopy(ret) elif len(ret) == len(longest) and", "i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for", "len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova): if len(list_of_words) >", "skipped == len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) ==", "\"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\",", "len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return", "return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j", "def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))):", "replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\",", "\"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\",", "+= 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if", "in dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words)", "len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []):", "for word in words: hova=[] for i in words: if word != i:", "= [] str_of_words = attacher(list_of_words) for i in words: if str_of_words != i:", "meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras,", "word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) #", "copy import deepcopy # Closed part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]]", "deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped = 0 hova = [] str_of_words", "recursive_2(cpy, longest) if len(ret) > len(longest): longest = deepcopy(ret) elif len(ret) == len(longest)", "dictionary = {} #init dict for word in words: hova=[] for i in", "< len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest):", "deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped = 0 hova =", "for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] = recursive_2(kiir[i]) #", "return tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0 for word in dictionary[list_of_words[-1]]:", "True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista", "len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest", "break #stop = 0 for word in hova: if word in list_of_words: skipped", "len(ret) > len(longest): longest = deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) <", "\"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\",", "len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and", "if skipped == len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words)", "cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest) < len(ret):", "= recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest = deepcopy(ret) if skipped", "deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest", "for word in hova: if word in list_of_words: skipped += 1 continue cpy", "\"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\",", "!= i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if", "\"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\",", "\"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir", "[word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else:", "str_of_words = attacher(list_of_words) for i in words: if str_of_words != i: for j", "\"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\",", "def recursive_2(list_of_words, longest = []): skipped = 0 hova = [] str_of_words =", "\"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\",", "len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest", "return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped = 0 hova = []", "len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest", "\"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir = []", "if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def", "len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words)", "cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest = deepcopy(ret)", "deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if", "= {} #init dict for word in words: hova=[] for i in words:", "1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) >", "\"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\",", "= []): skipped = 0 for word in dictionary[list_of_words[-1]]: if word in list_of_words:", "len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped =", "\"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\",", "dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp =", "words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0 for word in", "= deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words)", "in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation print() for i,firstword", "len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words", "hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the", "for i in words: if word != i: for j in range(1,1+min(len(i),len(word))): #", "for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp", "if len(longest) < len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words)", "= recursive_2(cpy, longest) if len(ret) > len(longest): longest = deepcopy(ret) elif len(ret) ==", "'+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\",", "\"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached", "print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] = recursive_2(kiir[i])", "longest = deepcopy(ret) if skipped == len(hova): if len(list_of_words) > len(longest): longest =", "\"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\",", "dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation print() for i,firstword in", "create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not", "= 0 for word in hova: if word in list_of_words: skipped += 1", "skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) ==", "\"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\",", "j: hány betűt nézünk meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for", "= 0 hova = [] str_of_words = attacher(list_of_words) for i in words: if", "in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for", "ret = recursive(dictionary, cpy, longest) if len(longest) < len(ret): longest = deepcopy(ret) if", "attached = [] kiir = [] dictionary = {} #init dict for word", "and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp", "\"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\",", "lista.append(dictionary[lista[-1]][0]) else: break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in", "= [] kiir = [] dictionary = {} #init dict for word in", "= deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret)", "\"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir =", "dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching for the longest concatenation", "deepcopy # Closed part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True:", "in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:]", "longest = deepcopy(list_of_words) return deepcopy(longest) def recursive_2(list_of_words, longest = []): skipped = 0", "skipped = 0 hova = [] str_of_words = attacher(list_of_words) for i in words:", "\"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\",", "in words: hova=[] for i in words: if word != i: for j", "\"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\",", "longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest =", "recursive(dictionary,list_of_words,longest = []): skipped = 0 for word in dictionary[list_of_words[-1]]: if word in", "def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0]", "else: break return lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)):", "range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if word[-j:] == i[:j]: hova.append(i) break", "dict for word in words: hova=[] for i in words: if word !=", "deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return", "len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(list_of_words) return deepcopy(longest) def", "hány betűt nézünk meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras", "= deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) > len(longest): longest =", "str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg", "= 0 for word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1", "hova: if word in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word)", "1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest)", "#init dict for word in words: hova=[] for i in words: if word", "for j in range(1,1+min(len(i),len(word))): # j: hány betűt nézünk meg if word[-j:] ==", "deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) > len(longest): longest = deepcopy(ret)", "in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] = recursive_2(kiir[i]) # Kiiratás print(len(kiir[i]),", "i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] = recursive_2(kiir[i]) # Kiiratás", "if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words))", "+= 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret)", "words: hova=[] for i in words: if word != i: for j in", "== len(hova): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest)", "\"lesson\", \"one\", \"nemo\", \"sack\"] attached = [] kiir = [] dictionary = {}", "# j: hány betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop", "\"sack\"] attached = [] kiir = [] dictionary = {} #init dict for", "0 for word in hova: if word in list_of_words: skipped += 1 continue", "if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras])", "range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break", "recursive_2(list_of_words, longest = []): skipped = 0 hova = [] str_of_words = attacher(list_of_words)", "deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\",", "= attacher(list_of_words) for i in words: if str_of_words != i: for j in", "= [] dictionary = {} #init dict for word in words: hova=[] for", "len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova): if", "while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in lista: lista.append(dictionary[lista[-1]][0]) else: break return", "len(longest) < len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) >", "deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\",", "= deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest))", "for word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1 continue cpy", "#stop = 0 for word in hova: if word in list_of_words: skipped +=", "dictionary): lista = [word] puffer=[dictionary[word]] while True: if len(dictionary[lista[-1]])>0 and dictionary[lista[-1]][0] not in", "'+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\",", "and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova): if len(list_of_words)", "\"one\", \"nemo\", \"sack\"] attached = [] kiir = [] dictionary = {} #init", "\"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\",", "continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy, longest) if len(longest) <", "and len(attacher(list_of_words)) < len(attacher(longest)): print(' longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest))", "lista def attacher(words_in_a_list): tmp = words_in_a_list[0] for i in range(1,len(words_in_a_list)): for j in", "cpy, longest) if len(longest) < len(ret): longest = deepcopy(ret) if skipped == len(dictionary[list_of_words[-1]]):", "print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\", \"writer\", \"grate\", \"ignorant\",", "enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i]) kiir[i] = recursive_2(kiir[i]) # Kiiratás print(len(kiir[i]), attacher(kiir[i]))", "len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped ==", "hova = [] str_of_words = attacher(list_of_words) for i in words: if str_of_words !=", "\"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\",", "range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest =", "in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i)", "i in range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp +=", "for j in range(1,1+min(len(str_of_words),len(i))): # j: hány betűt nézünk meg if str_of_words[-j:] ==", "i[:j]: hova.append(i) break #stop = 0 for word in hova: if word in", "\"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\", \"rex\", \"lesson\", \"one\", \"nemo\", \"sack\"]", "i in words: if word != i: for j in range(1,1+min(len(i),len(word))): # j:", "elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest = deepcopy(ret) if skipped", "import deepcopy # Closed part def create_path(word, dictionary): lista = [word] puffer=[dictionary[word]] while", "\"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\", \"expansion\",", "longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\", \"zonked\", \"rush\",", "i in words: if str_of_words != i: for j in range(1,1+min(len(str_of_words),len(i))): # j:", "the longest concatenation print() for i,firstword in enumerate(words): kiir.append([firstword]) #kiir[i] = recursive(dictionary, kiir[i])", "cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) > len(longest): longest = deepcopy(ret) elif", "skipped = 0 for word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped +=", "if len(ret) > len(longest): longest = deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words))", "cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy, longest) if len(ret) > len(longest): longest", "len(longest): longest = deepcopy(ret) elif len(ret) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest", "+= words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0 for word", "\"noxious\", \"desk\", \"shade\", \"error\", \"great\", \"flagrant\", \"cute\", \"plan\", \"daughter\", \"dare\", \"giraffe\", \"airplane\", \"aunt\",", "== i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in dictionary: print(kiiras, dictionary[kiiras]) # Searching", "longest: '+attacher(longest)) longest = deepcopy(list_of_words) print(' replace: '+attacher(longest)) return deepcopy(longest) words = [\"blood\",", "longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): longest =", "j: hány betűt nézünk meg if str_of_words[-j:] == i[:j]: hova.append(i) break #stop =", "betűt nézünk meg if word[-j:] == i[:j]: hova.append(i) break dictionary[word]=hova for kiiras in", "\"dare\", \"giraffe\", \"airplane\", \"aunt\", \"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\",", "len(longest): longest = deepcopy(list_of_words) elif len(list_of_words) == len(longest) and len(attacher(list_of_words)) < len(attacher(longest)): print('", "[] kiir = [] dictionary = {} #init dict for word in words:", "hova.append(i) break #stop = 0 for word in hova: if word in list_of_words:", "\"grate\", \"ignorant\", \"cloudy\", \"chicken\", \"illness\", \"useless\", \"challenge\", \"comfortable\", \"noxious\", \"desk\", \"shade\", \"error\", \"great\",", "in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest", "\"men\", \"vase\", \"cheap\", \"obsolete\", \"tomatoes\", \"receipt\", \"festive\", \"screeching\", \"moor\", \"ingredients\", \"great\", \"skill\", \"us\",", "0 for word in dictionary[list_of_words[-1]]: if word in list_of_words: skipped += 1 continue", "in list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive_2(cpy,", "tmp def recursive(dictionary,list_of_words,longest = []): skipped = 0 for word in dictionary[list_of_words[-1]]: if", "{} #init dict for word in words: hova=[] for i in words: if", "j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def", "range(1,len(words_in_a_list)): for j in range(1,1+min(len(tmp),len(words_in_a_list[i]))): if tmp[-j:] == words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return", "< len(attacher(longest)): longest = deepcopy(ret) if skipped == len(hova): if len(list_of_words) > len(longest):", "== words_in_a_list[i][:j]: tmp += words_in_a_list[i][j:] return tmp def recursive(dictionary,list_of_words,longest = []): skipped =", "list_of_words: skipped += 1 continue cpy = deepcopy(list_of_words) cpy.append(word) ret = recursive(dictionary, cpy,", "if skipped == len(dictionary[list_of_words[-1]]): if len(list_of_words) > len(longest): longest = deepcopy(list_of_words) elif len(list_of_words)" ]
[ "instance, value): if value is None and self.allow_none: pass elif value not in", "needs to be defined in subclasses for this to work as a real", "def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set", "ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none", "allowed_values self.allow_none = allow_none def __set__(self, instance, value): if value is None and", "and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of", "= prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs to be defined", ":param instance: :param value: :return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def", "def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass):", "raise TypeError(f'Value: \"{value}\" is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value", "allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self, instance, value): if", "as a real discriptor :param instance: :param value: :return: \"\"\" def __get__(self, instance,", "= value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values", "allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self, instance,", "in subclasses for this to work as a real discriptor :param instance: :param", "prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self, instance, value):", "allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self, instance, value): if", "del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type", "value: :return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del", "value): if value is None and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise", "= allowed_type self.allow_none = allow_none def __set__(self, instance, value): if value is None", "\"{value}\" is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass):", "in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the available options: {str(self.allowed_values)}') instance.__dict__[self.prop_name]", "self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] =", "type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name)", "import abc class DescriptorClass(abc.ABC): def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self,", "this to work as a real discriptor :param instance: :param value: :return: \"\"\"", "discriptor :param instance: :param value: :return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name]", "abc class DescriptorClass(abc.ABC): def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance,", "instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none", "def __set__(self, instance, value): if value is None and self.allow_none: pass elif not", "pass elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the", "owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type,", "@abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs to be defined in subclasses", "if value is None and self.allow_none: pass elif value not in self.allowed_values: raise", "value is None and self.allow_none: pass elif value not in self.allowed_values: raise ValueError(f'Value:", "self.allow_none = allow_none def __set__(self, instance, value): if value is None and self.allow_none:", "self.allow_none: pass elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of", "prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs to", "__set__(self, instance, value): if value is None and self.allow_none: pass elif not isinstance(value,", "instance: :param value: :return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self,", "= allow_none def __set__(self, instance, value): if value is None and self.allow_none: pass", "if value is None and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value:", "{str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values", "value): if value is None and self.allow_none: pass elif value not in self.allowed_values:", "value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the available options:", "TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none", "def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name)", "elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the required type:", "instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True):", "allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self, instance,", "value): \"\"\" Set needs to be defined in subclasses for this to work", "Set needs to be defined in subclasses for this to work as a", "return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name,", "__set__(self, instance, value): \"\"\" Set needs to be defined in subclasses for this", "class DescriptorClass(abc.ABC): def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value):", "\"\"\" Set needs to be defined in subclasses for this to work as", "super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self, instance, value): if value", "is None and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is", "def __set__(self, instance, value): if value is None and self.allow_none: pass elif value", "the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name,", "<filename>pbk/util/descriptors.py import abc class DescriptorClass(abc.ABC): def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def", "isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name]", "and self.allow_none: pass elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not", "pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the required", "of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values,", "instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type =", "is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def", ":return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name]", "= allowed_values self.allow_none = allow_none def __set__(self, instance, value): if value is None", "self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the", "raise ValueError(f'Value: \"{value}\" is not of the available options: {str(self.allowed_values)}') instance.__dict__[self.prop_name] = value", "value is None and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\"", "self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self, instance, value): if value is", "value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none", "instance, value): \"\"\" Set needs to be defined in subclasses for this to", "to work as a real discriptor :param instance: :param value: :return: \"\"\" def", "defined in subclasses for this to work as a real discriptor :param instance:", "subclasses for this to work as a real discriptor :param instance: :param value:", "instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self,", "def __set__(self, instance, value): \"\"\" Set needs to be defined in subclasses for", "def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def", "allowed_type self.allow_none = allow_none def __set__(self, instance, value): if value is None and", "super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self, instance, value): if value", "self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the available options: {str(self.allowed_values)}') instance.__dict__[self.prop_name] =", "to be defined in subclasses for this to work as a real discriptor", "work as a real discriptor :param instance: :param value: :return: \"\"\" def __get__(self,", "required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True):", "self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs to be", "\"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class", "DescriptorClass(abc.ABC): def __init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\"", "not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not of the required type: {str(self.allowed_type)}')", "a real discriptor :param instance: :param value: :return: \"\"\" def __get__(self, instance, owner):", "__delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type", "def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def", "None and self.allow_none: pass elif not isinstance(value, self.allowed_type): raise TypeError(f'Value: \"{value}\" is not", "real discriptor :param instance: :param value: :return: \"\"\" def __get__(self, instance, owner): return", "prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self, instance, value):", "class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none =", "TypeError(f'Value: \"{value}\" is not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class", "__init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self,", "instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values =", "not of the required type: {str(self.allowed_type)}') instance.__dict__[self.prop_name] = value class ValueChecked(DescriptorClass): def __init__(self,", "instance, value): if value is None and self.allow_none: pass elif not isinstance(value, self.allowed_type):", "not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the available options: {str(self.allowed_values)}')", "__get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance): del instance.__dict__[self.prop_name] class TypeChecked(DescriptorClass): def", ":param value: :return: \"\"\" def __get__(self, instance, owner): return instance.__dict__[self.prop_name] def __delete__(self, instance):", "is None and self.allow_none: pass elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\"", "elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is not of the available", "__set__(self, instance, value): if value is None and self.allow_none: pass elif value not", "allow_none def __set__(self, instance, value): if value is None and self.allow_none: pass elif", "__init__(self, allowed_values, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_values = allowed_values self.allow_none = allow_none def __set__(self,", "be defined in subclasses for this to work as a real discriptor :param", "__init__(self, prop_name): self.prop_name = prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs", "prop_name @abc.abstractmethod def __set__(self, instance, value): \"\"\" Set needs to be defined in", "for this to work as a real discriptor :param instance: :param value: :return:", "None and self.allow_none: pass elif value not in self.allowed_values: raise ValueError(f'Value: \"{value}\" is", "class TypeChecked(DescriptorClass): def __init__(self, allowed_type, prop_name, allow_none=True): super().__init__(prop_name=prop_name) self.allowed_type = allowed_type self.allow_none =", "self.allowed_type = allowed_type self.allow_none = allow_none def __set__(self, instance, value): if value is" ]
[ "range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1]) + \"", "str(points[i,1]) + \" \" + str(points[i,2]) + \" \" + str(color[0]) + \"", "+ \" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\") else:", "= npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points", "pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi']", "+ str(points[i,2]) + \" \" + str(color[0]) + \" \" + str(color[1]) +", "f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1]) + \" \"", "in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1]", "npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples =", "if points.shape[1] == 4: for i in range(points.shape[0]): f.write( \"v \" + str(points[i,0])", "str(points[i,0]) + \" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\")", "= npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points", "np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in range(points.shape[0]): f.write(", "\" + str(points[i,1]) + \" \" + str(points[i,2]) + \" \" + str(color[0])", "npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if", "\" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \" \" +", "points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0)", "\" + str(color[0]) + \" \" + str(color[1]) + \" \" + str(color[2])", "if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in", "npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples =", "0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1]) + \"", "+ str(points[i,1]) + \" \" + str(points[i,2]) + \" \" + str(color[0]) +", "\" + str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]): color = ((points[i,4:7]", "in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) +", "== 4: for i in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \"", "+ str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]): color = ((points[i,4:7] +", "= np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if", "npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i", "\" + str(points[i,2]) + \" \" + str(color[0]) + \" \" + str(color[1])", "+ \" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \" \"", "i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0])", "np npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0)", "= np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in range(points.shape[0]):", "= npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for", "range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \"", "\"v \" + str(points[i,0]) + \" \" + str(points[i,1]) + \" \" +", "in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples", "\" \" + str(color[0]) + \" \" + str(color[1]) + \" \" +", "negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4:", "\" \" + str(points[i,2]) + \" \" + str(color[0]) + \" \" +", "+ \" \" + str(color[0]) + \" \" + str(color[1]) + \" \"", "+ str(color[0]) + \" \" + str(color[1]) + \" \" + str(color[2]) +", "str(points[i,2]) + \" \" + str(color[0]) + \" \" + str(color[1]) + \"", "+ str(points[i,0]) + \" \" + str(points[i,1]) + \" \" + str(points[i,2]) +", "+ \"\\n\") else: for i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write(", "+ \" \" + str(points[i,2]) + \" \" + str(color[0]) + \" \"", "str(color[0]) + \" \" + str(color[1]) + \" \" + str(color[2]) + \"\\n\")", "\" + str(points[i,0]) + \" \" + str(points[i,1]) + \" \" + str(points[i,2])", "np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f=", "= ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \" \" +", "import numpy as np npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg']", "negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi']", "((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1])", "points.shape[1] == 4: for i in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) +", "npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points =", "points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in", "'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if", "else: for i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \"", "f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in range(points.shape[0]): f.write( \"v \"", "npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points =", "\" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\") else: for", "\" \" + str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]): color =", "posSamples = npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile:", "np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in", "npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] ==", "'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile:", "for i in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \" \" +", "numpy as np npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points", "+ str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\") else: for i in", "print(points.shape[0]) f= open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in range(points.shape[0]): f.write( \"v", "+ \" \" + str(color[1]) + \" \" + str(color[2]) + \"\\n\") f.close()", "4: for i in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \" \"", "str(points[i,0]) + \" \" + str(points[i,1]) + \" \" + str(points[i,2]) + \"", "points = np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0)", "str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8')", "str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]):", "\"\\n\") else: for i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v", "= np.append(points,pospoiSamples,axis=0) if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0])", "+ 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1]) +", "as np npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points =", "= np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi'", "i in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1])", "for i in range(points.shape[0]): color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" +", "if 'negpoi' in npzfile: negpoiSamples = npzfile['negpoi'] points = np.append(points,negpoiSamples,axis=0) print(points.shape[0]) f= open(\"sample.obj\",\"w+\")", "np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples = npzfile['pospoi'] points = np.append(points,pospoiSamples,axis=0) if 'negpoi'", "in range(points.shape[0]): f.write( \"v \" + str(points[i,0]) + \" \" + str(points[i,1]) +", "= npzfile['pos'] negSamples = npzfile['neg'] points = np.append(posSamples,negSamples,axis=0) if 'pospoi' in npzfile: pospoiSamples", "+ \" \" + str(points[i,2]) + \"\\n\") else: for i in range(points.shape[0]): color", "\" + str(points[i,1]) + \" \" + str(points[i,2]) + \"\\n\") else: for i", "open(\"sample.obj\",\"w+\") if points.shape[1] == 4: for i in range(points.shape[0]): f.write( \"v \" +", "<gh_stars>10-100 import numpy as np npzfile = np.load(\"./data/SdfSamples/dataset/heads/xxxxx_exx.npz\") posSamples = npzfile['pos'] negSamples =", "color = ((points[i,4:7] + 0.5)*255.0).astype('uint8') f.write( \"v \" + str(points[i,0]) + \" \"" ]
[ "%d records to ES\", len(batches)) batches = [] # Clear the batch size", "import namedtuple import itertools import logging import os import time from multiprocessing.dummy import", "= 0 try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout,", "help=\"Be very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The", "while True: chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it) except StopIteration: return", "for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image)", "log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new", "run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to", "index\") with Pool(num_threads) as pool: starts = [i * chunk_size for i in", "with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else: raise", "django.db import connection, transaction import requests from imageledger import models, search console =", "os import time from multiprocessing.dummy import Pool import multiprocessing import uuid from elasticsearch", "import settings from django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction import", "%s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads)", "timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT)", "records to ES\", len(batches)) batches = [] # Clear the batch size else:", "not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and", "parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch process at once\")", "while True: rows = cursor.fetchmany(chunk_size) if not rows: break for row in rows:", "yield obj def grouper_it(n, iterable): it = iter(iterable) while True: chunk_it = itertools.islice(it,", "if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX)", "chunk_size + 1 batches = [] retries = 0 try: es = search.init(timeout=2000)", "= DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable): it = iter(iterable) while", "%d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing", "log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record", "type=int, help=\"The number of records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS,", "for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to", "for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor =", "# Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e:", "[i * chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def", "Index from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import", "+ 1 batches = [] retries = 0 try: es = search.init(timeout=2000) if", "cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model']", "class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\",", "the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries", "database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new", "retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else:", "logging import os import time from multiprocessing.dummy import Pool import multiprocessing import uuid", "from django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction import requests from", "1]) yield obj def grouper_it(n, iterable): it = iter(iterable) while True: chunk_it =", "log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size:", "(requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with", "= 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True", "in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if", "default=False, help=\"Be very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int,", "import logging import os import time from multiprocessing.dummy import Pool import multiprocessing import", "compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False):", "mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as pool: starts = [i *", "server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model =", "new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\")", "= 5 # Number of sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000", "search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT", "search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as pool:", "batches = [] retries = 0 try: es = search.init(timeout=2000) if not settings.DEBUG:", "- retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0,", "from django.db import connection, transaction import requests from imageledger import models, search console", "= itertools.islice(it, n) try: first_el = next(chunk_it) except StopIteration: return yield itertools.chain((first_el,), chunk_it)", "once\") def handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads']", "field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name)", "from %d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in", "%s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not settings.DEBUG:", "itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start + chunk_size + 1 batches", "time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db)", "parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start up at once\")", "MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries +=", "index in range from %d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size]", "import models, search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES =", "request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to ES\", len(batches)) batches =", "not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of", "from multiprocessing.dummy import Pool import multiprocessing import uuid from elasticsearch import helpers import", "1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler =", "= 50 RETRY_WAIT = 5 # Number of sections to wait before retrying", "db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting", "`chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start up", "obj def grouper_it(n, iterable): it = iter(iterable) while True: chunk_it = itertools.islice(it, n)", "+ chunk_size + 1 batches = [] retries = 0 try: es =", "log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1", "in rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj", "def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with a", "if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch", "[] retries = 0 try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000)", "log.debug(\"Starting index in range from %d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False,", "import requests from imageledger import models, search console = logging.StreamHandler() log = logging.getLogger(__name__)", "uuid from elasticsearch import helpers import elasticsearch from elasticsearch_dsl import Index from django.conf", "fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable): it =", "default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start up at once\") def handle(self,", "CommandError from django.db import connection, transaction import requests from imageledger import models, search", "log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number of sections to", "helpers import elasticsearch from elasticsearch_dsl import Index from django.conf import settings from django.core.management.base", "Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if", "not rows: break for row in rows: DBObj = namedtuple('DBObj', fields) obj =", "= [i * chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts))))", "= Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping =", "requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and", "%d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs,", "= search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e)", "elasticsearch_dsl import Index from django.conf import settings from django.core.management.base import BaseCommand, CommandError from", "else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got", "= iter(iterable) while True: chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it) except", "start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database", "retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor()", "handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def", "default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\",", "es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to ES\", len(batches)) batches", "dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\",", "options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS):", "%d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es,", "pool: starts = [i * chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts,", "retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries)", "row in rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield", "log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range", "= [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id", "log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from", "grouper_it(n, iterable): it = iter(iterable) while True: chunk_it = itertools.islice(it, n) try: first_el", "not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done", "index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with", "= queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields", "at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch process", "import helpers import elasticsearch from elasticsearch_dsl import Index from django.conf import settings from", "import elasticsearch from elasticsearch_dsl import Index from django.conf import settings from django.core.management.base import", "mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as pool: starts", "ES\", len(batches)) batches = [] # Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except", "(requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return", "parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\",", ">= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches)", "log.debug(\"Pushed batch of %d records to ES\", len(batches)) batches = [] # Clear", "def handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] )", "logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number of sections", "len(starts)))) def do_index(start, chunk_size): end = start + chunk_size + 1 batches =", "to ES\", len(batches)) batches = [] # Clear the batch size else: batches.append(image.to_dict(include_meta=True))", "if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000)", "elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries", "add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run logging at DEBUG\")", "type=int, help=\"The number of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS,", "True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty", "time from multiprocessing.dummy import Pool import multiprocessing import uuid from elasticsearch import helpers", "retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE):", "def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model", "with Pool(num_threads) as pool: starts = [i * chunk_size for i in range(0,", "= search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green", "MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number of sections to wait before", "chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size):", "as e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index", "console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT =", "= models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier)", "import itertools import logging import os import time from multiprocessing.dummy import Pool import", "models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image", "compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d'", "db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try:", "% cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows =", "obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable): it = iter(iterable)", "return log.debug(\"Starting index in range from %d to %d...\", start, end) qs =", "Pool import multiprocessing import uuid from elasticsearch import helpers import elasticsearch from elasticsearch_dsl", "except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT)", "import uuid from elasticsearch import helpers import elasticsearch from elasticsearch_dsl import Index from", "of threads to start up at once\") def handle(self, *args, **options): if options['verbose']", "num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the", "the database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating", "[] # Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as", "remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def", "settings from django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction import requests", "it = iter(iterable) while True: chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it)", "of sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS", "process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop", "of records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number", "batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql()", "pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start + chunk_size +", "import BaseCommand, CommandError from django.db import connection, transaction import requests from imageledger import", "1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks", "settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying", "batch of %d records to ES\", len(batches)) batches = [] # Clear the", "multiprocessing.dummy import Pool import multiprocessing import uuid from elasticsearch import helpers import elasticsearch", "batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout:", "+ 1]) yield obj def grouper_it(n, iterable): it = iter(iterable) while True: chunk_it", "batches) log.debug(\"Pushed batch of %d records to ES\", len(batches)) batches = [] #", "def grouper_it(n, iterable): it = iter(iterable) while True: chunk_it = itertools.islice(it, n) try:", "to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4", "to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads", "num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with a server-side cursor\"\"\" index =", "log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number", "params = compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for", "\"\"\"Index every record in the database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX)", "chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed", "True: chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it) except StopIteration: return yield", "break for row in rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] +", "cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size)", "rows: break for row in rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1]", "= [] retries = 0 try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green',", "help=\"The number of threads to start up at once\") def handle(self, *args, **options):", "if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS,", "= 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def add_arguments(self, parser):", "= compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] +", "num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start + chunk_size", "to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times", "transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if not rows: break for", "num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database", "= True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run", "len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es,", "helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to ES\", len(batches)) batches = []", ") def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with", "len(batches)) batches = [] # Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout,", "DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable): it = iter(iterable) while True:", "django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction import requests from imageledger", "help=\"The number of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int,", "connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if not rows:", "# Number of sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS =", "batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d", "end = start + chunk_size + 1 batches = [] retries = 0", "help=\"The number of records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int,", "starts = [i * chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size,", "namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable): it", "start up at once\") def handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG)", "1]] cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params)", "from imageledger import models, search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO)", "= logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number of", "itertools import logging import os import time from multiprocessing.dummy import Pool import multiprocessing", "at once\") def handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'],", "elasticsearch import helpers import elasticsearch from elasticsearch_dsl import Index from django.conf import settings", "e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in", "*args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self,", "10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def", "dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch process at once\") parser.add_argument(\"--num-iterations\",", "collections import namedtuple import itertools import logging import os import time from multiprocessing.dummy", "sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname", "settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every", "wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d to %d...\", start, end)", "= True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very", "settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d", "after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d to %d...\", start,", "new index\") with Pool(num_threads) as pool: starts = [i * chunk_size for i", "server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches)", "chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >=", "elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d", "cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init()", "cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while", "sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS =", "type=int, help=\"The number of threads to start up at once\") def handle(self, *args,", "records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of", "with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index", "from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import connection,", "settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as", "e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES", "to start up at once\") def handle(self, *args, **options): if options['verbose'] or settings.DEBUG:", "fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' %", "dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start up at once\") def", "iter(iterable) while True: chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it) except StopIteration:", "= compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field", "DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def add_arguments(self,", "log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records", "and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records", "= [] # Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError)", "num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with a server-side cursor\"\"\" index", "models, search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50", "import Pool import multiprocessing import uuid from elasticsearch import helpers import elasticsearch from", "wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class", "True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run logging", "threads to start up at once\") def handle(self, *args, **options): if options['verbose'] or", "+= 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler", "DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks =", "**options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE,", "* chunk_size for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start,", "cursor.fetchmany(chunk_size) if not rows: break for row in rows: DBObj = namedtuple('DBObj', fields)", "at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop through", "status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to ES\", len(batches))", "50 RETRY_WAIT = 5 # Number of sections to wait before retrying DEFAULT_CHUNK_SIZE", "BaseCommand, CommandError from django.db import connection, transaction import requests from imageledger import models,", "index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating", "raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params", "in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with", "database record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if", "params) while True: rows = cursor.fetchmany(chunk_size) if not rows: break for row in", "def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run logging at", "parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop through `chunk_size` records\")", "django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import connection, transaction", "for row in rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1])", "import os import time from multiprocessing.dummy import Pool import multiprocessing import uuid from", "range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start +", "in the database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists():", "to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size):", "< MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES - retries) retries", "of %d records to ES\", len(batches)) batches = [] # Clear the batch", "0 try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError)", "def do_index(start, chunk_size): end = start + chunk_size + 1 batches = []", "iterable): it = iter(iterable) while True: chunk_it = itertools.islice(it, n) try: first_el =", "number of records to batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The", "= logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5", "1 batches = [] retries = 0 try: es = search.init(timeout=2000) if not", "do_index(start, chunk_size): end = start + chunk_size + 1 batches = [] retries", "number of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The", "if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch", "server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX)", "4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\",", "from collections import namedtuple import itertools import logging import os import time from", "5 # Number of sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS", "from elasticsearch_dsl import Index from django.conf import settings from django.core.management.base import BaseCommand, CommandError", "retries = 0 try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except", "and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d to", "image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for", "end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record", "rows: DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def", "[field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor", "logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch", "record %s\", db_image.identifier) image = search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not", "log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 # Number of sections to wait", "DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of records to batch process at", "batch process at once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to", "elasticsearch from elasticsearch_dsl import Index from django.conf import settings from django.core.management.base import BaseCommand,", "self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in", "chunk_size): end = start + chunk_size + 1 batches = [] retries =", "model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1]", "= compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name =", "select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]] cursor_name", "before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand):", "once\") parser.add_argument(\"--num-iterations\", dest=\"num_iterations\", default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop through `chunk_size`", "batches = [] # Clear the batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError,", "size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES:", "'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows", "retries remaining\", MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches)", "in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start", "zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end = start + chunk_size + 1", "can_import_settings = True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be", "else: raise helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql,", "= start + chunk_size + 1 batches = [] retries = 0 try:", "try: if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\") es.cluster.health(wait_for_status='green',", "logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES = 50 RETRY_WAIT = 5 #", "time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d to %d...\", start, end) qs", "DBObj = namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n,", "search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as pool: starts = [i", "imageledger import models, search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console) log.setLevel(logging.INFO) MAX_CONNECTION_RETRIES", "= 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings = True requires_migrations_checks = True", "up at once\") def handle(self, *args, **options): if options['verbose'] or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'],", "Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping = search.Image._doc_type.mapping", "except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying", "True: rows = cursor.fetchmany(chunk_size) if not rows: break for row in rows: DBObj", "index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with a server-side", "namedtuple import itertools import logging import os import time from multiprocessing.dummy import Pool", "request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\")", "= search.Image._doc_type.mapping mapping.save(settings.ELASTICSEARCH_INDEX) log.info(\"Done creating new index\") with Pool(num_threads) as pool: starts =", "index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\", settings.ELASTICSEARCH_INDEX) search.Image.init() mapping", "MAX_CONNECTION_RETRIES - retries) retries += 1 time.sleep(RETRY_WAIT) else: raise helpers.bulk(es, batches) def server_cursor_query(queryset,", "RETRY_WAIT = 5 # Number of sections to wait before retrying DEFAULT_CHUNK_SIZE =", "loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to", "as e: if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\",", "or settings.DEBUG: log.setLevel(logging.DEBUG) self.index_all_images(chunk_size=options['chunk_size'], num_iterations=options['num_iterations'], num_threads=options['num_threads'] ) def index_all_images(self, chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index", "chunk_it = itertools.islice(it, n) try: first_el = next(chunk_it) except StopIteration: return yield itertools.chain((first_el,),", "DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings =", "es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying after", "parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Be very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\",", "import time from multiprocessing.dummy import Pool import multiprocessing import uuid from elasticsearch import", "connection, transaction import requests from imageledger import models, search console = logging.StreamHandler() log", "elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping batch and retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting", "very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number", "= namedtuple('DBObj', fields) obj = DBObj(*row[select_fields[0]:select_fields[-1] + 1]) yield obj def grouper_it(n, iterable):", "range from %d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image", "import multiprocessing import uuid from elasticsearch import helpers import elasticsearch from elasticsearch_dsl import", "try: es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as", "requests from imageledger import models, search console = logging.StreamHandler() log = logging.getLogger(__name__) log.addHandler(console)", "connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields =", "from elasticsearch import helpers import elasticsearch from elasticsearch_dsl import Index from django.conf import", "in range from %d to %d...\", start, end) qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for", "log.info(\"Done creating new index\") with Pool(num_threads) as pool: starts = [i * chunk_size", "of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number", "rows = cursor.fetchmany(chunk_size) if not rows: break for row in rows: DBObj =", "chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields", "transaction import requests from imageledger import models, search console = logging.StreamHandler() log =", "Command(BaseCommand): can_import_settings = True requires_migrations_checks = True def add_arguments(self, parser): parser.add_argument(\"--verbose\", action=\"store_true\", default=False,", "times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of", "search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e: log.warn(e) log.warn(\"Skipping", "cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if not rows: break for row", "import connection, transaction import requests from imageledger import models, search console = logging.StreamHandler()", "retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000 DEFAULT_NUM_THREADS = 4 class Command(BaseCommand): can_import_settings", "with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if not rows: break", "search.db_image_to_index(db_image) try: if len(batches) >= chunk_size: if not settings.DEBUG: log.debug(\"Waiting for green status...\")", "every record in the database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if", "Number of sections to wait before retrying DEFAULT_CHUNK_SIZE = 1000 DEFAULT_NUM_ITERATIONS = 10000", "action=\"store_true\", default=False, help=\"Be very chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE,", "records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start up at", "if not rows: break for row in rows: DBObj = namedtuple('DBObj', fields) obj", "helpers.bulk(es, batches) def server_cursor_query(queryset, cursor_id=0, chunk_size=DEFAULT_CHUNK_SIZE): connection.cursor() compiler = queryset.query.get_compiler(using=queryset.db) sql, params =", "retrying after wait\") time.sleep(RETRY_WAIT) return log.debug(\"Starting index in range from %d to %d...\",", "chunk_size=DEFAULT_CHUNK_SIZE, num_iterations=DEFAULT_NUM_ITERATIONS, num_threads=DEFAULT_NUM_THREADS): \"\"\"Index every record in the database with a server-side cursor\"\"\"", "= connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if not", "queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields =", "multiprocessing import uuid from elasticsearch import helpers import elasticsearch from elasticsearch_dsl import Index", "as pool: starts = [i * chunk_size for i in range(0, num_iterations)] pool.starmap(do_index,", "if retries < MAX_CONNECTION_RETRIES: log.warn(\"Got timeout: retrying with %d retries remaining\", MAX_CONNECTION_RETRIES -", "batch size else: batches.append(image.to_dict(include_meta=True)) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError, elasticsearch.helpers.BulkIndexError) as e: if retries <", "es = search.init(timeout=2000) if not settings.DEBUG: es.cluster.health(wait_for_status='green', request_timeout=2000) except (requests.exceptions.ReadTimeout, elasticsearch.exceptions.TransportError) as e:", "+ 1]] cursor_name = 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql,", "= 'cursor-large-%d' % cursor_id cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True:", "chatty and run logging at DEBUG\") parser.add_argument(\"--chunk-size\", dest=\"chunk_size\", default=DEFAULT_CHUNK_SIZE, type=int, help=\"The number of", "import Index from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db", "qs = models.Image.objects.filter(removed_from_source=False, id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\",", "= cursor.fetchmany(chunk_size) if not rows: break for row in rows: DBObj = namedtuple('DBObj',", "i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end =", "id__gt=start).order_by('id')[0:chunk_size] for db_image in server_cursor_query(qs, chunk_size=chunk_size): log.debug(\"Indexing database record %s\", db_image.identifier) image =", "record in the database with a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not", "compiler = queryset.query.get_compiler(using=queryset.db) sql, params = compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields']", "compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in compiler.select[select_fields[0]:select_fields[-1] + 1]]", "green status...\") es.cluster.health(wait_for_status='green', request_timeout=2000) helpers.bulk(es, batches) log.debug(\"Pushed batch of %d records to ES\",", "for i in range(0, num_iterations)] pool.starmap(do_index, zip(starts, itertools.repeat(chunk_size, len(starts)))) def do_index(start, chunk_size): end", "start + chunk_size + 1 batches = [] retries = 0 try: es", "through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\", default=DEFAULT_NUM_THREADS, type=int, help=\"The number of threads to start", "default=DEFAULT_NUM_ITERATIONS, type=int, help=\"The number of times to loop through `chunk_size` records\") parser.add_argument(\"--num-threads\", dest=\"num_threads\",", "cursor = connection.connection.cursor(name=cursor_name) with transaction.atomic(savepoint=False): cursor.execute(sql, params) while True: rows = cursor.fetchmany(chunk_size) if", "compiler.as_sql() model = compiler.klass_info['model'] select_fields = compiler.klass_info['select_fields'] fields = [field[0].target.attname for field in", "number of threads to start up at once\") def handle(self, *args, **options): if", "creating new index\") with Pool(num_threads) as pool: starts = [i * chunk_size for", "Pool(num_threads) as pool: starts = [i * chunk_size for i in range(0, num_iterations)]", "a server-side cursor\"\"\" index = Index(settings.ELASTICSEARCH_INDEX) if not index.exists(): log.info(\"Creating new index %s\"," ]
[ "(seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From", "= \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION =", "immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID,", "immutabledict( (coord, f\"Time From Contraction {coord} to Peak (seconds)\") for coord in reversed(COORDS)", "= uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version to", ") ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions", "Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\")", "that this file was migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM", "migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta", "XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID", "type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE =", "lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty", "Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch", "mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just", "AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS", "Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512", "METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME =", "from importlib import metadata except ImportError: # pragma: no cover import importlib_metadata as", "to the SDK (.update is an in-place operation that doesn't return the dictionary,", "reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID", "WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID:", "\"\"\" # 10 seconds at sampling rate of 100Hz BASELINE_MEAN_NUM_DATA_POINTS = 10 *", "XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of", "PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID,", "= 2.5 ADC_GAIN = 2 # Beta 2 Memsic to magnetic field conversion", "2.5 ADC_GAIN = 2 # Beta 2 Memsic to magnetic field conversion factors.", "Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray", "50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\")", "INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs) to default", "\"XEM Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of times", "tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state", "= { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch", "uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\")", "REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column", "\"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID:", "uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\")", "= uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID =", "Magnet Finding \"\"\" # 10 seconds at sampling rate of 100Hz BASELINE_MEAN_NUM_DATA_POINTS =", "Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well", "Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA =", "AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\",", "# Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific", "% width, or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\")", "this file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that", "Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation", "from typing import Dict import uuid from immutabledict import immutabledict from labware_domain_models import", "uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\")", "= uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full relaxation", "= uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID:", "up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray Instrument has been powered", "values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID:", "{ TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches in the data point", "was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file", "# Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23", "REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID:", "uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\")", "stimulation protocol that was running on this well during recording. Empty string if", "in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION =", "ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when recorded, prior to any migrations", "\"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1", "concept of `None` in their metadata, so using this value to denote that", "a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID =", "= uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID,", "the SDK (.update is an in-place operation that doesn't return the dictionary, so", "an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was migrated from\",", "\"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of", "of the file when recorded, prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID:", "= 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET =", "(zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor", "centimilliseconds that has been trimmed off the end of when the original data", "of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity", "1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 **", "PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\":", "PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\"", "= 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME", "\"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total", "[ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID,", "values specific to the SDK (.update is an in-place operation that doesn't return", "the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or", "\"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS =", "\"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't store the concept of `None`", "metadata is not available (i.e. after migrating to a newer file format version)", "the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed off", "instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed off the", "(seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction", "log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate", "Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC", "= immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID:", "their metadata, so using this value to denote that a particular piece of", "General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\",", "pixels between left figure edge and plot area CHART_GAMMA = 150 # for", "11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to magnetic", "CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS", "peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\")", "# for full/snapshots -- num pixels between left figure edge and plot area", "15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS", "MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to magnetic field", "BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID,", "# create a mutable version to add in the new values specific to", "that should be used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND", "\"Is this stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file", "uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\")", "Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS )", "\"Is this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\",", "= immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21):", "uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\")", "Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\",", "as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID =", "BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID", "of `None` in their metadata, so using this value to denote that a", "uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\")", "+ 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS =", "TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID", "AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\",", "MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\",", "\"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\",", "Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue Sensor Data\",", "importlib_metadata as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID", "full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300", "CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START =", "300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START", "(μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width", "uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or", "} ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\",", "\"The stimulation protocol that was running on this well during recording. Empty string", "\"Is this an original file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number", "identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained", "centimilliseconds that has been trimmed off the beginning of when the original data", "TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID", "in-place operation that doesn't return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( {", "Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID:", "Period (µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH", "(Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID:", "when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when", "\"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000", "\"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files", "-*- coding: utf-8 -*- \"\"\"Constants for the Mantarray File Manager.\"\"\" from typing import", "Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\",", "\"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\"", "using this value to denote that a particular piece of metadata is not", "= uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION", "UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID", "between left figure edge and plot area CHART_GAMMA = 150 # for full/snapshots", "ImportError: # pragma: no cover import importlib_metadata as metadata # type: ignore PACKAGE_VERSION", "BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") #", "\"Timestamp when this file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format", "Timestamp of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning", "TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue", "BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for full/snapshots", "internals of the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number", "file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode", "= 60 # for full/snapshots -- num pixels between left figure edge and", "\"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\",", "Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on this well during recording.", "Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak", "name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this", "in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID =", "IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\")", "TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\",", "\"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity", "TAMPER_FLAG_UUID: \"Is it suspected the internals of the Mantarray enclosure have been tampered", "and plot area CHART_GAMMA = 150 # for full/snapshots -- num pixels between", "to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64", "ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main", "immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str]", "FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID", "RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this value from raw hardware data", "uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\")", "= \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME =", "= uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID =", "\"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal", "* CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch", "= uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID =", "Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID:", "Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\",", "IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS", "= 2 ** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA", "conversion factor. Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25", "coding: utf-8 -*- \"\"\"Constants for the Mantarray File Manager.\"\"\" from typing import Dict", "digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the scanner\",", "when recorded, prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this", "\"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\",", "\"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA", "CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\":", "TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed off the beginning of when", "downstream pipelines # simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID", "WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well", "= 35 # for full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH =", "# Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to %", "\"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp", "is pre-computed to make downstream pipelines # simpler. Frequency is reported in Hz", "15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL", "FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID", "immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of", "\"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID,", "Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\",", "figure edge and plot area CHART_GAMMA = 150 # for full/snapshots -- num", "is just the reciprocal of twitch period, but is pre-computed to make downstream", "Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID:", "full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS", "that has been trimmed off the end of when the original data ended\",", "uuid from immutabledict import immutabledict from labware_domain_models import LabwareDefinition try: from importlib import", "= uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID =", "= uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID =", "\"JSON string of the initial magnet finding params that should be used in", "to Relaxation {coord} (seconds)\") for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\":", "HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC", "to a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID", "a mutable version to add in the new values specific to the SDK", "UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was", "TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID,", "uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\")", "= immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID,", "\"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor", ") \"\"\" Magnet Finding \"\"\" # 10 seconds at sampling rate of 100Hz", "relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID,", "= uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID =", "0.000159 # Beta 1 GMR to magnetic field conversion values. Valid as of", "Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well", "= uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID =", "MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES", "= uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID =", "Timestamp of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID:", "MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\"", "10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\"", "from labware_domain_models import LabwareDefinition try: from importlib import metadata except ImportError: # pragma:", "45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\"", "= uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID =", "= uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to % width, or peak to", "earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was migrated from\", #", "particular piece of metadata is not available (i.e. after migrating to a newer", "(coord, f\"Time From Peak to Relaxation {coord} (seconds)\") for coord in COORDS )", "that has been trimmed off the beginning of when the original data started\",", "number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS =", "it suspected the internals of the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID:", "= uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID =", "be used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5)", "was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode", "= 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { #", "for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict(", "second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8", "Tissue Sampling Period (µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID,", "= { # Tissue Sampling Period (µs) to default Pipeline Filter UUID 9600:", "for contraction to % width, or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\")", "<NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta", "# type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE", "factor. Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER", "version of the file when recorded, prior to any migrations to newer versions/formats.\",", "FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch", "AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID", "IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {}", "Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID:", "= 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100", "of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE", "= \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS", "Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\",", "of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on this well during", "64 CHART_ALPHA = 60 # for full/snapshots -- num pixels between left figure", "STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS", "CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID =", "uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\")", "FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ]", "Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy", ") CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Contraction {coord} to Peak", "RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID", "\"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware", "= uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID =", "for full/snapshots -- num pixels between right figure edge and plot area CHART_PIXELS_PER_SECOND", "per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS =", "Peak to Relaxation {coord} (seconds)\") for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\":", "= dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version to add in the", "General mangetic field to force conversion factor. Obtained 03/09/2021 by <NAME>, Valid as", "Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer", "Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict(", "= immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES:", "TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID", "uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to % width, or peak to %", "trimmed off the end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original", "Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC", "left figure edge and plot area CHART_GAMMA = 150 # for full/snapshots --", "{coord} to Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] =", "edge and plot area CHART_GAMMA = 150 # for full/snapshots -- num pixels", "from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed", "Beta 2 Memsic to magnetic field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET", "uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion factor. Obtained 03/09/2021 by <NAME>,", "= uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to", "INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\" # 10 seconds at sampling", "25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord}", "CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS:", "off the beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds", "= uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID =", "enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\",", "From Peak to Relaxation {coord} (seconds)\") for coord in COORDS ) ALL_FORMATS =", "and plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number of pixels", "{ TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force", "\"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software", "the internals of the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial", "uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\")", "} DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for full/snapshots -- num pixels", "uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21", "Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference Sensor", "Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID:", "\"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the", "of times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of", "uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\")", "number of hours this Mantarray Instrument has been powered on and running\", TAMPER_FLAG_UUID:", "SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency", "uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\")", "= uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID =", "EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID:", "TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches in the data point up", "{ # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning", "= \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID(", "Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file", "(seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( {", "(coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] =", "data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\",", "AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID =", "str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS) )", "= \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID", "pipelines # simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID =", "{coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord,", "uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic", "coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Peak", "CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval", "(seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID,", "\"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID:", "Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning", "to force conversion factor. Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA", "2 Memsic to magnetic field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET =", "\"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS", "INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = {", "2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS", "UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File", "STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from the", "INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version", "uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\")", "START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID", "8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES", "by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this", "\"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\"", "# subtract this value from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN =", "PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer", "of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15", "BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for full/snapshots -- num", "23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to magnetic field conversion values.", "= 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH =", "cover import importlib_metadata as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID =", "protocol that was running on this well during recording. Empty string if stimulation", "= uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID =", "to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\":", "factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2", "TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue", "Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string", "\"UTC Timestamp of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\",", "UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID", "uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict(", "uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID,", "relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\")", "uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\")", "plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight", "raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta 2 Memsic", "of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file", "1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID:", "twitch period, but is pre-computed to make downstream pipelines # simpler. Frequency is", "GMR to magnetic field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6", "ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID", "= uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID =", "period, but is pre-computed to make downstream pipelines # simpler. Frequency is reported", "WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID:", "{ # Tissue Sampling Period (µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID,", "= immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int,", "uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\")", "num pixels between left figure edge and plot area CHART_GAMMA = 150 #", "{coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation", "WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\",", "uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\",", "file when recorded, prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when", "\"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID =", "to magnetic field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 **", "= uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID =", "\"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\"", "MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\",", "AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID", "Relaxation {coord} (seconds)\") for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}})", "full/snapshots -- num pixels between right figure edge and plot area CHART_PIXELS_PER_SECOND =", "was running on this well during recording. Empty string if stimulation was not", "to Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict(", "Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of times this", "Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS", "ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID", "Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID),", "= uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID =", "Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC", "mangetic field to force conversion factor. Obtained 03/09/2021 by <NAME>, Valid as of", "\"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from", "\"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active", "\"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\",", "recorded, prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file", "CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID", "23 # subtract this value from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN", "NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't store the", "the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC", "Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue", "initial magnet finding params that should be used in Pulse3D\", } ) DATETIME_STR_FORMAT", "PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID", "4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME", "Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\",", "value for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS =", "a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags", "INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding params that should be used", "\"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID:", "constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This", "Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER =", "= uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID =", "\"Is this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original", "this value to denote that a particular piece of metadata is not available", "CHART_ALPHA = 60 # for full/snapshots -- num pixels between left figure edge", "-- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS", "import immutabledict from labware_domain_models import LabwareDefinition try: from importlib import metadata except ImportError:", "= 2 ** 23 # subtract this value from raw hardware data REFERENCE_VOLTAGE", "Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID:", "should be used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND =", "(seconds)\") for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID =", "this an original file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of", "{coord} (seconds)\") for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID", "of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp", "\"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\"", "int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\"", "to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From", "MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\"", "uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\")", "been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The", "Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on this well", "Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the", "MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0", ") COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict(", "TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs) to default Pipeline Filter UUID", "CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH *", "(.update is an in-place operation that doesn't return the dictionary, so chaining is", "\"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\",", "= uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID =", "= uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID =", "plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number of pixels per", "Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray", "\"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS *", "\"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this", "# Kristian 10/29/21: for contraction to % width, or peak to % relaxation", "an original file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds", "FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 /", "CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL =", "of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue Sensor", "this well during recording. Empty string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim", "INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs)", "= \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\":", "# Kristian 11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID", "WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID", "uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\")", "hours this Mantarray Instrument has been powered on and running\", TAMPER_FLAG_UUID: \"Is it", "= uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID =", "WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\",", "uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID,", "= uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian", "`None` in their metadata, so using this value to denote that a particular", "= 64 CHART_ALPHA = 60 # for full/snapshots -- num pixels between left", "of centimilliseconds that has been trimmed off the end of when the original", "immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID:", "Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\",", "), } ) COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str]", "= uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General", "uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\")", "MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS =", "TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID", "\"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID:", "well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID:", "TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\"", "DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for full/snapshots -- num pixels between", "\"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON", "Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\",", "active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from", "uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\")", "ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID", "= uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID =", "conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB =", "TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray Instrument has been powered on", "STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID", "straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been", "60 # for full/snapshots -- num pixels between left figure edge and plot", "MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS", "= METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME", "params that should be used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\"", "UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning", "present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding params", "contraction to % width, or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID", "uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\")", "= \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS", "Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time", "Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded", "scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from the instrument and untrimmed\",", "(μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch", "uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\")", "(empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on", "Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build", "} ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND", "for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From", "Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time", "IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID", "that doesn't return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag", "= 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3", "migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was", "from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from the instrument", "to denote that a particular piece of metadata is not available (i.e. after", "Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version", "= uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction", "<NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this value", "METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\"", "10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME =", "= uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a", "UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID", "\"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet", "values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID:", "denote that a particular piece of metadata is not available (i.e. after migrating", "= uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of twitch period, but is", "= INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs) to", "when this file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version", "CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") #", "Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version", "optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( {", "specific to the SDK (.update is an in-place operation that doesn't return the", "= \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS =", "TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak", "Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific values", "magnetic field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15", "ADC_GAIN = 2 # Beta 2 Memsic to magnetic field conversion factors. Valid", "\"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor", "Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC", "Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is", "{ \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID,", "of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID:", "(seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to", "= uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID =", "RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID =", "uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\")", "CHART_GAMMA = 150 # for full/snapshots -- num pixels between right figure edge", "Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of", "number of times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number", "2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID:", "uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\")", "REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\"", "Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\",", "SDK (.update is an in-place operation that doesn't return the dictionary, so chaining", "\"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") #", "0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME =", "TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\")", "= 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of twitch", "newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\")", "during recording. Empty string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\",", "Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE", "11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\")", "= DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = {", "IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel", "BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial", "Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of", "TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS", "\"File format version that this file was migrated from\", # Beta 1 specific", "import Dict import uuid from immutabledict import immutabledict from labware_domain_models import LabwareDefinition try:", "= uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID =", "= immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict(", "= uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't store the concept", "field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB", "Contraction {coord} to Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str]", "# Tissue Sampling Period (µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600:", "= uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID =", "PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID", "(seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline", "uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\")", "mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version to add in", "uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version to add", "library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the", "= 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START", "uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\")", "= uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID =", "has been powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of", "BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values", "= uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { #", "WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID", "ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when recorded, prior to any", "\"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction", "UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account", "has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray Instrument has", "str] = immutabledict( (coord, f\"Time From Contraction {coord} to Peak (seconds)\") for coord", "been trimmed off the beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number", "original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when recorded, prior", "Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) )", "} ) \"\"\" Magnet Finding \"\"\" # 10 seconds at sampling rate of", "ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\",", "uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\")", "stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration", "H5 files can't store the concept of `None` in their metadata, so using", "version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was migrated from\", # Beta", "in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID =", "uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\")", "WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling", "values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME>", "uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\")", "simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID", "= uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID =", "immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\",", "-*- \"\"\"Constants for the Mantarray File Manager.\"\"\" from typing import Dict import uuid", "the beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that", "chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches", "full/snapshots -- num pixels between left figure edge and plot area CHART_GAMMA =", "REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID", "STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on this well during recording. Empty", "/ 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling", "+ 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\"", "can't store the concept of `None` in their metadata, so using this value", "\"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } )", "as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE =", "uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21:", "Sampling Period (µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, }", "IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID:", "METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID:", "= uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID =", "pre-computed to make downstream pipelines # simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID", "AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME", "\"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak", "str] = immutabledict( (coord, f\"Time From Peak to Relaxation {coord} (seconds)\") for coord", "difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches in the", "= immutabledict( (coord, f\"Time From Contraction {coord} to Peak (seconds)\") for coord in", "uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to", "(zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in", "# pragma: no cover import importlib_metadata as metadata # type: ignore PACKAGE_VERSION =", "force conversion factor. Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA =", "immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str]", "COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID", "Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6)", "HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID", "twitches in the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical", "FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION", "NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET", "not available (i.e. after migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID =", "labware_domain_models import LabwareDefinition try: from importlib import metadata except ImportError: # pragma: no", "uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\")", "was migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", #", "CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID", "to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated", "= uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID =", "From Peak to Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID,", "From Contraction {coord} to Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int,", "uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\")", "NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to magnetic field conversion values. Valid", "= uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID =", "= \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100", "MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row", "version that this file was migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID:", "(on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID:", "= 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to magnetic field conversion", "uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\")", "uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\")", "mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches in the data", "state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\",", "from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is", "so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the", "\"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded", "uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\")", "uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\")", "\"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\",", "Baseline (seconds)\", } CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": (", "(coord, f\"Time From Contraction {coord} to Peak (seconds)\") for coord in reversed(COORDS) )", "\"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running", "Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation", "Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of", "AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID", "no cover import importlib_metadata as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID", "File Manager.\"\"\" from typing import Dict import uuid from immutabledict import immutabledict from", "= uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian", "coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\")", "RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS", "= uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID =", "This is just the reciprocal of twitch period, but is pre-computed to make", "Width {coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict(", "= uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID =", "\"Is it suspected the internals of the Mantarray enclosure have been tampered with\",", "IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25, 50,", "RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID", "Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time", "reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord", "Dict[int, str] = immutabledict( (coord, f\"Time From Peak to Relaxation {coord} (seconds)\") for", "recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\",", "= uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID =", "\"\"\"Constants for the Mantarray File Manager.\"\"\" from typing import Dict import uuid from", "RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {}", "for coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\")", "data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta 2 Memsic to magnetic", "but is pre-computed to make downstream pipelines # simpler. Frequency is reported in", "} ) COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] =", "2 # Beta 2 Memsic to magnetic field conversion factors. Valid as of", "of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp", "the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data", "= uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID =", "immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5", "uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't store the concept of", "Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID =", "= uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID =", "# Beta 1 GMR to magnetic field conversion values. Valid as of 11/19/21", "area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number of pixels per second", "CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID", "** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS =", "Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1", "edge and plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number of", "Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 #", "uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\")", "= uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID =", "uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\")", "STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID", "Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well", "METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START =", "Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction", "of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of", "PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID =", "IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for", "\"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference", "# Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument", ") CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in", "area CHART_GAMMA = 150 # for full/snapshots -- num pixels between right figure", "= 0.000159 # Beta 1 GMR to magnetic field conversion values. Valid as", "MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format", "\"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to", "and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of the Mantarray enclosure have", "= uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID =", "Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning", "in the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well", "TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US =", "create a mutable version to add in the new values specific to the", "has been trimmed off the beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID:", "TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID", "(microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference", "TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of twitch period, but", "( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), }", "an in-place operation that doesn't return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update(", "Dict import uuid from immutabledict import immutabledict from labware_domain_models import LabwareDefinition try: from", "1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for full/snapshots --", "import uuid from immutabledict import immutabledict from labware_domain_models import LabwareDefinition try: from importlib", "150 # for full/snapshots -- num pixels between right figure edge and plot", "mutable version to add in the new values specific to the SDK (.update", "(coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] =", "TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION", "recording. Empty string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID:", "CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\"", "to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", } CALCULATED_METRICS =", "this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID:", "Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) #", "bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding params that should be", "1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of twitch period,", "file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware", "import LabwareDefinition try: from importlib import metadata except ImportError: # pragma: no cover", "COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Contraction {coord} to", "TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID", "immutabledict from labware_domain_models import LabwareDefinition try: from importlib import metadata except ImportError: #", "is not available (i.e. after migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID", "From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\",", "prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was", "of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on this", "string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this", "= uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID =", "Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference Sensor Data\",", "of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Reference", "newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from an earlier version.\",", "immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int,", "Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID:", "f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict(", "or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID =", "of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000", "uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\")", "MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID", "= uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS =", "metadata, so using this value to denote that a particular piece of metadata", "ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions =", "so using this value to denote that a particular piece of metadata is", "\"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID:", "ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4,", "subtract this value from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2", "= uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion factor. Obtained 03/09/2021 by", "= uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID =", "# General mangetic field to force conversion factor. Obtained 03/09/2021 by <NAME>, Valid", "point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\", }", "obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate) recording\",", "the initial magnet finding params that should be used in Pulse3D\", } )", "= uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian", "f\"Time From Contraction {coord} to Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES:", "{} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time", "untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed off the beginning of", "migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\")", "in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period", "\"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\" # 10", "total number of hours this Mantarray Instrument has been powered on and running\",", "column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File", "to make downstream pipelines # simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID =", "INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions)", "Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2 **", "pragma: no cover import importlib_metadata as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\")", "Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID:", "= uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction", "LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY =", "6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45", "uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\")", "board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol", "3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START =", "\"The total number of hours this Mantarray Instrument has been powered on and", "Manager.\"\"\" from typing import Dict import uuid from immutabledict import immutabledict from labware_domain_models", "SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep", "uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\")", ") DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND =", "UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", }", "TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID", "USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID:", "Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log", "powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of the Mantarray", "BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID", "-- num pixels between left figure edge and plot area CHART_GAMMA = 150", "CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS)", "in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Peak to", "= \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\"", "{\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS )", "interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID:", "= METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\"", "90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord", "\"Flag indicating whether or not the twitches in the data point up or", "reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord", "\"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the", "PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25, 50, 75,", "] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\")", "Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of", "barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from", "METADATA_UUID_DESCRIPTIONS ) # create a mutable version to add in the new values", "* MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs) to default Pipeline", "BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion factor. Obtained 03/09/2021", "SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID", "new values specific to the SDK (.update is an in-place operation that doesn't", "\"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\" # 10 seconds at", "MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this value from", "METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS", "= metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION", "number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\",", "= uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID =", "file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has", "barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate)", "= [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID,", "coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\")", "in their metadata, so using this value to denote that a particular piece", "metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION =", "BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is", "(μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID:", "the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware", "uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\")", "COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord,", "= uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS =", "BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field", "# -*- coding: utf-8 -*- \"\"\"Constants for the Mantarray File Manager.\"\"\" from typing", "uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\")", "uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21:", "Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\",", "uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\")", "= 150 # for full/snapshots -- num pixels between right figure edge and", "(1/19/21): H5 files can't store the concept of `None` in their metadata, so", "Mantarray File Manager.\"\"\" from typing import Dict import uuid from immutabledict import immutabledict", "# for full/snapshots -- num pixels between right figure edge and plot area", "(microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC", "reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Peak to Relaxation", "% relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID =", "a particular piece of metadata is not available (i.e. after migrating to a", "just the reciprocal of twitch period, but is pre-computed to make downstream pipelines", "FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25,", "SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID", "= 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this value from raw", "Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch", "in the new values specific to the SDK (.update is an in-place operation", "} CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID,", "UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 #", "10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH", "16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3", "\"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\",", "uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion factor. Obtained", "store the concept of `None` in their metadata, so using this value to", "(10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width", "CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH", "Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release", "uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\")", "CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From Baseline to", "uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\")", "ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\",", "= \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants", "as of 11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2 ** 16", "immutabledict( (coord, f\"Time From Peak to Relaxation {coord} (seconds)\") for coord in COORDS", "= \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME =", "int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\"", "booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray Instrument has been", ") RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Peak to Relaxation {coord}", "uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\")", "METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME =", "UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID", "TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding", "{ WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\",", "Kristian 10/29/21: for contraction to % width, or peak to % relaxation TIME_VALUE_UUID", "str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES:", "MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID", "not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS =", "right figure edge and plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots --", "TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") #", "UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp", "= uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID =", "WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID", "uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is", "specific values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument has booted up\",", "= \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME =", "uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\")", "Active Twitch Force (μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID:", "started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed off the end of", "uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable", "PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6)", "= uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID =", "trimmed off the beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of", "\"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of", "\"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START +", "= uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID =", "the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the", "CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES =", "= uuid.UUID(\"7d026e86-da70-4464-9181-dc0ce2d47bd1\") STIM_BARCODE_IS_FROM_SCANNER_UUID = uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID =", "Kristian 9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to % width,", "\"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\",", "RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID,", "TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full", "of Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User", "Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray", "# simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\")", "(i.e. after migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID", "obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from the", "FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli", "of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR to", "\"The original version of the file when recorded, prior to any migrations to", "for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates", "= uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID =", "the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed off", "after migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID =", "Finding \"\"\" # 10 seconds at sampling rate of 100Hz BASELINE_MEAN_NUM_DATA_POINTS = 10", "RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID", "\"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't store", "to magnetic field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 #", "16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants", "PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of", "if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim", "75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for", "(Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial", "{} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID: \"Time From", "= immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\", TISSUE_SAMPLING_PERIOD_UUID: \"E5\", TWITCHES_POINT_UP_UUID: \"E6\",", "PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\",", "CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID", "to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from an earlier", "CONTINUOUS_WAVEFORM_SHEET_NAME = \"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME", "uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\")", "of the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of", "the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation", "BASELINE_TO_PEAK_UUID: \"Time From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline", "to % width, or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID =", "# General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of", "WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID", "is an in-place operation that doesn't return the dictionary, so chaining is difficult)", "SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID", "= int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS =", "Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software", "for full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT =", "-- num pixels between right figure edge and plot area CHART_PIXELS_PER_SECOND = 35", "ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID", "whether or not the twitches in the data point up or not\", INTERPOLATION_VALUE_UUID:", "to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\", BASELINE_TO_PEAK_UUID:", "Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray", "uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\")", "TWITCHES_POINT_UP_UUID: \"E6\", MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\" #", "device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding params that should", "= uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID = uuid.UUID(\"68d0147f-9a84-4423-9c50-228da16ba895\") PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID =", "value from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta", "this stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a", ") RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in", "immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS", "TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int,", "MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE =", "= uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID =", "pixels between right figure edge and plot area CHART_PIXELS_PER_SECOND = 35 # for", "= 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID:", "been trimmed off the end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The", "METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6", "100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch", "** 23 # subtract this value from raw hardware data REFERENCE_VOLTAGE = 2.5", "Mantarray Instrument has been powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected the", "f\"Time From Peak to Relaxation {coord} (seconds)\") for coord in COORDS ) ALL_FORMATS", "as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 # Beta 1 GMR", "= 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2", "0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract this value from raw hardware", "Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware", "computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is", "finding params that should be used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d", "(µs) to default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH =", "for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From", "SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID", "\"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\")", "= int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS =", "\"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) #", "on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding params that", "from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta 2", "\"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" ) # Eli (1/19/21): H5 files can't", "MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16", "coord in COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID", "been powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of the", "Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest", "uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\")", "TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord in", "magnetic field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained", "PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID", "data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when recorded, prior to", "uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\")", "and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that has been trimmed off the beginning", "stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid", "or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS", "values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number", "reciprocal of twitch period, but is pre-computed to make downstream pipelines # simpler.", "CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10,", "= \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"})", "up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for optical well data interpolation\", } )", "calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present", "2 specific values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument has booted", "uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID = uuid.UUID(\"dc10066c-abf2-42b6-9b94-5e52d1ea9bfc\") PLATE_BARCODE_UUID = uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\")", "uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\")", "well during recording. Empty string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid", "= uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID =", "of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been", "FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to % width, or peak", "= uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test", "plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version (Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device", "PCB_SERIAL_NUMBER_UUID = uuid.UUID(\"5103f995-19d2-4880-8a2e-2ce9080cd2f5\") MAGNETOMETER_CONFIGURATION_UUID = uuid.UUID(\"921121e9-4191-4536-bedd-03186fa1e117\") UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID", "CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID:", "= \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library", "= immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int,", "= 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\",", "03/09/2021 by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159", "\"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS = 1 / 100 INTERPOLATED_DATA_PERIOD_US", "= \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START", "\"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START", "uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\")", "uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\")", "versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID:", "Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that was running on", "conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by", "= uuid.UUID(\"6e5a4b3e-f766-4638-80f7-d95c417c0fc2\") IS_FILE_ORIGINAL_UNTRIMMED_UUID = uuid.UUID(\"52231a24-97a3-497a-917c-86c780d9993f\") TRIMMED_TIME_FROM_ORIGINAL_START_UUID = uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID =", "Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID:", "= uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION", "data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\",", "MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID = uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of", "indicating whether or not the twitches in the data point up or not\",", "this file was migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial", "WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\")", "WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID", "Eli (1/19/21): H5 files can't store the concept of `None` in their metadata,", "metadata except ImportError: # pragma: no cover import importlib_metadata as metadata # type:", "STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this", "DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10", "3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START =", "width, or peak to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID", "From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak", "= uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID =", "constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4", "from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was migrated", "times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours", "contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS =", "Beta 2 specific values BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument has", "import metadata except ImportError: # pragma: no cover import importlib_metadata as metadata #", "except ImportError: # pragma: no cover import importlib_metadata as metadata # type: ignore", "of metadata is not available (i.e. after migrating to a newer file format", "this value from raw hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 #", "used in Pulse3D\", } ) DATETIME_STR_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION", "the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the file when recorded,", "format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID =", "START_RECORDING_TIME_INDEX_UUID: \"Timepoint of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data", "COMPUTER_NAME_HASH_UUID: \"SHA512 digest of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from", "on and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of the Mantarray enclosure", "this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this", "= uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID =", "1 GMR to magnetic field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA =", "string of the initial magnet finding params that should be used in Pulse3D\",", "Instrument has been powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected the internals", "= uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID = uuid.UUID(\"41069860-159f-49f2-a59d-401783c1ecb4\") ADC_REF_OFFSET_UUID =", "dict( METADATA_UUID_DESCRIPTIONS ) # create a mutable version to add in the new", "available (i.e. after migrating to a newer file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\")", "AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } )", "\"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID:", "MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID", "= LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY", "in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction Coordinates {coord}\") for", "Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA = uuid.UUID( \"59d92e00-99d5-4460-9a28-5a1a0fe9aecf\" )", "WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") #", "(WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID,", "Peak (seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord,", "= 3 \"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START", "\"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from the scanner\",", "hardware data REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta 2 Memsic to", "Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord,", "when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed", "\"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet", "BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion", "\"Number of centimilliseconds that has been trimmed off the beginning of when the", "{} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From", "\"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID:", "of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID:", "Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells", "utf-8 -*- \"\"\"Constants for the Mantarray File Manager.\"\"\" from typing import Dict import", "uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID = uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\")", "(seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to Relaxation {}", "original version of the file when recorded, prior to any migrations to newer", "value to denote that a particular piece of metadata is not available (i.e.", "100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period", "\"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID: \"Time From Peak to", "str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES:", "in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Contraction {coord}", "SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray Nickname\", MANTARRAY_SERIAL_NUMBER_UUID: \"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID:", "PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME", "= immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware Test Recording\", START_RECORDING_TIME_INDEX_UUID: \"Timepoint", "on this well during recording. Empty string if stimulation was not active\", STIM_BARCODE_UUID:", "for the Mantarray File Manager.\"\"\" from typing import Dict import uuid from immutabledict", "import importlib_metadata as metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\")", "any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from", "= uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID =", "(μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time", "Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\", SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\",", "\"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\", WELL_INDEX_UUID: \"Well Index", "Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend", "migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp when this file was migrated from an", "\"\"\" Magnet Finding \"\"\" # 10 seconds at sampling rate of 100Hz BASELINE_MEAN_NUM_DATA_POINTS", "for full/snapshots -- num pixels between left figure edge and plot area CHART_GAMMA", "RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25, 50, 75, 90)", "UTC_BEGINNING_RECORDING_UUID: \"UTC Timestamp of Beginning of Recording\", UTC_FIRST_TISSUE_DATA_POINT_UUID: \"UTC Timestamp of Beginning of", "from the scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID:", "add in the new values specific to the SDK (.update is an in-place", "= uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID =", "uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\")", "is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not the twitches in", "specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2 specific values BOOTUP_COUNTER_UUID: \"The", "MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning", "Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID: \"SHA512 digest of", "Kristian 11/9/21: full contraction or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID =", "in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates {coord}\") for", "end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of the", "CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active", "return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether", "METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID: \"E4\",", "TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed off the end of when", "= uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID,", "Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate", "file was migrated from an earlier version.\", FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this", "USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID", "ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID, AUC_UUID, TWITCH_FREQUENCY_UUID, CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID,", "format version that this file was migrated from\", # Beta 1 specific values", "\"Desired value for optical well data interpolation\", } ) METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS", "TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum", "Peak to Relaxation {} (seconds)\", CONTRACTION_TIME_UUID: \"Time From Contraction {} to Peak (seconds)\",", "the Mantarray File Manager.\"\"\" from typing import Dict import uuid from immutabledict import", "10/29/21: for contraction to % width, or peak to % relaxation TIME_VALUE_UUID =", "running\", TAMPER_FLAG_UUID: \"Is it suspected the internals of the Mantarray enclosure have been", "of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID:", "Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain", "Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained from the scanner\", IS_CALIBRATION_FILE_UUID:", "uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\")", "serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's", "\"UTC Timestamp of Beginning of Recorded Tissue Sensor Data\", UTC_FIRST_REF_DATA_POINT_UUID: \"UTC Timestamp of", "importlib import metadata except ImportError: # pragma: no cover import importlib_metadata as metadata", "Dict[int, str] = immutabledict( (coord, f\"Time From Contraction {coord} to Peak (seconds)\") for", "03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE = 2 ** 23 # subtract", "field to force conversion factor. Obtained 03/09/2021 by <NAME>, Valid as of 11/19/21", "# 10 seconds at sampling rate of 100Hz BASELINE_MEAN_NUM_DATA_POINTS = 10 * 100", "\"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\"", "\"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID:", "Column (zero-based)\", WELL_INDEX_UUID: \"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference", "CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Contraction {coord} to Peak (seconds)\")", "Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp", "uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\")", "WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID", "WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\") TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID", "MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID", ") # create a mutable version to add in the new values specific", "= uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\") CONTRACTION_VELOCITY_UUID = uuid.UUID(\"73961e7c-17ec-42b0-b503-a23195ec249c\") IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") # Kristian 9/15/21 FRACTION_MAX_UUID =", "Beginning of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account", "running on this well during recording. Empty string if stimulation was not active\",", "that a particular piece of metadata is not available (i.e. after migrating to", "the new values specific to the SDK (.update is an in-place operation that", "(Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch Force", "metadata # type: ignore PACKAGE_VERSION = metadata.version(\"pulse3D\") CURI_BIO_ACCOUNT_UUID = uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\")", "= uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\") UTC_FIRST_REF_DATA_POINT_UUID = uuid.UUID(\"7cc07b2b-4146-4374-b8f3-1c4d40ff0cf7\") CUSTOMER_ACCOUNT_ID_UUID =", "= uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID =", "the twitches in the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value for", "MANTARRAY_SERIAL_NUMBER_UUID: \"E7\", INTERPOLATION_VALUE_UUID: \"E8\", } ) \"\"\" Magnet Finding \"\"\" # 10 seconds", "uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\")", "TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\") mutable_metadata_uuid_descriptions = dict( METADATA_UUID_DESCRIPTIONS ) # create", "has been trimmed off the end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID:", "RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Peak to Relaxation {coord} (seconds)\")", "have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID:", "of twitch period, but is pre-computed to make downstream pipelines # simpler. Frequency", "SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS", "make downstream pipelines # simpler. Frequency is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\")", "FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS = immutabledict({\"0.3.1\": \"0.4.1\", \"0.4.1\": \"0.4.2\"}) NOT_APPLICABLE_H5_METADATA =", "Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total number of hours this Mantarray Instrument", "DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID:", "BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS =", "(Channel Controller)\", BOOT_FLAGS_UUID: \"Hardware/firmware flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of", "uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID = uuid.UUID(\"cd89f639-1e36-4a13-a5ed-7fec6205f779\")", "of computer name\", PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID:", "9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60 # for", "Memsic to magnetic field conversion factors. Valid as of 11/19/21 MEMSIC_CENTER_OFFSET = 2", "# Beta 2 Memsic to magnetic field conversion factors. Valid as of 11/19/21", "\"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID,", "BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID", "off the end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version", "immutabledict import immutabledict from labware_domain_models import LabwareDefinition try: from importlib import metadata except", "Dict[int, str] = immutabledict( (coord, f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS)", "from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\", # Beta 2", "num pixels between right figure edge and plot area CHART_PIXELS_PER_SECOND = 35 #", "# This is just the reciprocal of twitch period, but is pre-computed to", "= 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\" REFERENCE_SENSOR_READINGS = \"reference_sensor_readings\" STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES =", "= (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Twitch", "uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\") UTC_FIRST_TISSUE_DATA_POINT_UUID = uuid.UUID(\"b32fb8cb-ebf8-4378-a2c0-f53a27bc77cc\")", "is reported in Hz TWITCH_FREQUENCY_UUID = uuid.UUID(\"472d0707-ff87-4198-9374-c28900bb216c\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\")", "# Eli (1/19/21): H5 files can't store the concept of `None` in their", "PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off) of", "of Recorded Reference Sensor Data\", CUSTOMER_ACCOUNT_ID_UUID: \"Customer Account ID\", USER_ACCOUNT_ID_UUID: \"User Account ID\",", "Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID: \"Mantarray", "original file straight from the instrument and untrimmed\", TRIMMED_TIME_FROM_ORIGINAL_START_UUID: \"Number of centimilliseconds that", "plot area CHART_GAMMA = 150 # for full/snapshots -- num pixels between right", "INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General values HARDWARE_TEST_RECORDING_UUID: \"Is Hardware", "uuid.UUID(\"73f52be0-368c-42d8-a1fd-660d49ba5604\") CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION =", "uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID = uuid.UUID(\"0fcc0dc3-f9aa-4f1b-91b3-e5b5924279a9\")", "uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\")", "TOTAL_WELL_COUNT_UUID = uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID", "WIDTH_UUID = uuid.UUID(\"c4c60d55-017a-4783-9600-f19606de26f3\") WIDTH_VALUE_UUID = uuid.UUID(\"05041f4e-c77d-42d9-a2ae-8902f912e9ac\") WIDTH_RISING_COORDS_UUID = uuid.UUID(\"2a16acb6-4df7-4064-9d47-5d27ea7a98ad\") WIDTH_FALLING_COORDS_UUID = uuid.UUID(\"26e5637d-42c9-4060-aa5d-52209b349c84\") RELAXATION_VELOCITY_UUID", "doesn't return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating", "IRREGULARITY_INTERVAL_UUID = uuid.UUID(\"61046076-66b9-4b8b-bfec-1e00603743c0\") FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") TIME_DIFFERENCE_UUID = uuid.UUID(\"1363817a-b1fb-468e-9f1c-ec54fce72dfe\") TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID", "UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID = uuid.UUID(\"11b4945b-3cf3-4f67-8bee-7abc3c449756\") BOOTUP_COUNTER_UUID = uuid.UUID(\"b9ccc724-a39d-429a-be6d-3fd29be5037d\") TOTAL_WORKING_HOURS_UUID = uuid.UUID(\"f8108718-2fa0-40ce-a51a-8478e5edd4b8\") TAMPER_FLAG_UUID", "\"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ),", "ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor", "uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID = uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force", "try: from importlib import metadata except ImportError: # pragma: no cover import importlib_metadata", "files can't store the concept of `None` in their metadata, so using this", "version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID = uuid.UUID(\"d2449271-0e84-4b45-a28b-8deab390b7c2\")", "the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file straight from the instrument and", "\"Number of centimilliseconds that has been trimmed off the end of when the", "REFERENCE_VOLTAGE = 2.5 ADC_GAIN = 2 # Beta 2 Memsic to magnetic field", "(coord, f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str]", "\"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\"", "pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START +", "LabwareDefinition try: from importlib import metadata except ImportError: # pragma: no cover import", "full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID,", "= \"continuous-waveform-snapshots\" FULL_CHART_SHEET_NAME = \"full-continuous-waveform-plots\" TWITCH_FREQUENCIES_CHART_SHEET_NAME = \"twitch-frequencies-plots\" FORCE_FREQUENCY_RELATIONSHIP_SHEET = \"force-frequency-relationship\" INTERPOLATED_DATA_PERIOD_SECONDS =", "\"Twitch Period (seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID:", "11/19/21 MEMSIC_CENTER_OFFSET = 2 ** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE =", "Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA = 60", "2 ** 23 # subtract this value from raw hardware data REFERENCE_VOLTAGE =", ") METADATA_UUID_DESCRIPTIONS = immutabledict(mutable_metadata_uuid_descriptions) EXCEL_OPTICAL_METADATA_CELLS = immutabledict( { WELL_NAME_UUID: \"E2\", UTC_BEGINNING_RECORDING_UUID: \"E3\", PLATE_BARCODE_UUID:", "9/15/21 FRACTION_MAX_UUID = uuid.UUID(\"8fe142e2-2504-4c9e-b3dc-817b24c7447e\") # Kristian 10/29/21: for contraction to % width, or", "TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID", "CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID, CONTRACTION_VELOCITY_UUID, FRACTION_MAX_UUID, IRREGULARITY_INTERVAL_UUID, PEAK_TO_BASELINE_UUID, RELAXATION_VELOCITY_UUID, TWITCH_FREQUENCY_UUID,", "= uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID =", "CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION = \"1.0.0\" FILE_FORMAT_VERSION_METADATA_KEY = \"File Format Version\" FILE_MIGRATION_PATHS =", "the reciprocal of twitch period, but is pre-computed to make downstream pipelines #", "RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full", "pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT = 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS", "file was migrated from\", # Beta 1 specific values XEM_SERIAL_NUMBER_UUID: \"XEM Serial Number\",", "default Pipeline Filter UUID 9600: BESSEL_LOWPASS_10_UUID, 1600: BUTTERWORTH_LOWPASS_30_UUID, } DEFAULT_CELL_WIDTH = 64 CHART_ALPHA", "or full relaxation metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [", "(μN)\", AUC_UUID: \"Energy (μJ)\", CONTRACTION_VELOCITY_UUID: \"Twitch Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity", "\"Mantarray Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\",", "\"continuous-waveforms\" AGGREGATE_METRICS_SHEET_NAME = \"aggregate-metrics\" PER_TWITCH_METRICS_SHEET_NAME = \"per-twitch-metrics\" NUMBER_OF_PER_TWITCH_METRICS = 45 SNAPSHOT_CHART_SHEET_NAME = \"continuous-waveform-snapshots\"", "GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D constants \"\"\"", "UTC_BEGINNING_STIMULATION_UUID = uuid.UUID(\"4b310594-ded4-45fd-a1b4-b829aceb416c\") STIMULATION_PROTOCOL_UUID = uuid.UUID(\"ede638ce-544e-427a-b1d9-c40784d7c82d\") IS_CALIBRATION_FILE_UUID = uuid.UUID(\"9a6f90eb-fe34-423b-bfed-fb441d6d9e5f\") CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID", "From Baseline to Peak (seconds)\", PEAK_TO_BASELINE_UUID: \"Time From Peak to Baseline (seconds)\", }", "BOOTUP_COUNTER_UUID: \"The number of times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The", "SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\") MANTARRAY_NICKNAME_UUID = uuid.UUID(\"0cdec9bb-d2b4-4c5b-9dd5-6a49766c5ed4\") MANTARRAY_SERIAL_NUMBER_UUID = uuid.UUID(\"83720d36-b941-4d85-9b39-1d817799edd6\") REFERENCE_VOLTAGE_UUID", "CHANNEL_FIRMWARE_VERSION_UUID = uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( {", "SOFTWARE_BUILD_NUMBER_UUID: \"Software Build Number\", SOFTWARE_RELEASE_VERSION_UUID: \"Software Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\",", "the end of when the original data ended\", ORIGINAL_FILE_VERSION_UUID: \"The original version of", "11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021 by <NAME> MIDSCALE_CODE = 0x800000 RAW_TO_SIGNED_CONVERSION_VALUE", "Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of Maximum Active Twitch", "of Beginning of Recording\", UTC_BEGINNING_DATA_ACQUISTION_UUID: \"UTC Timestamp of Beginning of Data Acquisition\", UTC_BEGINNING_RECORDING_UUID:", "\"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\",", "field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA = 1073.6 # Obtained 03/09/2021", "Beta 1 GMR to magnetic field conversion values. Valid as of 11/19/21 MILLIVOLTS_PER_MILLITESLA", "= immutabledict( (coord, f\"Time From Peak to Relaxation {coord} (seconds)\") for coord in", "operation that doesn't return the dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID:", "= uuid.UUID(\"4927c810-fbf4-406f-a848-eba5308576e6\") USER_ACCOUNT_ID_UUID = uuid.UUID(\"7282cf00-2b6e-4202-9d9e-db0c73c3a71f\") SOFTWARE_BUILD_NUMBER_UUID = uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID =", "of the initial magnet finding params that should be used in Pulse3D\", }", "PLATE_BARCODE_IS_FROM_SCANNER_UUID: \"Is this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an", "(seconds)\") for coord in reversed(COORDS) ) RELAXATION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time", "\"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC", "the file when recorded, prior to any migrations to newer versions/formats.\", UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID: \"Timestamp", "TWITCH_FREQUENCY_UUID, TWITCH_PERIOD_UUID, ), } ) COORDS = (10, 25, 50, 75, 90) TWITCH_WIDTH_METRIC_DISPLAY_NAMES:", "or not the twitches in the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired", "flags present on device bootup\", INITIAL_MAGNET_FINDING_PARAMS: \"JSON string of the initial magnet finding", "to % relaxation TIME_VALUE_UUID = uuid.UUID(\"32f5ce6b-e311-4434-8a2a-c2b6bbd81ee6\") RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID", "(zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID:", "this plate barcode obtained from the scanner\", IS_FILE_ORIGINAL_UNTRIMMED_UUID: \"Is this an original file", "(seconds)\", TWITCH_FREQUENCY_UUID: \"Twitch Frequency (Hz)\", AMPLITUDE_UUID: \"Active Twitch Force (μN)\", FRACTION_MAX_UUID: \"Fraction of", "by <NAME>, Valid as of 11/19/21 MILLIMETERS_PER_MILLITESLA = 23.25 NEWTONS_PER_MILLIMETER = 0.000159 #", "MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue Sampling Period (µs) to default Pipeline Filter", "original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed off the", "from immutabledict import immutabledict from labware_domain_models import LabwareDefinition try: from importlib import metadata", "= uuid.UUID(\"cf60afef-a9f0-4bc3-89e9-c665c6bb6941\") STIM_BARCODE_UUID = uuid.UUID(\"6fa67db1-c8b9-4937-b93f-6fe8bdc7e6d7\") BACKEND_LOG_UUID = uuid.UUID(\"87533deb-2495-4430-bce7-12fdfc99158e\") COMPUTER_NAME_HASH_UUID = uuid.UUID(\"fefd0675-35c2-45f6-855a-9500ad3f100d\") PLATE_BARCODE_IS_FROM_SCANNER_UUID =", "COORDS ) ALL_FORMATS = immutabledict({\"CoV\": {\"num_format\": \"0.00%\"}}) TWITCHES_POINT_UP_UUID = uuid.UUID(\"97f69f56-f1c6-4c50-8590-7332570ed3c5\") INTERPOLATION_VALUE_UUID = uuid.UUID(\"466d0131-06b7-4f0f-ba1e-062a771cb280\")", "ADC_REF_OFFSET_UUID: \"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\",", "\"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID: \"Well Column (zero-based)\",", "magnet finding params that should be used in Pulse3D\", } ) DATETIME_STR_FORMAT =", "= uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID =", "= uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID = uuid.UUID(\"0ecf0e52-0a29-453f-a6ff-46f5ec3ae783\") BESSEL_LOWPASS_10_UUID = uuid.UUID(\"7d64cac3-b841-4912-b734-c0cf20a81e7a\") BESSEL_LOWPASS_30_UUID =", "uuid.UUID(\"b4db8436-10a4-4359-932d-aa80e6de5c76\") SOFTWARE_RELEASE_VERSION_UUID = uuid.UUID(\"432fc3c1-051b-4604-bc3d-cc0d0bd75368\") MAIN_FIRMWARE_VERSION_UUID = uuid.UUID(\"faa48a0c-0155-4234-afbf-5e5dbaa59537\") SLEEP_FIRMWARE_VERSION_UUID = uuid.UUID(\"3a816076-90e4-4437-9929-dc910724a49d\") XEM_SERIAL_NUMBER_UUID = uuid.UUID(\"e5f5b134-60c7-4881-a531-33aa0edba540\")", "Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period (microseconds)\", TISSUE_SAMPLING_PERIOD_UUID: \"Tissue Sensor Sampling", "CALCULATED_METRICS = immutabledict( { \"by_width\": (WIDTH_UUID, CONTRACTION_TIME_UUID, RELAXATION_TIME_UUID), \"scalar\": ( AMPLITUDE_UUID, AUC_UUID, BASELINE_TO_PEAK_UUID,", "CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5 CALCULATED_METRIC_DISPLAY_NAMES = { TWITCH_PERIOD_UUID: \"Twitch Period", "CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH", "** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA = 10", "# for full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10 CHART_HEIGHT", "Sampling Period (microseconds)\", ADC_GAIN_SETTING_UUID: \"ADC Gain Setting\", ADC_TISSUE_OFFSET_UUID: \"ADC Tissue Sensor Offset\", ADC_REF_OFFSET_UUID:", "= 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START + 4 METADATA_OUTPUT_FILE_ROW_START = METADATA_INSTRUMENT_ROW_START + 6 CONTINUOUS_WAVEFORM_SHEET_NAME", "1 / 100 INTERPOLATED_DATA_PERIOD_US = INTERPOLATED_DATA_PERIOD_SECONDS * MICRO_TO_BASE_CONVERSION TSP_TO_DEFAULT_FILTER_UUID = { # Tissue", "magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The stimulation protocol that", "figure edge and plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots -- number", "to add in the new values specific to the SDK (.update is an", "{coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time", "of centimilliseconds that has been trimmed off the beginning of when the original", "uuid.UUID(\"d9694cfe-824c-41f8-915e-91e41ce7af32\") BOOT_FLAGS_UUID = uuid.UUID(\"762f6715-ffcd-4e8d-b707-638dd5777841\") INITIAL_MAGNET_FINDING_PARAMS = uuid.UUID(\"da5f2f6d-6874-4e53-be10-90c4bfbd3d45\") METADATA_UUID_DESCRIPTIONS = immutabledict( { # General", "suspected the internals of the Mantarray enclosure have been tampered with\", PCB_SERIAL_NUMBER_UUID: \"The", "uuid.UUID(\"6e0cd81c-7861-4c49-ba14-87b2739d65fb\") # This is just the reciprocal of twitch period, but is pre-computed", "dictionary, so chaining is difficult) mutable_metadata_uuid_descriptions.update( { TWITCHES_POINT_UP_UUID: \"Flag indicating whether or not", "f\"Twitch Width {coord} (seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] =", "not the twitches in the data point up or not\", INTERPOLATION_VALUE_UUID: \"Desired value", "Empty string if stimulation was not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is", "RELAXATION_TIME_UUID = uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") AMPLITUDE_UUID = uuid.UUID(\"89cf1105-a015-434f-b527-4169b9400e26\") AUC_UUID = uuid.UUID(\"e7b9a6e4-c43d-4e8b-af7e-51742e252030\") WIDTH_UUID", "= \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis library \"\"\" MILLI_TO_BASE_CONVERSION = 1000 TWITCH_PERIOD_UUID =", "2 ** 15 MEMSIC_MSB = 2 ** 16 MEMSIC_FULL_SCALE = 16 GAUSS_PER_MILLITESLA =", "metrics BASELINE_TO_PEAK_UUID = uuid.UUID(\"03ce2d30-3580-4129-9913-2fc2e35eddb7\") PEAK_TO_BASELINE_UUID = uuid.UUID(\"1ac2589d-4713-41c0-8dd0-1e6c98600e37\") ALL_METRICS = [ TWITCH_PERIOD_UUID, FRACTION_MAX_UUID, AMPLITUDE_UUID,", "= 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS PEAK_VALLEY_COLUMN_START = 100 SECONDS_PER_CELL = 2.5", "\"The number of times this Mantarray Instrument has booted up\", TOTAL_WORKING_HOURS_UUID: \"The total", "typing import Dict import uuid from immutabledict import immutabledict from labware_domain_models import LabwareDefinition", "Release Version\", MAIN_FIRMWARE_VERSION_UUID: \"Firmware Version (Main Controller)\", SLEEP_FIRMWARE_VERSION_UUID: \"Firmware Version (Sleep Mode)\", MANTARRAY_NICKNAME_UUID:", "= uuid.UUID(\"371996e6-5e2d-4183-a5cf-06de7058210a\") TRIMMED_TIME_FROM_ORIGINAL_END_UUID = uuid.UUID(\"55f6770d-c369-42ce-a437-5ed89c3cb1f8\") ORIGINAL_FILE_VERSION_UUID = uuid.UUID(\"cd1b4063-4a87-4a57-bc12-923ff4890844\") UTC_TIMESTAMP_OF_FILE_VERSION_MIGRATION_UUID = uuid.UUID(\"399b2148-09d4-418b-a132-e37df2721938\") FILE_VERSION_PRIOR_TO_MIGRATION_UUID =", "Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference (seconds)\", WIDTH_UUID: \"Twitch Width {} (seconds)\", RELAXATION_TIME_UUID:", "Coordinates {coord}\") for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord,", "version to add in the new values specific to the SDK (.update is", "= 16 GAUSS_PER_MILLITESLA = 10 MIN_NUMBER_PEAKS = 3 MIN_NUMBER_VALLEYS = 3 \"\"\" pulse3D", "between right figure edge and plot area CHART_PIXELS_PER_SECOND = 35 # for full/snapshots", "for coord in reversed(COORDS) ) RELAXATION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Relaxation Coordinates", "uuid.UUID(\"0ad56cd1-7bcc-4b57-8076-14366d7f3c6a\") CONTRACTION_TIME_UUID = uuid.UUID(\"33b5b0a8-f197-46ef-a451-a254e530757b\") # Kristian 11/9/21: full contraction or full relaxation metrics", "of the board's magnetometers\", UTC_BEGINNING_STIMULATION_UUID: \"UTC Timestamp of Beginning of Stimulation\", STIMULATION_PROTOCOL_UUID: \"The", "with\", PCB_SERIAL_NUMBER_UUID: \"The serial number of the Mantarray PCB\", MAGNETOMETER_CONFIGURATION_UUID: \"The state (on/off)", "the concept of `None` in their metadata, so using this value to denote", "Serial Number\", REFERENCE_VOLTAGE_UUID: \"Reference Voltage\", WELL_NAME_UUID: \"Well Name\", WELL_ROW_UUID: \"Well Row (zero-based)\", WELL_COLUMN_UUID:", "REFERENCE_VOLTAGE_UUID = uuid.UUID(\"0b3f3f56-0cc7-45f0-b748-9b9de480cba8\") WELL_NAME_UUID = uuid.UUID(\"6d78f3b9-135a-4195-b014-e74dee70387b\") WELL_ROW_UUID = uuid.UUID(\"da82fe73-16dd-456a-ac05-0b70fb7e0161\") WELL_COLUMN_UUID = uuid.UUID(\"7af25a0a-8253-4d32-98c4-3c2ca0d83906\") WELL_INDEX_UUID", "RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\", TIME_DIFFERENCE_UUID: \"Time Difference", "FILE_VERSION_PRIOR_TO_MIGRATION_UUID: \"File format version that this file was migrated from\", # Beta 1", "of hours this Mantarray Instrument has been powered on and running\", TAMPER_FLAG_UUID: \"Is", "coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Time From Contraction", "PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID = uuid.UUID(\"72ba9466-c203-41b6-ac30-337b4a17a124\") SUBSEQUENT_PEAK_INDEX_UUID = uuid.UUID(\"7e37325b-6681-4623-b192-39f154350f36\") SUBSEQUENT_VALLEY_INDEX_UUID = uuid.UUID(\"fd47ba6b-ee4d-4674-9a89-56e0db7f3d97\") BESSEL_BANDPASS_UUID", "= 2 # Beta 2 Memsic to magnetic field conversion factors. Valid as", "this Mantarray Instrument has been powered on and running\", TAMPER_FLAG_UUID: \"Is it suspected", "that was running on this well during recording. Empty string if stimulation was", "piece of metadata is not available (i.e. after migrating to a newer file", "(seconds)\") for coord in reversed(COORDS) ) CONTRACTION_COORDINATES_DISPLAY_NAMES: Dict[int, str] = immutabledict( (coord, f\"Contraction", "scanner\", IS_CALIBRATION_FILE_UUID: \"Is this file a calibration (empty plate) recording\", CHANNEL_FIRMWARE_VERSION_UUID: \"Firmware Version", "\"E8\", } ) \"\"\" Magnet Finding \"\"\" # 10 seconds at sampling rate", "f\"Relaxation Coordinates {coord}\") for coord in COORDS ) CONTRACTION_TIME_DIFFERENCE_DISPLAY_NAMES: Dict[int, str] = immutabledict(", "\"\"\" pulse3D constants \"\"\" METADATA_EXCEL_SHEET_NAME = \"metadata\" METADATA_RECORDING_ROW_START = 0 METADATA_INSTRUMENT_ROW_START = METADATA_RECORDING_ROW_START", "Contraction Velocity (μN/second)\", RELAXATION_VELOCITY_UUID: \"Twitch Relaxation Velocity (μN/second)\", IRREGULARITY_INTERVAL_UUID: \"Twitch Interval Irregularity (seconds)\",", "uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\" CURRENT_BETA2_HDF5_FILE_FORMAT_VERSION =", "= 300 CHART_HEIGHT_CELLS = 15 CHART_FIXED_WIDTH_CELLS = 8 CHART_FIXED_WIDTH = DEFAULT_CELL_WIDTH * CHART_FIXED_WIDTH_CELLS", "beginning of when the original data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has", "not active\", STIM_BARCODE_UUID: \"Stim Lid Barcode\", STIM_BARCODE_IS_FROM_SCANNER_UUID: \"Is this stim lid barcode obtained", "data started\", TRIMMED_TIME_FROM_ORIGINAL_END_UUID: \"Number of centimilliseconds that has been trimmed off the end", "CONTRACTION_VELOCITY_UUID, RELAXATION_VELOCITY_UUID, IRREGULARITY_INTERVAL_UUID, BASELINE_TO_PEAK_UUID, PEAK_TO_BASELINE_UUID, WIDTH_UUID, RELAXATION_TIME_UUID, CONTRACTION_TIME_UUID, ] PRIOR_PEAK_INDEX_UUID = uuid.UUID(\"80df90dc-21f8-4cad-a164-89436909b30a\") PRIOR_VALLEY_INDEX_UUID", "file format version) HARDWARE_TEST_RECORDING_UUID = uuid.UUID(\"a2e76058-08cd-475d-a55d-31d401c3cb34\") UTC_BEGINNING_DATA_ACQUISTION_UUID = uuid.UUID(\"98c67f22-013b-421a-831b-0ea55df4651e\") START_RECORDING_TIME_INDEX_UUID = uuid.UUID(\"e41422b3-c903-48fd-9856-46ff56a6534c\") UTC_BEGINNING_RECORDING_UUID", "= uuid.UUID(\"eee66c75-4dc4-4eb4-8d48-6c608bf28d91\") BUTTERWORTH_LOWPASS_30_UUID = uuid.UUID(\"de8d8cef-65bf-4119-ada7-bdecbbaa897a\") # General mangetic field to force conversion factor.", "%H:%M:%S.%f\" CENTIMILLISECONDS_PER_SECOND = int(1e5) MICRO_TO_BASE_CONVERSION = int(1e6) MICROSECONDS_PER_CENTIMILLISECOND = 10 TISSUE_SENSOR_READINGS = \"tissue_sensor_readings\"", "\"ADC Reference Sensor Offset\", PLATE_BARCODE_UUID: \"Plate Barcode\", BACKEND_LOG_UUID: \"Backend log file identifier\", COMPUTER_NAME_HASH_UUID:", "\"Well Index (zero-based)\", TOTAL_WELL_COUNT_UUID: \"Total Wells in Plate\", REF_SAMPLING_PERIOD_UUID: \"Reference Sensor Sampling Period", "= uuid.UUID(\"7ca73e1c-9555-4eca-8281-3f844b5606dc\") REF_SAMPLING_PERIOD_UUID = uuid.UUID(\"48aa034d-8775-453f-b135-75a983d6b553\") TISSUE_SAMPLING_PERIOD_UUID = uuid.UUID(\"f629083a-3724-4100-8ece-c03e637ac19c\") ADC_GAIN_SETTING_UUID = uuid.UUID(\"a3c3bb32-9b92-4da1-8ed8-6c09f9c816f8\") ADC_TISSUE_OFFSET_UUID =", "35 # for full/snapshots -- number of pixels per second CHART_MAXIMUM_SNAPSHOT_LENGTH = 10", "STIMULATION_READINGS = \"stimulation_readings\" TIME_INDICES = \"time_indices\" TIME_OFFSETS = \"time_offsets\" \"\"\" constants from mantarray_waveform_analysis", "CURI_BIO_USER_ACCOUNT_ID = uuid.UUID(\"<KEY>\") TWENTY_FOUR_WELL_PLATE = LabwareDefinition(row_count=4, column_count=6) MIN_SUPPORTED_FILE_VERSION = \"0.1.1\" CURRENT_BETA1_HDF5_FILE_FORMAT_VERSION = \"0.4.2\"", ") # Eli (1/19/21): H5 files can't store the concept of `None` in" ]
[ "HS.poll() ) except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(),", "INFLUX_IP IP address of the machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT", "read in environment variables, set some defaults if env vars are not defined", "to InfluxDB. \"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power()", "class HS110: def __init__(self, ip, port): self.ip = ip self.port = port def", "\"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}'))", "default: HS110 SAMPLE_TIME time to wait before getting the next sample, default: 60", "INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER')", "not connect to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\"", "\"\"\" decrypt power data and convert to Volts, Ampere, Watt, kWh \"\"\" import", "self.port = port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR", "select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb #################################################################################################### def write_database(client,", "import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V", "prints unexpected results. Copy/paste from my homeclimate code. \"\"\" from datetime import datetime", "= socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except:", "# Send data to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a given", "60 \"\"\" #################################################################################################### # imports #################################################################################################### import os import time from influxdb import", "def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with", "and receive power data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10))", "create new database if necessary if not INFLUX_DB in [db['name'] for db in", "while True: try: write_database(client = client, data = HS.poll() ) except Exception as", "code 9999 This error code is presumably not used by TP-Link, so I", "# Continuously take data #################################################################################################### try: while True: try: write_database(client = client, data", "} except: raise TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\" In case", "iresponse: print(\"Sending data to database failed. Response: \", iresponse) except inexc.InfluxDBServerError as e:", "= os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or", "or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER", "8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB =", "receive power data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip,", "= sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\"", "decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\" In", "are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP =", "print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime,", "Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously", "db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data", "the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write the measurements to, default:", "data #################################################################################################### try: while True: try: write_database(client = client, data = HS.poll() )", "\"\" for i in self.encrypted[4:]: a = key ^ i key = i", "# V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, #", "i self.decrypted += chr(a) def get_raw(self): \"\"\" connect to HS110, send payload and", "vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP", "# W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not", "the measurements to, default: HS110 SAMPLE_TIME time to wait before getting the next", "try: iresponse = client.write_points(data) if not iresponse: print(\"Sending data to database failed. Response:", "client.write_points(data) if not iresponse: print(\"Sending data to database failed. Response: \", iresponse) except", "i in self.encrypted[4:]: a = key ^ i key = i self.decrypted +=", "# imports #################################################################################################### import os import time from influxdb import InfluxDBClient import influxdb.exceptions", "# connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username", "except: raise TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\" In case of", "e: print(datetime.utcnow().isoformat(), \" Sending data to database failed due to timeout.\\n\", e) pass", "error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }]", "code. \"\"\" from datetime import datetime try: iresponse = client.write_points(data) if not iresponse:", "highjack this metric to let '9999' denote errors within HS110Influx. \"\"\" self.data =", "socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted =", "log FritzBox to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This", "as inexc #################################################################################################### # settings #################################################################################################### # read in environment variables, set some", "{'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### # Set", "for i in self.encrypted[4:]: a = key ^ i key = i self.decrypted", "\", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to database failed", "time from influxdb import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings ####################################################################################################", ") # create new database if necessary if not INFLUX_DB in [db['name'] for", "errors within HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None, 'power': None, 'energy_total':", "machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB,", "due to timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown", "\"\"\" In case of an error set all data to None and return", "\" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields':", "kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned data.\") def error_data(self):", "port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher", "decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000,", "'<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### #", "import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error", "= int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or", "presumably not used by TP-Link, so I highjack this metric to let '9999'", "# select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb #################################################################################################### def", "print(polltime, \" Error decrypting data\") self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data", "returned data.\") def error_data(self): \"\"\" In case of an error set all data", "= ip self.port = port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home", "address of the HS110 HS110_PORT port to use for the connection, default: 9999", "error_data(self): \"\"\" In case of an error set all data to None and", "self.encrypted[4:]: a = key ^ i key = i self.decrypted += chr(a) def", "decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could", "'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize ####################################################################################################", "= INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> ) # create new database", "i key = i self.decrypted += chr(a) def get_raw(self): \"\"\" connect to HS110,", "\"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment variables for", ") except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \"", "to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment variables for authentification and", "None, 'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\" Poll the HS110 and", "authentification and settings: HS110_IP IP address of the HS110 HS110_PORT port to use", "to HS110, send payload and receive power data \"\"\" import socket try: sock_tcp", "HS110_PORT port to use for the connection, default: 9999 INFLUX_IP IP address of", "the next sample, default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import os import", "\"\"\" self.data = {'voltage': None, 'current': None, 'power': None, 'energy_total': None, 'error_code': 9999", "as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped by", "to use for the connection, default: 9999 INFLUX_IP IP address of the machine", "sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close()", "error code is presumably not used by TP-Link, so I highjack this metric", "database and prints unexpected results. Copy/paste from my homeclimate code. \"\"\" from datetime", "import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### # read in", "from datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime,", "#################################################################################################### # log FritzBox to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME>", "60) #################################################################################################### # helper functions #################################################################################################### class HS110: def __init__(self, ip, port): self.ip", "self.ip = ip self.port = port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart", "database failed. Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data", "password to access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write the", "record to the database and prints unexpected results. Copy/paste from my homeclimate code.", "iresponse = client.write_points(data) if not iresponse: print(\"Sending data to database failed. Response: \",", "data): \"\"\" Writes a given data record to the database and prints unexpected", "int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>'", "self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, #", "Home Protocoll: XOR Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug", "+= chr(a) def get_raw(self): \"\"\" connect to HS110, send payload and receive power", "raise TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\" In case of an", "decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A", "the machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port to connect to", "FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment variables for authentification", "Send data to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a given data", "timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e)", "= 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\" for", "None, 'error_code': 9999 } def poll(self): \"\"\" Poll the HS110 and format the", "key = 171 self.decrypted = \"\" for i in self.encrypted[4:]: a = key", "#################################################################################################### import os import time from influxdb import InfluxDBClient import influxdb.exceptions as inexc", "'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise", "'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### # Set up HS110", "or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) ####################################################################################################", "to be sent to InfluxDB. \"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat()", "#################################################################################################### # Send data to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a", "port to use for the connection, default: 9999 INFLUX_IP IP address of the", "Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key =", "measurements to, default: HS110 SAMPLE_TIME time to wait before getting the next sample,", "HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting data\") self.error_data except Exception: print(polltime,", "current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb #################################################################################################### def write_database(client, data):", "Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage':", "follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key = 171 result = pack('>I',", "key ^ i key = i self.decrypted += chr(a) def get_raw(self): \"\"\" connect", "client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password =", "def error_data(self): \"\"\" In case of an error set all data to None", "not decrypt returned data.\") def error_data(self): \"\"\" In case of an error set", "pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass ####################################################################################################", "so I highjack this metric to let '9999' denote errors within HS110Influx. \"\"\"", "Continuously take data #################################################################################################### try: while True: try: write_database(client = client, data =", "decrypt_power(self): \"\"\" decrypt power data and convert to Volts, Ampere, Watt, kWh \"\"\"", "\"\"\" #################################################################################################### # imports #################################################################################################### import os import time from influxdb import InfluxDBClient", "getting the next sample, default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import os", "os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root'", "access the InfluxDB database, default: root INFLUX_PASSWD password to access the InfluxDB database,", "or 60) #################################################################################################### # helper functions #################################################################################################### class HS110: def __init__(self, ip, port):", "if necessary if not INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) #", "environment variables for authentification and settings: HS110_IP IP address of the HS110 HS110_PORT", "9999 This error code is presumably not used by TP-Link, so I highjack", "for authentification and settings: HS110_IP IP address of the HS110 HS110_PORT port to", "Writes a given data record to the database and prints unexpected results. Copy/paste", "except: raise ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port))", "\"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and convert to Volts, Ampere, Watt,", "= INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> ) #", "inexc #################################################################################################### # settings #################################################################################################### # read in environment variables, set some defaults", "author: <NAME> (GiantMolecularCloud) This script uses environment variables for authentification and settings: HS110_IP", "use for the connection, default: 9999 INFLUX_IP IP address of the machine InfluxDB", "follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\" for i in self.encrypted[4:]:", "True: try: write_database(client = client, data = HS.poll() ) except Exception as e:", "HS110 and format the data to be sent to InfluxDB. \"\"\" from datetime", "(GiantMolecularCloud) This script uses environment variables for authentification and settings: HS110_IP IP address", "# Set up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client", "This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key = 171 result =", "I highjack this metric to let '9999' denote errors within HS110Influx. \"\"\" self.data", "connection, default: 9999 INFLUX_IP IP address of the machine InfluxDB is running on,", "This error code is presumably not used by TP-Link, so I highjack this", "result += bytes([a]) return result def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home", "import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted", "datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \"", "failed due to timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered", "to let '9999' denote errors within HS110Influx. \"\"\" self.data = {'voltage': None, 'current':", "\" Error decrypting data\") self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data return", "inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to database failed due to timeout.\\n\",", "to Volts, Ampere, Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted)", "INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> ) # create", "my homeclimate code. \"\"\" from datetime import datetime try: iresponse = client.write_points(data) if", "self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except TypeError: print(polltime,", "}] #################################################################################################### # Initialize #################################################################################################### # Set up HS110 HS = HS110(HS110_IP, HS110_PORT)", "data = HS.poll() ) except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt:", "return result def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR Autokey", "wait before getting the next sample, default: 60 \"\"\" #################################################################################################### # imports ####################################################################################################", "\"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and convert to", "int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086)", "= key ^ i key = i self.decrypted += chr(a) def get_raw(self): \"\"\"", "default: root INFLUX_PASSWD password to access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database", "= a result += bytes([a]) return result def decrypt(self): \"\"\" Decrypt the TP-Link", "pack key = 171 result = pack('>I', len(string)) for i in string: a", "'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code':", "defaults if env vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT')", "self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor':", "'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME =", "[{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize", "settings #################################################################################################### # read in environment variables, set some defaults if env vars", "Initialize #################################################################################################### # Set up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to", "HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host =", "= HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port", "on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and convert to Volts,", "contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting data\") self.error_data except Exception:", "127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default: 8086 INFLUX_USER user to access", "Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171", "= pack('>I', len(string)) for i in string: a = key ^ ord(i) key", "a = key ^ i key = i self.decrypted += chr(a) def get_raw(self):", "= port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR Autokey", "print(polltime, \" Error contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting data\")", "connect to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt", "be sent to InfluxDB. \"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat() try:", "HS110, send payload and receive power data \"\"\" import socket try: sock_tcp =", "port = INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> ) # create new", "Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped", "of the HS110 HS110_PORT port to use for the connection, default: 9999 INFLUX_IP", "key = i self.decrypted += chr(a) def get_raw(self): \"\"\" connect to HS110, send", "<PASSWORD> INFLUX_DB Database to write the measurements to, default: HS110 SAMPLE_TIME time to", "for the connection, default: 9999 INFLUX_IP IP address of the machine InfluxDB is", "print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously take data ####################################################################################################", "import influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### # read in environment variables,", "Error decrypting data\") self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement':", "failed. Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to", "to connect to InfluxDB, default: 8086 INFLUX_USER user to access the InfluxDB database,", "TypeError: print(polltime, \" Error decrypting data\") self.error_data except Exception: print(polltime, \" Unknown error.\")", "def write_database(client, data): \"\"\" Writes a given data record to the database and", "an error set all data to None and return error code 9999 This", "INFLUX_USER user to access the InfluxDB database, default: root INFLUX_PASSWD password to access", "or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD", "next sample, default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import os import time", "of an error set all data to None and return error code 9999", "W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt", "<NAME> (GiantMolecularCloud) This script uses environment variables for authentification and settings: HS110_IP IP", "on, default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default: 8086 INFLUX_USER user", "HS110_IP IP address of the HS110 HS110_PORT port to use for the connection,", "and prints unexpected results. Copy/paste from my homeclimate code. \"\"\" from datetime import", "#################################################################################################### try: while True: try: write_database(client = client, data = HS.poll() ) except", "struct import pack key = 171 result = pack('>I', len(string)) for i in", "\"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError:", "e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard", "os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT =", "= 171 result = pack('>I', len(string)) for i in string: a = key", "def poll(self): \"\"\" Poll the HS110 and format the data to be sent", "Copy/paste from my homeclimate code. \"\"\" from datetime import datetime try: iresponse =", "Decrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key =", "before getting the next sample, default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import", "V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh", "user to access the InfluxDB database, default: root INFLUX_PASSWD password to access the", "'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### # Set up", "= key ^ ord(i) key = a result += bytes([a]) return result def", "in self.encrypted[4:]: a = key ^ i key = i self.decrypted += chr(a)", "data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None)", "\"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key", "#################################################################################################### # settings #################################################################################################### # read in environment variables, set some defaults if", "INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB')", "In case of an error set all data to None and return error", "datetime import datetime try: iresponse = client.write_points(data) if not iresponse: print(\"Sending data to", "root INFLUX_PASSWD password to access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to", "\"\"\" from datetime import datetime try: iresponse = client.write_points(data) if not iresponse: print(\"Sending", "power data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port))", "} def poll(self): \"\"\" Poll the HS110 and format the data to be", "self.decrypted = \"\" for i in self.encrypted[4:]: a = key ^ i key", "XOR Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key", "to write the measurements to, default: HS110 SAMPLE_TIME time to wait before getting", "= client, data = HS.poll() ) except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME)", "influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### # read in environment variables, set", "database, default: root INFLUX_PASSWD password to access the InfluxDB database, default: <PASSWORD> INFLUX_DB", "InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment variables for authentification and settings:", "FritzBox to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script", "variables for authentification and settings: HS110_IP IP address of the HS110 HS110_PORT port", "a = key ^ ord(i) key = a result += bytes([a]) return result", "This script uses environment variables for authentification and settings: HS110_IP IP address of", "the InfluxDB database, default: root INFLUX_PASSWD password to access the InfluxDB database, default:", "Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time':", "finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard interrupt [CTRL_C]", "'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### # Set up HS110 HS =", "starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted =", "the HS110 HS110_PORT port to use for the connection, default: 9999 INFLUX_IP IP", "denote errors within HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None, 'power': None,", "database failed due to timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(), \"", "in string: a = key ^ ord(i) key = a result += bytes([a])", "def get_raw(self): \"\"\" connect to HS110, send payload and receive power data \"\"\"", "Volts, Ampere, Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data", "key = 171 result = pack('>I', len(string)) for i in string: a =", "pass #################################################################################################### # Continuously take data #################################################################################################### try: while True: try: write_database(client =", "let '9999' denote errors within HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None,", "9999 INFLUX_IP IP address of the machine InfluxDB is running on, default: 127.0.0.1", "len(string)) for i in string: a = key ^ ord(i) key = a", "# create new database if necessary if not INFLUX_DB in [db['name'] for db", "from datetime import datetime try: iresponse = client.write_points(data) if not iresponse: print(\"Sending data", "ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self):", "sample, default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import os import time from", "in environment variables, set some defaults if env vars are not defined HS110_IP", "[db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### #", "a given data record to the database and prints unexpected results. Copy/paste from", "{'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total':", "= client.write_points(data) if not iresponse: print(\"Sending data to database failed. Response: \", iresponse)", "or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME", "INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD')", "power data and convert to Volts, Ampere, Watt, kWh \"\"\" import json try:", "decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting", "to timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\",", "code is presumably not used by TP-Link, so I highjack this metric to", "print (datetime.now(), \" Program stopped by keyboard interrupt [CTRL_C] by user. \") ####################################################################################################", "send payload and receive power data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET,", "client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb ####################################################################################################", "HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data", "8086 INFLUX_USER user to access the InfluxDB database, default: root INFLUX_PASSWD password to", "Database to write the measurements to, default: HS110 SAMPLE_TIME time to wait before", "starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key", "from struct import pack key = 171 result = pack('>I', len(string)) for i", "password = <PASSWORD> ) # create new database if necessary if not INFLUX_DB", "e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously take data", "'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\" Poll the HS110 and format", "connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username =", "encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting", "= 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key = 171", "to access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write the measurements", "print(datetime.utcnow().isoformat(), \" Sending data to database failed due to timeout.\\n\", e) pass except", "171 self.decrypted = \"\" for i in self.encrypted[4:]: a = key ^ i", "os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110'", "not INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database", "\"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key", "^ ord(i) key = a result += bytes([a]) return result def decrypt(self): \"\"\"", "e) pass #################################################################################################### # Continuously take data #################################################################################################### try: while True: try: write_database(client", "# read in environment variables, set some defaults if env vars are not", "payload and receive power data \"\"\" import socket try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)", "9999 } def poll(self): \"\"\" Poll the HS110 and format the data to", "def decrypt_power(self): \"\"\" decrypt power data and convert to Volts, Ampere, Watt, kWh", "INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB)", "# Initialize #################################################################################################### # Set up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect", "= os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or", "ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting", "HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP,", "os import time from influxdb import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### #", "to the database and prints unexpected results. Copy/paste from my homeclimate code. \"\"\"", "Poll the HS110 and format the data to be sent to InfluxDB. \"\"\"", "InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### # read in environment", "datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting", "to database failed. Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending", "print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard interrupt", "uses environment variables for authentification and settings: HS110_IP IP address of the HS110", "Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import", "socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could", "time to wait before getting the next sample, default: 60 \"\"\" #################################################################################################### #", "necessary if not INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select", "not iresponse: print(\"Sending data to database failed. Response: \", iresponse) except inexc.InfluxDBServerError as", "to None and return error code 9999 This error code is presumably not", "HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT,", "int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions #################################################################################################### class HS110: def __init__(self, ip,", "#################################################################################################### # Set up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB", "= <PASSWORD> ) # create new database if necessary if not INFLUX_DB in", "XOR Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from", "up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host", "if not iresponse: print(\"Sending data to database failed. Response: \", iresponse) except inexc.InfluxDBServerError", "# log FritzBox to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud)", "https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\" for i in self.encrypted[4:]: a", "client, data = HS.poll() ) except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except", "sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\" on", "default: <PASSWORD> INFLUX_DB Database to write the measurements to, default: HS110 SAMPLE_TIME time", "kWh \"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000,", "key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key =", "bytes([a]) return result def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR", "\"\"\" connect to HS110, send payload and receive power data \"\"\" import socket", "self.decrypted += chr(a) def get_raw(self): \"\"\" connect to HS110, send payload and receive", "and convert to Volts, Ampere, Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict", "= {'voltage': None, 'current': None, 'power': None, 'energy_total': None, 'error_code': 9999 } def", "self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] ####################################################################################################", "InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write the measurements to, default: HS110", "try: write_database(client = client, data = HS.poll() ) except Exception as e: print(e)", "except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass #################################################################################################### #", "a result += bytes([a]) return result def decrypt(self): \"\"\" Decrypt the TP-Link Smart", "= InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD>", "try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000,", "functions #################################################################################################### class HS110: def __init__(self, ip, port): self.ip = ip self.port =", "SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions #################################################################################################### class HS110: def", "Encrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key =", "\"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, #", "{'voltage': None, 'current': None, 'power': None, 'energy_total': None, 'error_code': 9999 } def poll(self):", "key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\"", "def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher with", "of the machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port to connect", "import pack key = 171 result = pack('>I', len(string)) for i in string:", "time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard interrupt [CTRL_C] by", "# settings #################################################################################################### # read in environment variables, set some defaults if env", "sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not", "None and return error code 9999 This error code is presumably not used", "by TP-Link, so I highjack this metric to let '9999' denote errors within", "raise ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def", "None, 'current': None, 'power': None, 'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\"", "A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except:", "try: while True: try: write_database(client = client, data = HS.poll() ) except Exception", "INFLUX_PORT port to connect to InfluxDB, default: 8086 INFLUX_USER user to access the", "#################################################################################################### # Continuously take data #################################################################################################### try: while True: try: write_database(client = client,", "#################################################################################################### # read in environment variables, set some defaults if env vars are", "This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\" for i in", "data\") self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags':", "to wait before getting the next sample, default: 60 \"\"\" #################################################################################################### # imports", "self.polltime, 'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### # Set up HS110 HS", "InfluxDB, default: 8086 INFLUX_USER user to access the InfluxDB database, default: root INFLUX_PASSWD", "data to be sent to InfluxDB. \"\"\" from datetime import datetime self.polltime =", "is running on, default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default: 8086", "171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted = \"\" for i", "Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously take data #################################################################################################### try: while", "= i self.decrypted += chr(a) def get_raw(self): \"\"\" connect to HS110, send payload", "= INFLUX_USER, password = <PASSWORD> ) # create new database if necessary if", "homeclimate code. \"\"\" from datetime import datetime try: iresponse = client.write_points(data) if not", "as e: print(datetime.utcnow().isoformat(), \" Sending data to database failed due to timeout.\\n\", e)", "default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default: 8086 INFLUX_USER user to", "= \"\" for i in self.encrypted[4:]: a = key ^ i key =", "decrypting data\") self.error_data except Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power',", "to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER,", "running on, default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default: 8086 INFLUX_USER", "imports #################################################################################################### import os import time from influxdb import InfluxDBClient import influxdb.exceptions as", "port to connect to InfluxDB, default: 8086 INFLUX_USER user to access the InfluxDB", "chr(a) def get_raw(self): \"\"\" connect to HS110, send payload and receive power data", "Error contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting data\") self.error_data except", "the connection, default: 9999 INFLUX_IP IP address of the machine InfluxDB is running", "results. Copy/paste from my homeclimate code. \"\"\" from datetime import datetime try: iresponse", "= HS.poll() ) except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print", "IP address of the HS110 HS110_PORT port to use for the connection, default:", "try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except TypeError:", "sent to InfluxDB. \"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw()", "^ i key = i self.decrypted += chr(a) def get_raw(self): \"\"\" connect to", "'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### # Initialize #################################################################################################### #", "result def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll: XOR Autokey Cipher", "datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except", "Set up HS110 HS = HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client =", "\"\"\" Poll the HS110 and format the data to be sent to InfluxDB.", "self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110 at IP", "import time from influxdb import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings", "def __init__(self, ip, port): self.ip = ip self.port = port def encrypt(self,string): \"\"\"", "return error code 9999 This error code is presumably not used by TP-Link,", "in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) ####################################################################################################", "write_database(client = client, data = HS.poll() ) except Exception as e: print(e) finally:", "<filename>HS110Influx.py #################################################################################################### # log FritzBox to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author:", "with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" key = 171 self.decrypted", "metric to let '9999' denote errors within HS110Influx. \"\"\" self.data = {'voltage': None,", "access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write the measurements to,", "format the data to be sent to InfluxDB. \"\"\" from datetime import datetime", "take data #################################################################################################### try: while True: try: write_database(client = client, data = HS.poll()", "database if necessary if not INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB)", "return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data }] #################################################################################################### #", "INFLUX_PASSWD password to access the InfluxDB database, default: <PASSWORD> INFLUX_DB Database to write", "error set all data to None and return error code 9999 This error", "unexpected results. Copy/paste from my homeclimate code. \"\"\" from datetime import datetime try:", "all data to None and return error code 9999 This error code is", "# kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned data.\") def", "used by TP-Link, so I highjack this metric to let '9999' denote errors", "to access the InfluxDB database, default: root INFLUX_PASSWD password to access the InfluxDB", "settings: HS110_IP IP address of the HS110 HS110_PORT port to use for the", "ord(i) key = a result += bytes([a]) return result def decrypt(self): \"\"\" Decrypt", "171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key = 171 result", "json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000,", "data record to the database and prints unexpected results. Copy/paste from my homeclimate", "socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise", "#################################################################################################### # Initialize #################################################################################################### # Set up HS110 HS = HS110(HS110_IP, HS110_PORT) #", "#################################################################################################### # helper functions #################################################################################################### class HS110: def __init__(self, ip, port): self.ip =", "to HS110 at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power", "= datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data", "INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME')", "at IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and", "INFLUX_DB Database to write the measurements to, default: HS110 SAMPLE_TIME time to wait", "IP \"+str(self.ip)+\" on port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and convert", "'current': None, 'power': None, 'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\" Poll", "Protocoll: XOR Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\"", "in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to", "the HS110 and format the data to be sent to InfluxDB. \"\"\" from", "convert to Volts, Ampere, Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict =", "HS110: def __init__(self, ip, port): self.ip = ip self.port = port def encrypt(self,string):", "e) pass except Exception as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass", "'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions #################################################################################################### class HS110:", "decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code']", "some defaults if env vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT =", "port): self.ip = ip self.port = port def encrypt(self,string): \"\"\" Encrypt the TP-Link", "is presumably not used by TP-Link, so I highjack this metric to let", "with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack", "script uses environment variables for authentification and settings: HS110_IP IP address of the", "from influxdb import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### #", "'9999' denote errors within HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None, 'power':", "data to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a given data record", "InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment", "INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper", "within HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None, 'power': None, 'energy_total': None,", "INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> ) # create new database if", "TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key = 171 This", "Ampere, Watt, kWh \"\"\" import json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data =", "or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD = os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB", "#################################################################################################### class HS110: def __init__(self, ip, port): self.ip = ip self.port = port", "HS110(HS110_IP, HS110_PORT) # connect to InfluxDB client = InfluxDBClient(host = INFLUX_IP, port =", "InfluxDB client = InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password", "TP-Link, so I highjack this metric to let '9999' denote errors within HS110Influx.", "to InfluxDB, default: 8086 INFLUX_USER user to access the InfluxDB database, default: root", "key ^ ord(i) key = a result += bytes([a]) return result def decrypt(self):", "client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes", "except Exception as e: print(e) finally: time.sleep(SAMPLE_TIME) except KeyboardInterrupt: print (datetime.now(), \" Program", "HS110 HS110_PORT port to use for the connection, default: 9999 INFLUX_IP IP address", "default: 8086 INFLUX_USER user to access the InfluxDB database, default: root INFLUX_PASSWD password", "and settings: HS110_IP IP address of the HS110 HS110_PORT port to use for", "9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER =", "decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned data.\")", "not used by TP-Link, so I highjack this metric to let '9999' denote", "unknown error.\\n\", e) pass #################################################################################################### # Continuously take data #################################################################################################### try: while True:", "username = INFLUX_USER, password = <PASSWORD> ) # create new database if necessary", "helper functions #################################################################################################### class HS110: def __init__(self, ip, port): self.ip = ip self.port", "os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60)", "Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'}, 'time': self.polltime, 'fields': self.data", "to influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a given data record to", "case of an error set all data to None and return error code", "import datetime try: iresponse = client.write_points(data) if not iresponse: print(\"Sending data to database", "ip, port): self.ip = ip self.port = port def encrypt(self,string): \"\"\" Encrypt the", "the database and prints unexpected results. Copy/paste from my homeclimate code. \"\"\" from", "= 171 self.decrypted = \"\" for i in self.encrypted[4:]: a = key ^", "default: 9999 INFLUX_IP IP address of the machine InfluxDB is running on, default:", "'error_code': 9999 } def poll(self): \"\"\" Poll the HS110 and format the data", "environment variables, set some defaults if env vars are not defined HS110_IP =", "except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error", "\" Error contacting HS110.\") self.error_data except TypeError: print(polltime, \" Error decrypting data\") self.error_data", "except KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard interrupt [CTRL_C] by user.", "and return error code 9999 This error code is presumably not used by", "port \"+str(self.port)) def decrypt_power(self): \"\"\" decrypt power data and convert to Volts, Ampere,", "<PASSWORD> ) # create new database if necessary if not INFLUX_DB in [db['name']", "Sending data to database failed due to timeout.\\n\", e) pass except Exception as", "data.\") def error_data(self): \"\"\" In case of an error set all data to", "HS110 SAMPLE_TIME time to wait before getting the next sample, default: 60 \"\"\"", "pack('>I', len(string)) for i in string: a = key ^ ord(i) key =", "or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions #################################################################################################### class", "if env vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or", "try: sock_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock_tcp.settimeout(int(10)) sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048)", "#################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses environment variables", "data to database failed due to timeout.\\n\", e) pass except Exception as e:", "address of the machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port to", "os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions ####################################################################################################", "self.data }] #################################################################################################### # Initialize #################################################################################################### # Set up HS110 HS = HS110(HS110_IP,", "Autokey Cipher with starting key = 171 This follows: https://github.com/softScheck/tplink-smartplug \"\"\" from struct", "data and convert to Volts, Ampere, Watt, kWh \"\"\" import json try: self.decrypt()", "IP address of the machine InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port", "influxdb #################################################################################################### def write_database(client, data): \"\"\" Writes a given data record to the", "decrypt returned data.\") def error_data(self): \"\"\" In case of an error set all", "self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to", "set all data to None and return error code 9999 This error code", "InfluxDBClient(host = INFLUX_IP, port = INFLUX_PORT, username = INFLUX_USER, password = <PASSWORD> )", "#################################################################################################### def write_database(client, data): \"\"\" Writes a given data record to the database", "decrypt power data and convert to Volts, Ampere, Watt, kWh \"\"\" import json", "sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110 at", "default: 60 \"\"\" #################################################################################################### # imports #################################################################################################### import os import time from influxdb", "#################################################################################################### # imports #################################################################################################### import os import time from influxdb import InfluxDBClient import", "self.data = {'voltage': None, 'current': None, 'power': None, 'energy_total': None, 'error_code': 9999 }", "except Exception: print(polltime, \" Unknown error.\") self.error_data return [{'measurement': 'power', 'tags': {'sensor': 'HS110'},", "data to None and return error code 9999 This error code is presumably", "\" Sending data to database failed due to timeout.\\n\", e) pass except Exception", "import os import time from influxdb import InfluxDBClient import influxdb.exceptions as inexc ####################################################################################################", "for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send", "ip self.port = port def encrypt(self,string): \"\"\" Encrypt the TP-Link Smart Home Protocoll:", "KeyboardInterrupt: print (datetime.now(), \" Program stopped by keyboard interrupt [CTRL_C] by user. \")", "self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\") self.error_data except TypeError: print(polltime, \"", "to InfluxDB #################################################################################################### \"\"\" FritzBox to InfluxDB author: <NAME> (GiantMolecularCloud) This script uses", "HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT')", "HS110Influx. \"\"\" self.data = {'voltage': None, 'current': None, 'power': None, 'energy_total': None, 'error_code':", "__init__(self, ip, port): self.ip = ip self.port = port def encrypt(self,string): \"\"\" Encrypt", "\" Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously take data #################################################################################################### try:", "self.error_data except TypeError: print(polltime, \" Error decrypting data\") self.error_data except Exception: print(polltime, \"", "not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP')", "INFLUX_USER, password = <PASSWORD> ) # create new database if necessary if not", "data to database failed. Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \"", "json try: self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current':", "given data record to the database and prints unexpected results. Copy/paste from my", "# helper functions #################################################################################################### class HS110: def __init__(self, ip, port): self.ip = ip", "TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\" In case of an error", "self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except ConnectionError: print(polltime, \" Error contacting HS110.\")", "'127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or 8086) INFLUX_USER = os.getenv('INFLUX_USER') or 'root' INFLUX_PASSWD =", "# A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W 'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] }", "to, default: HS110 SAMPLE_TIME time to wait before getting the next sample, default:", "connect to HS110, send payload and receive power data \"\"\" import socket try:", "client.get_list_database()]: client.create_database(INFLUX_DB) # select current database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb", "this metric to let '9999' denote errors within HS110Influx. \"\"\" self.data = {'voltage':", "write_database(client, data): \"\"\" Writes a given data record to the database and prints", "env vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999)", "+= bytes([a]) return result def decrypt(self): \"\"\" Decrypt the TP-Link Smart Home Protocoll:", "InfluxDB is running on, default: 127.0.0.1 INFLUX_PORT port to connect to InfluxDB, default:", "error code 9999 This error code is presumably not used by TP-Link, so", "influxdb import InfluxDBClient import influxdb.exceptions as inexc #################################################################################################### # settings #################################################################################################### # read", "string: a = key ^ ord(i) key = a result += bytes([a]) return", "for i in string: a = key ^ ord(i) key = a result", "= int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions #################################################################################################### class HS110: def __init__(self,", "set some defaults if env vars are not defined HS110_IP = os.getenv('HS110_IP') HS110_PORT", "new database if necessary if not INFLUX_DB in [db['name'] for db in client.get_list_database()]:", "HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1'", "\"\"\" key = 171 self.decrypted = \"\" for i in self.encrypted[4:]: a =", "the TP-Link Smart Home Protocoll: XOR Autokey Cipher with starting key = 171", "error.\\n\", e) pass #################################################################################################### # Continuously take data #################################################################################################### try: while True: try:", "InfluxDB database, default: root INFLUX_PASSWD password to access the InfluxDB database, default: <PASSWORD>", "'energy_total': decrypt_dict['emeter']['get_realtime']['total_wh']/1000, # kWh 'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned", "171 result = pack('>I', len(string)) for i in string: a = key ^", "None, 'power': None, 'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\" Poll the", "and format the data to be sent to InfluxDB. \"\"\" from datetime import", "\"\"\" from struct import pack key = 171 result = pack('>I', len(string)) for", "key = a result += bytes([a]) return result def decrypt(self): \"\"\" Decrypt the", "'power': None, 'energy_total': None, 'error_code': 9999 } def poll(self): \"\"\" Poll the HS110", "= os.getenv('INFLUX_PASSWD') or '<PASSWORD>' INFLUX_DB = os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or", "sock_tcp.connect((self.ip, self.port)) sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect", "Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to database", "iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to database failed due", "= os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT", "= json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power':", "as e: print(datetime.utcnow().isoformat(), \" Encountered unknown error.\\n\", e) pass #################################################################################################### # Continuously take", "SAMPLE_TIME time to wait before getting the next sample, default: 60 \"\"\" ####################################################################################################", "connect to InfluxDB, default: 8086 INFLUX_USER user to access the InfluxDB database, default:", "write the measurements to, default: HS110 SAMPLE_TIME time to wait before getting the", "the data to be sent to InfluxDB. \"\"\" from datetime import datetime self.polltime", "from my homeclimate code. \"\"\" from datetime import datetime try: iresponse = client.write_points(data)", "Smart Home Protocoll: XOR Autokey Cipher with starting key = 171 This follows:", "defined HS110_IP = os.getenv('HS110_IP') HS110_PORT = int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or", "\"\"\" Writes a given data record to the database and prints unexpected results.", "self.decrypt() decrypt_dict = json.loads(self.decrypted) self.data = {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, #", "i in string: a = key ^ ord(i) key = a result +=", "print(\"Sending data to database failed. Response: \", iresponse) except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(),", "= int(os.getenv('HS110_PORT') or 9999) INFLUX_IP = os.getenv('INFLUX_IP') or '127.0.0.1' INFLUX_PORT = int(os.getenv('INFLUX_PORT') or", "result = pack('>I', len(string)) for i in string: a = key ^ ord(i)", "get_raw(self): \"\"\" connect to HS110, send payload and receive power data \"\"\" import", "datetime try: iresponse = client.write_points(data) if not iresponse: print(\"Sending data to database failed.", "database, default: <PASSWORD> INFLUX_DB Database to write the measurements to, default: HS110 SAMPLE_TIME", "poll(self): \"\"\" Poll the HS110 and format the data to be sent to", "if not INFLUX_DB in [db['name'] for db in client.get_list_database()]: client.create_database(INFLUX_DB) # select current", "InfluxDB. \"\"\" from datetime import datetime self.polltime = datetime.utcnow().isoformat() try: self.get_raw() self.decrypt_power() except", "sock_tcp.settimeout(None) sock_tcp.send(self.encrypt('{\"emeter\":{\"get_realtime\":{}}}')) self.encrypted = sock_tcp.recv(2048) sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110", "to database failed due to timeout.\\n\", e) pass except Exception as e: print(datetime.utcnow().isoformat(),", "variables, set some defaults if env vars are not defined HS110_IP = os.getenv('HS110_IP')", "sock_tcp.close() except: raise ConnectionError(\"Could not connect to HS110 at IP \"+str(self.ip)+\" on port", "'error_code': decrypt_dict['emeter']['get_realtime']['err_code'] } except: raise TypeError(\"Could not decrypt returned data.\") def error_data(self): \"\"\"", "= os.getenv('INFLUX_DB') or 'HS110' SAMPLE_TIME = int(os.getenv('SAMPLE_TIME') or 60) #################################################################################################### # helper functions", "https://github.com/softScheck/tplink-smartplug \"\"\" from struct import pack key = 171 result = pack('>I', len(string))", "except TypeError: print(polltime, \" Error decrypting data\") self.error_data except Exception: print(polltime, \" Unknown", "except inexc.InfluxDBServerError as e: print(datetime.utcnow().isoformat(), \" Sending data to database failed due to", "database client.switch_database(INFLUX_DB) #################################################################################################### # Send data to influxdb #################################################################################################### def write_database(client, data): \"\"\"", "= {'voltage': decrypt_dict['emeter']['get_realtime']['voltage_mv']/1000, # V 'current': decrypt_dict['emeter']['get_realtime']['current_ma']/1000, # A 'power': decrypt_dict['emeter']['get_realtime']['power_mw']/1000, # W" ]
[ "import MiddlewareMixin from django.utils import translation from django.conf import settings from .models import", "site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE !=", "country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE", "# For use by js frontend if local != country_code: response.set_cookie(\"local\", country_code) request.session[\"local\"]", "if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE", "False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def", "= request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request,", "sets `country` attribute to request object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request)", "request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use by js frontend if local", "on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if", "InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to request object. \"\"\" def process_request(self,", "Set language based on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language", "based on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language", ".models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to request", "request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response):", "wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language)", "def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For", "process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language based on country site if", "request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local =", "\"\"\" Middleware that sets `country` attribute to request object. \"\"\" def process_request(self, request):", "request object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language based", "For use by js frontend if local != country_code: response.set_cookie(\"local\", country_code) request.session[\"local\"] =", "CountrySite.objects.get_current(request) # Set language based on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\",", "`country` attribute to request object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) #", "import translation from django.conf import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\"", "from django.utils.deprecation import MiddlewareMixin from django.utils import translation from django.conf import settings from", "if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language:", "default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\")", "\"\") country_code = request.country_site.country_code # For use by js frontend if local !=", "import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to request object.", "django.conf import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets", "django.utils import translation from django.conf import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin):", "MiddlewareMixin from django.utils import translation from django.conf import settings from .models import CountrySite", "if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local", "request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code =", "Middleware that sets `country` attribute to request object. \"\"\" def process_request(self, request): request.country_site", "translation from django.conf import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware", "to request object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language", "translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code", "!= default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\",", "import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country`", "<reponame>project-cece/django-international-sites<filename>international/middleware.py<gh_stars>1-10 from django.utils.deprecation import MiddlewareMixin from django.utils import translation from django.conf import settings", "object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language based on", "\"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language based on country", "# Set language based on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)):", "request, response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use by", "response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use by js", "attribute to request object. \"\"\" def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set", "request.country_site.country_code # For use by js frontend if local != country_code: response.set_cookie(\"local\", country_code)", "js frontend if local != country_code: response.set_cookie(\"local\", country_code) request.session[\"local\"] = country_code return response", "use by js frontend if local != country_code: response.set_cookie(\"local\", country_code) request.session[\"local\"] = country_code", "from django.conf import settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that", "from django.utils import translation from django.conf import settings from .models import CountrySite class", "process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use", "django.utils.deprecation import MiddlewareMixin from django.utils import translation from django.conf import settings from .models", "= translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code", "settings from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute", "by js frontend if local != country_code: response.set_cookie(\"local\", country_code) request.session[\"local\"] = country_code return", "translation.get_language() def process_response(self, request, response): local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code #", "= request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use by js frontend if", "local = request.COOKIES.get(\"local\", \"\") country_code = request.country_site.country_code # For use by js frontend", "= CountrySite.objects.get_current(request) # Set language based on country site if wanted if (getattr(settings,", "\"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language()", "class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to request object. \"\"\" def", "CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to request object. \"\"\"", "that sets `country` attribute to request object. \"\"\" def process_request(self, request): request.country_site =", "def process_request(self, request): request.country_site = CountrySite.objects.get_current(request) # Set language based on country site", "= request.country_site.country_code # For use by js frontend if local != country_code: response.set_cookie(\"local\",", "request): request.country_site = CountrySite.objects.get_current(request) # Set language based on country site if wanted", "language based on country site if wanted if (getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language =", "(getattr(settings, \"FORCE_COUNTRY_LANGUAGE\", False)): default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE =", "request.country_site = CountrySite.objects.get_current(request) # Set language based on country site if wanted if", "country_code = request.country_site.country_code # For use by js frontend if local != country_code:", "default_language = request.country_site.default_language if request.LANGUAGE_CODE != default_language: translation.activate(default_language) request.LANGUAGE_CODE = translation.get_language() def process_response(self,", "from .models import CountrySite class InternationalSiteMiddleware(MiddlewareMixin): \"\"\" Middleware that sets `country` attribute to" ]
[ "coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from", "Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME =", "from exoskeleton import _version NAME = \"exoskeleton\" __version__ = _version.__version__ __author__ = \"<NAME>\"", "#!/usr/bin/env python3 # -*- coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from", "import Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\" __version__ = _version.__version__ __author__", "from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\" __version__ =", "\"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version", "for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\"", "Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\" __version__", "-*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import", "utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton", "<reponame>RuedigerVoigt/exoskeleton #!/usr/bin/env python3 # -*- coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\"", "# -*- coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import", "exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\" __version__ = _version.__version__", "Exoskeleton from exoskeleton import _version NAME = \"exoskeleton\" __version__ = _version.__version__ __author__ =", "-*- coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton", "python3 # -*- coding: utf-8 -*- \"Exoskeleton Crawler Framwork for Python\" from exoskeleton.__main__", "Crawler Framwork for Python\" from exoskeleton.__main__ import Exoskeleton from exoskeleton import _version NAME" ]
[]
[ ":: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System", "\"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\",", "setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages,", "MIT License\", \"Operating System :: OS Independent\", ], install_requires=[ 'pylint>=2.4.2', 'twine>=3.1.1' ], python_requires='>=3.6'", "include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__,", "from setuptools import setup, find_packages import logger as pkg packages = find_packages( where='.',", "import logger as pkg packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\")", "description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language", "classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved :: MIT", "packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description =", "fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License',", "license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI", "find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup(", "long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python", "name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[", "as pkg packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh:", "Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System ::", "url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python :: 3\",", "packages=packages, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved ::", "OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], install_requires=[ 'pylint>=2.4.2',", ":: 3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS", "<gh_stars>0 from setuptools import setup, find_packages import logger as pkg packages = find_packages(", ") with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger", "= fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT", "3\", \"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\",", "library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language ::", "License', packages=packages, classifiers=[ \"Programming Language :: Python :: 3\", \"License :: OSI Approved", "fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>',", "author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python :: 3\", \"License", "setuptools import setup, find_packages import logger as pkg packages = find_packages( where='.', include=['logger*']", "as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\",", "pkg packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description", "\"License :: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ],", "author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python :: 3\", \"License ::", "setup, find_packages import logger as pkg packages = find_packages( where='.', include=['logger*'] ) with", "find_packages import logger as pkg packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\",", "Approved :: MIT License\", \"Operating System :: OS Independent\", ], install_requires=[ 'pylint>=2.4.2', 'twine>=3.1.1'", ":: OSI Approved :: MIT License\", \"Operating System :: OS Independent\", ], install_requires=[", ":: MIT License\", \"Operating System :: OS Independent\", ], install_requires=[ 'pylint>=2.4.2', 'twine>=3.1.1' ],", "License\", \"Operating System :: OS Independent\", ], install_requires=[ 'pylint>=2.4.2', 'twine>=3.1.1' ], python_requires='>=3.6' )", "logger as pkg packages = find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as", "version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming", "with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library',", "long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>',", "where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name='pyclay_logger',", "import setup, find_packages import logger as pkg packages = find_packages( where='.', include=['logger*'] )", "Language :: Python :: 3\", \"License :: OSI Approved :: MIT License\", \"Operating", "= find_packages( where='.', include=['logger*'] ) with open(\"README.md\", \"r\") as fh: long_description = fh.read()", "\"r\") as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description, long_description_content_type=\"text/markdown\",", "open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name='pyclay_logger', version=pkg.__version__, description='logger library', long_description=long_description,", "long_description_content_type=\"text/markdown\", url=\"https://github.com/cm107/logger\", author='<NAME>', author_email='<EMAIL>', license='MIT License', packages=packages, classifiers=[ \"Programming Language :: Python ::" ]
[ "if ant: words.append(ant) i += 2 continue words.append(word) i += 1 return words", "and i + 1 < len_sent: ant = self.replace(sent[i + 1]) if ant:", "= sent[i] if word == 'not' and i + 1 < len_sent: ant", "sent = word_tokenize(string) len_sent = len(sent) words = [] while i < len_sent:", "< len_sent: ant = self.replace(sent[i + 1]) if ant: words.append(ant) i += 2", "wordnet from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word): ant = list()", "return ant[0] else: return None def negreplace(self, string): i = 0 sent =", "word_tokenize class AntonymReplacer(object): def replace(self, word): ant = list() for syn in wordnet.synsets(word):", "= 0 sent = word_tokenize(string) len_sent = len(sent) words = [] while i", "i < len_sent: word = sent[i] if word == 'not' and i +", "len_sent: ant = self.replace(sent[i + 1]) if ant: words.append(ant) i += 2 continue", "from nltk.corpus import wordnet from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word):", "word = sent[i] if word == 'not' and i + 1 < len_sent:", "lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else: return None def negreplace(self,", "= word_tokenize(string) len_sent = len(sent) words = [] while i < len_sent: word", "word == 'not' and i + 1 < len_sent: ant = self.replace(sent[i +", "+ 1]) if ant: words.append(ant) i += 2 continue words.append(word) i += 1", "0 sent = word_tokenize(string) len_sent = len(sent) words = [] while i <", "while i < len_sent: word = sent[i] if word == 'not' and i", ">= 1: return ant[0] else: return None def negreplace(self, string): i = 0", "lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else:", "string): i = 0 sent = word_tokenize(string) len_sent = len(sent) words = []", "nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word): ant = list() for syn", "'not' and i + 1 < len_sent: ant = self.replace(sent[i + 1]) if", "+ 1 < len_sent: ant = self.replace(sent[i + 1]) if ant: words.append(ant) i", "= self.replace(sent[i + 1]) if ant: words.append(ant) i += 2 continue words.append(word) i", "if len(ant) >= 1: return ant[0] else: return None def negreplace(self, string): i", "len(ant) >= 1: return ant[0] else: return None def negreplace(self, string): i =", "in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1:", "self.replace(sent[i + 1]) if ant: words.append(ant) i += 2 continue words.append(word) i +=", "< len_sent: word = sent[i] if word == 'not' and i + 1", "ant[0] else: return None def negreplace(self, string): i = 0 sent = word_tokenize(string)", "ant = self.replace(sent[i + 1]) if ant: words.append(ant) i += 2 continue words.append(word)", "word_tokenize(string) len_sent = len(sent) words = [] while i < len_sent: word =", "<reponame>aravindvnair99/Natural-Language-Processing-Project from nltk.corpus import wordnet from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self,", "def replace(self, word): ant = list() for syn in wordnet.synsets(word): for lemma in", "syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else: return None", "if word == 'not' and i + 1 < len_sent: ant = self.replace(sent[i", "for syn in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant)", "= list() for syn in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name())", "import wordnet from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word): ant =", "AntonymReplacer(object): def replace(self, word): ant = list() for syn in wordnet.synsets(word): for lemma", "nltk.corpus import wordnet from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word): ant", "len_sent = len(sent) words = [] while i < len_sent: word = sent[i]", "== 'not' and i + 1 < len_sent: ant = self.replace(sent[i + 1])", "class AntonymReplacer(object): def replace(self, word): ant = list() for syn in wordnet.synsets(word): for", "import word_tokenize class AntonymReplacer(object): def replace(self, word): ant = list() for syn in", "list() for syn in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if", "1: return ant[0] else: return None def negreplace(self, string): i = 0 sent", "for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0]", "= len(sent) words = [] while i < len_sent: word = sent[i] if", "words = [] while i < len_sent: word = sent[i] if word ==", "sent[i] if word == 'not' and i + 1 < len_sent: ant =", "1]) if ant: words.append(ant) i += 2 continue words.append(word) i += 1 return", "word): ant = list() for syn in wordnet.synsets(word): for lemma in syn.lemmas(): if", "ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else: return None def negreplace(self, string):", "replace(self, word): ant = list() for syn in wordnet.synsets(word): for lemma in syn.lemmas():", "1 < len_sent: ant = self.replace(sent[i + 1]) if ant: words.append(ant) i +=", "i + 1 < len_sent: ant = self.replace(sent[i + 1]) if ant: words.append(ant)", "wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return", "def negreplace(self, string): i = 0 sent = word_tokenize(string) len_sent = len(sent) words", "[] while i < len_sent: word = sent[i] if word == 'not' and", "len_sent: word = sent[i] if word == 'not' and i + 1 <", "len(sent) words = [] while i < len_sent: word = sent[i] if word", "syn in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >=", "ant = list() for syn in wordnet.synsets(word): for lemma in syn.lemmas(): if lemma.antonyms():", "= [] while i < len_sent: word = sent[i] if word == 'not'", "if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else: return None def", "else: return None def negreplace(self, string): i = 0 sent = word_tokenize(string) len_sent", "negreplace(self, string): i = 0 sent = word_tokenize(string) len_sent = len(sent) words =", "i = 0 sent = word_tokenize(string) len_sent = len(sent) words = [] while", "from nltk.tokenize import word_tokenize class AntonymReplacer(object): def replace(self, word): ant = list() for", "return None def negreplace(self, string): i = 0 sent = word_tokenize(string) len_sent =", "in syn.lemmas(): if lemma.antonyms(): ant.append(lemma.antonyms()[0].name()) if len(ant) >= 1: return ant[0] else: return", "None def negreplace(self, string): i = 0 sent = word_tokenize(string) len_sent = len(sent)" ]
[ "assert response.status_code == 200 data = response.get_data(as_text=True) assert data if rf_format == 'json':", "notes of a basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name)", "= bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response = client.head(url) assert", "return { 'Authorization': 'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept':", "data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert 'latest_version' in basis_set", "'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\" response =", "import current_app import pytest import json from base64 import b64encode import basis_set_exchange as", "= self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code == 200", "'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json'", "the APIs by connecting to the flask app from a client. \"\"\" @classmethod", "= client.get(self.api_url + 'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data)", "client.get(self.api_url + 'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) ==", "response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys())", "dict # get the basis data of any basis set basis_set_name = list(data.keys())[0]", "current_app import pytest import json from base64 import b64encode import basis_set_exchange as bse", "data if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple", "dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\"", "response.status_code == 200 data = response.get_data(as_text=True) assert output in data if bs_format ==", "bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\"", "response.get_data(as_text=True) assert data if rf_format == 'json': assert json.loads(data) # without elements response", "assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g'", "\"client\", autouse=True) # to use fixtures from conftest class TestAPIs(object): \"\"\" Testing the", "assert output in data if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client):", "response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set", "use fixtures from conftest class TestAPIs(object): \"\"\" Testing the APIs by connecting to", "\"\"\"Get notes of a basis set\"\"\" bs_name = '3-21g' url = self.api_url +", "= client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data)", "self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name',", "set\"\"\" bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url)", "200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] == 'BibTeX' def", "type(data) == dict # get the basis data of any basis set basis_set_name", "= response.get_data(as_text=True) assert output in data if bs_format == 'json': assert json.loads(data) def", "notes\"\"\" ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response =", "= data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert 'latest_version' in", "set family notes\"\"\" ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type)", "== 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name", "by connecting to the flask app from a client. \"\"\" @classmethod def setup_class(cls):", "# to use fixtures from conftest class TestAPIs(object): \"\"\" Testing the APIs by", "formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data =", "+ password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the supported", "test_get_references(self, rf_format, client): \"\"\"Get references for a basis set with different formats\"\"\" bs_name", "200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the basis data", "200 def test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\" bs_name = '3-21g'", "bs_format = 'gaussian94' params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response", "from flask import current_app import pytest import json from base64 import b64encode import", "data = json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the basis data of", "]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis set\"\"\" bs_name =", "'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client):", "':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the", "dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert", "+ 'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict", "== 200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert 'H'", "of the basis sets \"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code ==", "\"\"\"Get the supported references formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code", "'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type',", "not None def get_api_headers(self, username, password): return { 'Authorization': 'Basic ' + b64encode(", "get_api_headers(self, username, password): return { 'Authorization': 'Basic ' + b64encode( (username + ':'", "url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200 assert", "import b64encode import basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return", "200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get", "'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\" url = self.api_url", "the flask app from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/'", "fixtures from conftest class TestAPIs(object): \"\"\" Testing the APIs by connecting to the", "of any basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in", "def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\" url = self.api_url +", "(username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client):", "basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in", "'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for a", "client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name,", "references for a basis set with different formats\"\"\" bs_name = '3-21g' params =", "= 'gaussian94' params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response =", "in basis_set assert 'display_name' in basis_set assert 'family' in basis_set assert 'role' in", "cls.template_url = '/' def test_app_exists(self): assert current_app is not None def get_api_headers(self, username,", "@pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for a basis set with", "in basis_set assert 'functiontypes' in basis_set assert 'latest_version' in basis_set assert 'display_name' in", "self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code == 200", "assert json.loads(data) # without elements response = client.get(url) assert response.status_code == 200 def", "('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis", "set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a", "client): \"\"\"Get references for a basis set with different formats\"\"\" bs_name = '3-21g'", "a simple basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format)", "client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' url = self.api_url +", "= '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code", "set with different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url = self.api_url", "response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type,", "basis set with different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url =", "response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis", "a basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response =", "test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\" response = client.get(self.api_url + 'reference_formats/')", "+ 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople',", "assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis", "\"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params =", "type(data) == dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the", "and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for", "response.get_data(as_text=True) assert output in data if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self,", "== 200 data = response.get_data(as_text=True) assert output in data if bs_format == 'json':", "client): \"\"\"Get the supported references formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert", "client.get(url) assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes of a basis", "assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\"", "basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"')", "= json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the basis data of any", "+ ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get", "to use fixtures from conftest class TestAPIs(object): \"\"\" Testing the APIs by connecting", "sets \"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code == 200 data =", "3-21G' in data assert 'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats())", "client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self):", "APIs by connecting to the flask app from a client. \"\"\" @classmethod def", "'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert 'latest_version' in basis_set assert 'display_name'", "base64 import b64encode import basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def get_ref_formats():", "basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert", "assert response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in data", "'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def", "the supported references formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code ==", "def test_get_references(self, rf_format, client): \"\"\"Get references for a basis set with different formats\"\"\"", "client): \"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code", "== 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] == 'GAMESS", "connecting to the flask app from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url", "archive_type, client): \"\"\"Get basis set family notes\"\"\" ver = bse.version() url = self.api_url", "'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code == 200 data =", "response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert data", "in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from conftest class TestAPIs(object):", "client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert data if rf_format", "response = client.get(self.api_url + 'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert", "'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True) assert", "from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/'", "bs_name = '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url = self.api_url +", "@pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\" ver", "type(data) == dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs", "= '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code ==", "= client.get(url) assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes of a", "conftest class TestAPIs(object): \"\"\" Testing the APIs by connecting to the flask app", "'latest_version' in basis_set assert 'display_name' in basis_set assert 'family' in basis_set assert 'role'", "test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name)", "= client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True) assert output in data", "assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported references formats", "\"\"\" Testing the APIs by connecting to the flask app from a client.", "basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url =", "basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response =", "== 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\" response", "data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] == 'GAMESS US' def", "data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for a basis set", "query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert data if rf_format ==", "basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert 'latest_version'", "assert 'functiontypes' in basis_set assert 'latest_version' in basis_set assert 'display_name' in basis_set assert", "basis_set assert 'display_name' in basis_set assert 'family' in basis_set assert 'role' in basis_set", "= self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code == 200 data", "\"\"\"Get basis set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url)", "client): \"\"\"Get basis set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response =", "# without elements response = client.get(url) assert response.status_code == 200 def test_get_notes(self, client):", "self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format',", "basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format", "of a basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response", "= self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code ==", "200 data = response.get_data(as_text=True) assert data if rf_format == 'json': assert json.loads(data) #", "client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True) assert output in data if", "in basis_set assert 'latest_version' in basis_set assert 'display_name' in basis_set assert 'family' in", "== dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata", "US' def test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\" response = client.get(self.api_url", "b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self,", "bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\" ver = bse.version() url =", "response = client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert", "assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family", "\"\"\"Get references for a basis set with different formats\"\"\" bs_name = '3-21g' params", "bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response = client.head(url) assert response.status_code", "+ 'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict", "' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' }", "response.status_code == 200 data = response.get_data(as_text=True) assert data if rf_format == 'json': assert", "json.loads(data) # without elements response = client.get(url) assert response.status_code == 200 def test_get_notes(self,", "json from base64 import b64encode import basis_set_exchange as bse headers = {'Content-Type': 'application/json'}", "+ 'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict", "@pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from conftest class TestAPIs(object): \"\"\" Testing", "simple basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url", "} def test_get_formats(self, client): \"\"\"Get the supported formats of the basis sets \"\"\"", "= json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client):", "assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict # get", "data = response.get_data(as_text=True) assert output in data if bs_format == 'json': assert json.loads(data)", "= client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis set:", "self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code == 200 data =", "without elements response = client.get(url) assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get", "'gaussian94' params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url,", "response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def", "rf_format, client): \"\"\"Get references for a basis set with different formats\"\"\" bs_name =", "family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code ==", "bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\" ver =", "app from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url =", "setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self): assert current_app is not", "@classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self): assert current_app", "format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from conftest class", "assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert 'latest_version' in basis_set assert", "def get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to", "bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code", "get the basis data of any basis set basis_set_name = list(data.keys())[0] basis_set =", "as bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format in", "to the flask app from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url =", "if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis", "params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params)", "response = client.get(url) assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes of", "json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the basis data of any basis", "family notes\"\"\" ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response", "+ 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code == 200 data", "assert 'display_name' in basis_set assert 'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[", "a basis set with different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url", "= '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name,", "json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client):", "metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code == 200 data =", "= '/' def test_app_exists(self): assert current_app is not None def get_api_headers(self, username, password):", "import json from base64 import b64encode import basis_set_exchange as bse headers = {'Content-Type':", "'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the supported formats of the basis", "'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert", "client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self,", "b64encode import basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format)", "assert 'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format,", "client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) ==", "test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\" ver = bse.version() url", "basis sets \"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code == 200 data", "200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert 'H' in", "url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code ==", "== 200 def test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\" bs_name =", "password): return { 'Authorization': 'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'),", "def test_get_formats(self, client): \"\"\"Get the supported formats of the basis sets \"\"\" response", "data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references", "response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert", "\"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True))", "response = client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True) assert output in", "'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json',", "client): \"\"\"Get basis set family notes\"\"\" ver = bse.version() url = self.api_url +", "== 'json': assert json.loads(data) # without elements response = client.get(url) assert response.status_code ==", "the bs metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code == 200", "response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert 'H' in data and 'Li'", "different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name,", "== 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url", "list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set assert", "'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url +", "\"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis set\"\"\" bs_name", "'functiontypes' in basis_set assert 'latest_version' in basis_set assert 'display_name' in basis_set assert 'family'", "a client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def", "rf_format == 'json': assert json.loads(data) # without elements response = client.get(url) assert response.status_code", "def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url + 'metadata/')", "assert 'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'),", "'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the supported formats of the", "self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code == 200 data", "client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params", "'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the supported formats of", "= '3-21g' params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response", "bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\"", "elements response = client.get(url) assert response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes", "the supported formats of the basis sets \"\"\" response = client.get(self.api_url + 'formats/')", "basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format,", "'3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format)", "= response.get_data(as_text=True) assert data if rf_format == 'json': assert json.loads(data) # without elements", "flask import current_app import pytest import json from base64 import b64encode import basis_set_exchange", "+ 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys())", "client.get(self.api_url + 'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) ==", "basis_set assert 'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set:", "json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get", "@pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output,", "dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code", "# get the basis data of any basis set basis_set_name = list(data.keys())[0] basis_set", "data assert 'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self,", "basis set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert", "'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict #", "3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple", "family_name, client): \"\"\"Get basis set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response", "== 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis", "= dict(elements='1,3') url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert", "set family notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code", "data of any basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries'", "response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\"", "'Authorization': 'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type':", "return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures", "def get_api_headers(self, username, password): return { 'Authorization': 'Basic ' + b64encode( (username +", "assert data if rf_format == 'json': assert json.loads(data) # without elements response =", "if rf_format == 'json': assert json.loads(data) # without elements response = client.get(url) assert", "def test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\" bs_name = '3-21g' url", "client): \"\"\"Get the supported formats of the basis sets \"\"\" response = client.get(self.api_url", "pytest import json from base64 import b64encode import basis_set_exchange as bse headers =", "assert type(data) == dict assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the", "any basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set", "data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\"", "formats of the basis sets \"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code", "'3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code ==", "'application/json'} def get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) #", "'Basis set: 3-21G' in data assert 'H' in data and 'Li' in data", "def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family notes\"\"\" ver = bse.version()", "= self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response = client.head(url) assert response.status_code == 200", "basis data of any basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert", "'/api/' cls.template_url = '/' def test_app_exists(self): assert current_app is not None def get_api_headers(self,", "current_app is not None def get_api_headers(self, username, password): return { 'Authorization': 'Basic '", "flask app from a client. \"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url", "= client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert data if", "+ 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True)", "response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get", "bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert", "assert data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response", "None def get_api_headers(self, username, password): return { 'Authorization': 'Basic ' + b64encode( (username", "import basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for", "in basis_set assert 'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis", "in data assert 'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def", "= list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes' in basis_set", "== 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client):", "notes\"\"\" url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200", "data if rf_format == 'json': assert json.loads(data) # without elements response = client.get(url)", "test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert", "headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\",", "200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set", "'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True)", "\"\"\"Get the bs metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code ==", "import pytest import json from base64 import b64encode import basis_set_exchange as bse headers", "url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url) assert response.status_code == 200", "assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client):", "{'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True)", "== 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the basis", "in data if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a", "\"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True))", "= response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert 'H' in data and", "'display_name' in basis_set assert 'family' in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94',", "def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' bs_format =", "\"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True))", "'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get", "client): \"\"\"Get notes of a basis set\"\"\" bs_name = '3-21g' url = self.api_url", "200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] == 'GAMESS US'", "'reference_formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert", "'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto'])", "client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G'", "from conftest class TestAPIs(object): \"\"\" Testing the APIs by connecting to the flask", "in data and 'Li' in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get", "response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict # get the", "\"\"\" @classmethod def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self): assert", "= {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\",", "'3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200", "test_app_exists(self): assert current_app is not None def get_api_headers(self, username, password): return { 'Authorization':", "in basis_set assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\":", "\"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name,", "the basis sets \"\"\" response = client.get(self.api_url + 'formats/') assert response.status_code == 200", "basis set family notes\"\"\" ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format,", "== 200 data = response.get_data(as_text=True) assert data if rf_format == 'json': assert json.loads(data)", "cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self): assert current_app is not None", "assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us']", "for a basis set with different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3')", "data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in data assert 'H' in data", "'application/json' } def test_get_formats(self, client): \"\"\"Get the supported formats of the basis sets", "\"\"\"Get the supported formats of the basis sets \"\"\" response = client.get(self.api_url +", "in data @pytest.mark.parametrize('rf_format', get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for a basis", "with different formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url = self.api_url +", "TestAPIs(object): \"\"\" Testing the APIs by connecting to the flask app from a", "def test_get_references_formats(self, client): \"\"\"Get the supported references formats \"\"\" response = client.get(self.api_url +", "assert response.status_code == 200 data = response.get_data(as_text=True) assert output in data if bs_format", "= client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self,", "test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94'", "@pytest.mark.parametrize('family_name', ['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\" url", "in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self,", "query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert 'Basis set: 3-21G' in", "formats\"\"\" bs_name = '3-21g' params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format)", "= client.get(self.api_url + 'metadata/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data)", "assert 'Basis set: 3-21G' in data assert 'H' in data and 'Li' in", "json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' bs_format", "references formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code == 200 data", "data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] == 'BibTeX' def test_get_metadata(self,", "\"\"\"Get basis set family notes\"\"\" ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver,", "response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] ==", "basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url)", "assert 'role' in basis_set @pytest.mark.parametrize('bs_format,output',[ ('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ])", "response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] ==", "print(url) response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert", "bs_format) response = client.get(url) assert response.status_code == 200 data = response.get_data(as_text=True) assert output", "assert current_app is not None def get_api_headers(self, username, password): return { 'Authorization': 'Basic", "response.status_code == 200 def test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\" bs_name", "'/' def test_app_exists(self): assert current_app is not None def get_api_headers(self, username, password): return", "+ b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def", "'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get a simple basis set\"\"\" bs_name =", "= self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True)", "autouse=True) # to use fixtures from conftest class TestAPIs(object): \"\"\" Testing the APIs", "test_get_notes(self, client): \"\"\"Get notes of a basis set\"\"\" bs_name = '3-21g' url =", "url = self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200 assert", "@pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format, archive_type, client): \"\"\"Get basis set family", "test_get_formats(self, client): \"\"\"Get the supported formats of the basis sets \"\"\" response =", "def setup_class(cls): cls.api_url = '/api/' cls.template_url = '/' def test_app_exists(self): assert current_app is", "bs metadata \"\"\" response = client.get(self.api_url + 'metadata/') assert response.status_code == 200 data", "response = client.get(self.api_url + 'formats/') assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert", "params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url,", "set\"\"\" bs_name = '3-21g' url = self.api_url + 'notes/{}/'.format(bs_name) response = client.get(url) assert", "is not None def get_api_headers(self, username, password): return { 'Authorization': 'Basic ' +", "basis_set assert 'latest_version' in basis_set assert 'display_name' in basis_set assert 'family' in basis_set", "= '/api/' cls.template_url = '/' def test_app_exists(self): assert current_app is not None def", "['pople', 'sto']) def test_bs_family_notes(self, family_name, client): \"\"\"Get basis set family notes\"\"\" url =", "assert type(data) == dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get", "def test_app_exists(self): assert current_app is not None def get_api_headers(self, username, password): return {", "username, password): return { 'Authorization': 'Basic ' + b64encode( (username + ':' +", "{ 'Authorization': 'Basic ' + b64encode( (username + ':' + password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json',", "supported formats of the basis sets \"\"\" response = client.get(self.api_url + 'formats/') assert", "assert response.status_code == 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib']", "= json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self,", "basis_set assert 'functiontypes' in basis_set assert 'latest_version' in basis_set assert 'display_name' in basis_set", "('gaussian94', 'Basis set: 3-21G'), ('json', '\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client):", "output, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' url = self.api_url", "set: 3-21G' in data assert 'H' in data and 'Li' in data @pytest.mark.parametrize('rf_format',", "bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from conftest class TestAPIs(object): \"\"\"", "data = response.get_data(as_text=True) assert data if rf_format == 'json': assert json.loads(data) # without", "'json': assert json.loads(data) # without elements response = client.get(url) assert response.status_code == 200", "Testing the APIs by connecting to the flask app from a client. \"\"\"", "'3-21g' params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response =", "[(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from", "'\"name\": \"3-21G\"') ]) def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis set\"\"\"", "rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True)", "url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params) assert response.status_code", "url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response = client.head(url) assert response.status_code ==", "for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use fixtures from conftest", "data['bib'] == 'BibTeX' def test_get_metadata(self, client): \"\"\"Get the bs metadata \"\"\" response =", "get_ref_formats()) def test_get_references(self, rf_format, client): \"\"\"Get references for a basis set with different", "simple basis set\"\"\" bs_name = '3-21g' url = self.api_url + 'basis/{}/format/{}/'.format(bs_name, bs_format) response", "200 data = response.get_data(as_text=True) assert output in data if bs_format == 'json': assert", "class TestAPIs(object): \"\"\" Testing the APIs by connecting to the flask app from", "password).encode('utf-8')).decode('utf-8'), 'Accept': 'application/json', 'Content-Type': 'application/json' } def test_get_formats(self, client): \"\"\"Get the supported formats", "== 200 data = json.loads(response.get_data(as_text=True)) assert type(data) == dict assert data['bib'] == 'BibTeX'", "the basis data of any basis set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name]", "output in data if bs_format == 'json': assert json.loads(data) def test_get_basis_elements(self, client): \"\"\"Get", "test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' url", "dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported references", "supported references formats \"\"\" response = client.get(self.api_url + 'reference_formats/') assert response.status_code == 200", "def test_get_simple_basis(self, bs_format, output, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g'", "bse headers = {'Content-Type': 'application/json'} def get_ref_formats(): return [(format) for format in bse.get_reference_formats()]", "assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def test_download(self, bs_format,", "set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3') url = self.api_url", "assert 'latest_version' in basis_set assert 'display_name' in basis_set assert 'family' in basis_set assert", "set basis_set_name = list(data.keys())[0] basis_set = data[basis_set_name] assert 'auxiliaries' in basis_set assert 'functiontypes'", "from base64 import b64encode import basis_set_exchange as bse headers = {'Content-Type': 'application/json'} def", "ver = bse.version() url = self.api_url + 'download/{}/{}/{}'.format(ver, bs_format, archive_type) response = client.head(url)", "== dict assert data['gamess_us'] == 'GAMESS US' def test_get_references_formats(self, client): \"\"\"Get the supported", "bs_name = '3-21g' params = dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url)", "= self.api_url + 'family_notes/{}/'.format(family_name) response = client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True)", "bs_format) response = client.get(url, query_string=params) assert response.status_code == 200 data = response.get_data(as_text=True) assert", "bs_format, output, client): \"\"\"Get a simple basis set\"\"\" bs_name = '3-21g' url =", "== dict # get the basis data of any basis set basis_set_name =", "= client.get(url) assert response.status_code == 200 assert response.get_data(as_text=True) @pytest.mark.parametrize('bs_format', bse.get_formats().keys()) @pytest.mark.parametrize('archive_type', bse.get_archive_types().keys()) def", "assert type(data) == dict # get the basis data of any basis set", "a simple basis set\"\"\" bs_name = '3-21g' bs_format = 'gaussian94' params = dict(elements='1,3')", "= dict(elements='1,3') url = self.api_url + 'references/{}/format/{}/'.format(bs_name, rf_format) print(url) response = client.get(url, query_string=params)", "+ 'basis/{}/format/{}/'.format(bs_name, bs_format) response = client.get(url, query_string=params) assert response.status_code == 200 data =", "get_ref_formats(): return [(format) for format in bse.get_reference_formats()] @pytest.mark.usefixtures(\"app\", \"client\", autouse=True) # to use" ]
[ "'0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request return(request) if request.method=='GET':", "\"\" def gen(): global geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield", "requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if", "data(): global data if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if __name__ ==", "def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def", "global geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n'", "vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video():", "geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')", "Response, request from video import Video import requests app = Flask(__name__) vid=Video(0) geste", "geste = \"\" data = \"\" def gen(): global geste while True: frame,", "video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main", "return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\",", "gen(): global geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type:", "vid=Video(0) geste = \"\" data = \"\" def gen(): global geste while True:", "render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r =", "= vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def", "flask import Flask, render_template, Response, request from video import Video import requests app", "r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video(): return", "from flask import Flask, render_template, Response, request from video import Video import requests", "geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data():", "yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste", "True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame +", "geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/')", "\"\" data = \"\" def gen(): global geste while True: frame, geste =", "@app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed')", "= geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace;", "boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\")", "@app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste')", "if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if __name__ == '__main__': app.run(debug=False, port=8080)", "frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')", "data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST':", "Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position':", "@app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST'])", "mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'})", "return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request return(request) if request.method=='GET': return(data)", "def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def", "def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI', data={'geste':", "= requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data", "return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r", "geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' +", "from video import Video import requests app = Flask(__name__) vid=Video(0) geste = \"\"", "Video import requests app = Flask(__name__) vid=Video(0) geste = \"\" data = \"\"", "'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request return(request) if", "import Video import requests app = Flask(__name__) vid=Video(0) geste = \"\" data =", "global data if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if __name__ == '__main__':", "(b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste =", "= Flask(__name__) vid=Video(0) geste = \"\" data = \"\" def gen(): global geste", "render_template, Response, request from video import Video import requests app = Flask(__name__) vid=Video(0)", "render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(),", "frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt():", "import Flask, render_template, Response, request from video import Video import requests app =", "b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html')", "b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste)", "app = Flask(__name__) vid=Video(0) geste = \"\" data = \"\" def gen(): global", "video import Video import requests app = Flask(__name__) vid=Video(0) geste = \"\" data", "def gen(): global geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n'", "while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'}) yield (b'--frame\\r\\n' b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame", "image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay')", "@app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste(): r = requests.post('http://localhost:8090/getAPI',", "@app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if", "request from video import Video import requests app = Flask(__name__) vid=Video(0) geste =", "= \"\" data = \"\" def gen(): global geste while True: frame, geste", "= \"\" def gen(): global geste while True: frame, geste = vid.get_frame() r=requests.post('http://localhost:8090/getAPI',data={'geste':geste,'position':'0123'})", "Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request return(request)", "return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return", "\"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global data if request.method=='POST': data=request", "video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed():", "Flask(__name__) vid=Video(0) geste = \"\" data = \"\" def gen(): global geste while", "requests app = Flask(__name__) vid=Video(0) geste = \"\" data = \"\" def gen():", "data if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if __name__ == '__main__': app.run(debug=False,", "data = \"\" def gen(): global geste while True: frame, geste = vid.get_frame()", "+ b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def ppt(): return", "ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def geste():", "def ppt(): return render_template('pptDisplay.html') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') @app.route('/geste') def", "def data(): global data if request.method=='POST': data=request return(request) if request.method=='GET': return(data) if __name__", "Flask, render_template, Response, request from video import Video import requests app = Flask(__name__)", "r = requests.post('http://localhost:8090/getAPI', data={'geste': \"Main Ouverte\", 'position': '0123'}) return(\"geste\") @app.route('/data',methods=['GET','POST']) def data(): global", "+ frame + b'\\r\\n') @app.route('/') def video(): return render_template('index.html',geste = geste) @app.route('/pptDisplay') def", "import requests app = Flask(__name__) vid=Video(0) geste = \"\" data = \"\" def" ]
[ "return 'FAILED' return '%s %s' % (name.strip(), version.strip()) return { 'info': 'returns relay", "= \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ = ['value', 'events'] __mods_required__ =", "== 1: return int(result) / 100 elif ret == 2: return None if", "import PHI as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from", "analog inputs, t1-8 for temperature inputs. DIN events can be received by SNMP", "__description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ = ['value', 'events'] __mods_required__", "oid = self.oid_temp port_max = 8 port = port[1:] ret = 2 else:", "0: return result elif ret == 1: return int(result) / 100 elif ret", "= self.snmp_port if not community: community = self.community if tries is None: tries", "snmp_port, community, _timeout, tries - 1, rf=int) if ret == 0: return result", "port - 1), host, snmp_port, community, _timeout, tries - 1, rf=int) if ret", "if name and cmd == 'self': return 'OK' if netsnmp: try: version =", "port > port_max: return None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port,", "'str', 'required': False }, { 'name': 'retries', 'help': 'snmp retry attemps (default: 0)',", "cmd == 'module': return 'default' if not netsnmp else 'netsnmp' if cmd ==", "self.snmp_host is None: return 'OK' if cmd == 'info' or cmd == 'self':", "}] __get_help__ = [] __set_help__ = [] __help__ = \"\"\" PHI for Denkovi", "not community: community = self.community if tries is None: tries = self.snmp_tries if", "eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port", "except: log_traceback() name = None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(),", "1) o = netsnmp.VarList('%s.%u' % (oid, port - 1)) result = sess.get(o)[0].decode() except", "\"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\" __version__ = \"2.0.0\"", "netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name =", "1: return int(result) / 100 elif ret == 2: return None if result", "parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries') try: tries = int(tries) +", "= \"Altertech Group, https://www.altertech.com/\" __copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__ =", "if not netsnmp else 'netsnmp' if cmd == 'self' and self.snmp_host is None:", "process_snmp_trap(self, host, data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return", "Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess = None if netsnmp:", "__author__ = \"Altertech Group, https://www.altertech.com/\" __copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__", "= sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port,", "'.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self)", "port[1:] ret = 1 elif port.startswith('t'): oid = self.oid_temp port_max = 8 port", "i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature", "None tries = None if not host: host = self.snmp_host snmp_port = self.snmp_port", "__config_help__ = [{ 'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required': True },", "(oid, port - 1)) result = sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback()", "data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value:", "1 elif port.startswith('t'): oid = self.oid_temp port_max = 8 port = port[1:] ret", "= None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None", "'community', 'help': 'snmp default community (default: public)', 'type': 'str', 'required': False }, {", "= None else: host = None community = None tries = None if", "ret = 2 else: oid = self.oid_din port_max = 16 ret = 0", "== 'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() *", "None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return", "'type': 'int', 'required': False }] __get_help__ = [] __set_help__ = [] __help__ =", "= '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0):", "host specified') self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public'", "= port[1:] ret = 2 else: oid = self.oid_din port_max = 16 ret", "default community (default: public)', 'type': 'str', 'required': False }, { 'name': 'retries', 'help':", "name='DIN port #{}', description='digital input port #{}') for i in range(1, 9): l.append({", "except: tries = None else: host = None community = None tries =", "ret = 1 elif port.startswith('t'): oid = self.oid_temp port_max = 8 port =", "__lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__ = [{", "port - 1)) result = sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return", "value: port = 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] =", "except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import", "community = None tries = None if not host: host = self.snmp_host snmp_port", "value}) return def test(self, cmd=None): if cmd == 'module': return 'default' if not", "8 port = port[1:] ret = 1 elif port.startswith('t'): oid = self.oid_temp port_max", "tries port = str(port) if port.startswith('a'): oid = self.oid_ain port_max = 8 port", "community = self.community if tries is None: tries = self.snmp_tries if not host", "self.community, timeout=get_timeout()) if not version: return 'FAILED' return '%s %s' % (name.strip(), version.strip())", "self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u' % (oid, port - 1),", "not netsnmp else 'netsnmp' if cmd == 'self' and self.snmp_host is None: return", "try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7'", "production it is recommended to install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp", "netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import log_traceback", "__version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ =", "for analog inputs, t1-8 for temperature inputs. DIN events can be received by", "log_traceback() name = None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries", "attemps (default: 0)', 'type': 'int', 'required': False }] __get_help__ = [] __set_help__ =", "self.snmp_port if not community: community = self.community if tries is None: tries =", "SNMP traps. For production it is recommended to install python \"python3-netsnmp\" module. \"\"\"", "value)) self.port_state[port] = value handle_phi_event(self, port, {port: value}) return def test(self, cmd=None): if", "digital inputs, a1-a8 for analog inputs, t1-8 for temperature inputs. DIN events can", "IP-32IN' __features__ = [] __config_help__ = [{ 'name': 'host', 'help': 'module host/ip', 'type':", "'module host/ip', 'type': 'str', 'required': True }, { 'name': 'community', 'help': 'snmp default", "'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__ = [{ 'name': 'host',", "self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def", "'type': 'str', 'required': True }, { 'name': 'community', 'help': 'snmp default community (default:", "from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import", "= self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1", "host or not community: return None _timeout = timeout / tries port =", "return result elif ret == 1: return int(result) / 100 elif ret ==", "l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i) })", "host, data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for", "!= self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value", "'FAILED' if name and cmd == 'self': return 'OK' if netsnmp: try: version", "host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16):", "self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain", "= self.oid_ain port_max = 8 port = port[1:] ret = 1 elif port.startswith('t'):", "tries = self.snmp_tries if not host or not community: return None _timeout =", "port = port[1:] ret = 2 else: oid = self.oid_din port_max = 16", "parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI):", "[{ 'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required': True }, { 'name':", "__get_help__ = [] __set_help__ = [] __help__ = \"\"\" PHI for Denkovi smartDEN", "import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor", "if port < 1 or port > port_max: return None if netsnmp: try:", "port < 1 or port > port_max: return None if netsnmp: try: sess", "0 try: port = int(port) except: return None if port < 1 or", "def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg:", "def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port =", "= self.snmp_tries if not host or not community: return None _timeout = timeout", "netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u'", "'%s %s' % (name.strip(), version.strip()) return { 'info': 'returns relay ip module name", "range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1) self.log_debug('event {}", "+ 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port:", "'.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0'", "'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return l def process_snmp_trap(self,", "- 1) except: log_traceback() sess = None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode()", "if not name: return 'FAILED' if name and cmd == 'self': return 'OK'", "version.strip()) return { 'info': 'returns relay ip module name and version', 'module': 'current", "module. \"\"\" try: import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI", "get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community =", "'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1", "= 1 elif port.startswith('t'): oid = self.oid_temp port_max = 8 port = port[1:]", "= {} if not self.snmp_host: self.log_error('no host specified') self.ready = False self.community =", "/ tries port = str(port) if port.startswith('a'): oid = self.oid_ain port_max = 8", "log_traceback() sess = None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name", "None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else:", "cfg.get('community') tries = cfg.get('retries') try: tries = int(tries) + 1 except: tries =", "int(tries) + 1 except: tries = None else: host = None community =", "= {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port: value}) return def test(self,", "in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1) self.log_debug('event", "except Exception as e: self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u' %", "= int(tries) + 1 except: tries = None else: host = None community", "None else: host = None community = None tries = None if not", "* 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess = None if netsnmp: try:", "== 'self': return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version", "'name': 'retries', 'help': 'snmp retry attemps (default: 0)', 'type': 'int', 'required': False }]", "None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000),", "tries - 1, rf=int) if ret == 0: return result elif ret ==", "sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community,", "return '%s %s' % (name.strip(), version.strip()) return { 'info': 'returns relay ip module", "= 2 else: oid = self.oid_din port_max = 16 ret = 0 try:", "except: return None if port < 1 or port > port_max: return None", "is None: return 'OK' if cmd == 'info' or cmd == 'self': if", "name and cmd == 'self': return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList(", "try: port = int(port) except: return None if port < 1 or port", "'FAILED' return '%s %s' % (name.strip(), version.strip()) return { 'info': 'returns relay ip", "DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' %", "= netsnmp.VarList('%s.%u' % (oid, port - 1)) result = sess.get(o)[0].decode() except Exception as", "None else: result = snmp.get('%s.%u' % (oid, port - 1), host, snmp_port, community,", "_timeout, tries - 1, rf=int) if ret == 0: return result elif ret", "host: host = self.snmp_host snmp_port = self.snmp_port if not community: community = self.community", "retry attemps (default: 0)', 'type': 'int', 'required': False }] __get_help__ = [] __set_help__", "sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except:", "= '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self,", "= parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host: self.log_error('no host specified')", "self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED' return '%s %s' %", "= 8 port = port[1:] ret = 2 else: oid = self.oid_din port_max", "= 4 __required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__", "self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED' return '%s %s' % (name.strip(),", "handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi", "port = str(port) if port.startswith('a'): oid = self.oid_ain port_max = 8 port =", "or cmd == 'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community,", "return 'OK' if cmd == 'info' or cmd == 'self': if netsnmp: try:", "ret = 0 try: port = int(port) except: return None if port <", "self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value =", "'host', 'help': 'module host/ip', 'type': 'str', 'required': True }, { 'name': 'community', 'help':", "== 2: return None if result == '---' else result def get_ports(self): l", "= \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should have port set 1-16", "netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries -", "community: return None _timeout = timeout / tries port = str(port) if port.startswith('a'):", "else: host = None community = None tries = None if not host:", "get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp", "'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din =", "'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return", "Exception as e: self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u' % (oid,", "handle_phi_event(self, port, {port: value}) return def test(self, cmd=None): if cmd == 'module': return", "'help': 'snmp default community (default: public)', 'type': 'str', 'required': False }, { 'name':", "oid = self.oid_ain port_max = 8 port = port[1:] ret = 1 elif", "host = None community = None tries = None if not host: host", "snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED' return '%s %s'", "elif port.startswith('t'): oid = self.oid_temp port_max = 8 port = port[1:] ret =", "self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host: self.log_error('no host", "= cfg.get('community') tries = cfg.get('retries') try: tries = int(tries) + 1 except: tries", "host = self.snmp_host snmp_port = self.snmp_port if not community: community = self.community if", "eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp", "def test(self, cmd=None): if cmd == 'module': return 'default' if not netsnmp else", "except: version = None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if", "try: tries = int(tries) + 1 except: tries = None else: host =", "(name.strip(), version.strip()) return { 'info': 'returns relay ip module name and version', 'module':", "netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries -", "self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def", "'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000),", "1) if not name: return 'FAILED' if name and cmd == 'self': return", "if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries", "= self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}') for i in range(1,", "self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return 'FAILED' if", "__mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = []", "None if port < 1 or port > port_max: return None if netsnmp:", "else: oid = self.oid_din port_max = 16 ret = 0 try: port =", "eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor", "- 1), host, snmp_port, community, _timeout, tries - 1, rf=int) if ret ==", "}) for i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i),", "Sensors should have port set 1-16 for digital inputs, a1-a8 for analog inputs,", "import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import", "cfg.get('retries') try: tries = int(tries) + 1 except: tries = None else: host", "PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state =", "= False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries =", "'.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self)", "\"Apache License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ =", "if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries')", "python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi", "'.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None,", "'smartDEN IP-32IN' __features__ = [] __config_help__ = [{ 'name': 'host', 'help': 'module host/ip',", "received by SNMP traps. For production it is recommended to install python \"python3-netsnmp\"", "= 16 ret = 0 try: port = int(port) except: return None if", "timeout / tries port = str(port) if port.startswith('a'): oid = self.oid_ain port_max =", "i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1)", "from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import", "'retries', 'help': 'snmp retry attemps (default: 0)', 'type': 'int', 'required': False }] __get_help__", "return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i))", "= sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return None else: result =", "if cmd == 'info' or cmd == 'self': if netsnmp: try: sess =", "if not community: community = self.community if tries is None: tries = self.snmp_tries", "parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host: self.log_error('no host specified') self.ready", "if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if", "GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event", "port = 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value", "= self.oid_temp port_max = 8 port = port[1:] ret = 2 else: oid", "= [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__", "+ 1 except: tries = None else: host = None community = None", "port = port[1:] ret = 1 elif port.startswith('t'): oid = self.oid_temp port_max =", "get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}') for i", "\"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should have port set 1-16 for", "= self.snmp_host snmp_port = self.snmp_port if not community: community = self.community if tries", "temperature inputs. DIN events can be received by SNMP traps. For production it", "\"\"\" try: import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as", "tries = int(tries) + 1 except: tries = None else: host = None", "if not host or not community: return None _timeout = timeout / tries", "if result == '---' else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port", "{ 'name': 'community', 'help': 'snmp default community (default: public)', 'type': 'str', 'required': False", "import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class", "%s' % (name.strip(), version.strip()) return { 'info': 'returns relay ip module name and", "4 __required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ =", "self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None,", "port #{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for i in range(1, 9):", "is recommended to install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp", "host/ip', 'type': 'str', 'required': True }, { 'name': 'community', 'help': 'snmp default community", "result = snmp.get('%s.%u' % (oid, port - 1), host, snmp_port, community, _timeout, tries", "host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries') try: tries", "range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input port", "data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i", "'type': 'str', 'required': False }, { 'name': 'retries', 'help': 'snmp retry attemps (default:", "1 except: tries = None else: host = None community = None tries", "def get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community", "community = cfg.get('community') tries = cfg.get('retries') try: tries = int(tries) + 1 except:", "for i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description':", "'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required': True }, { 'name': 'community',", "test(self, cmd=None): if cmd == 'module': return 'default' if not netsnmp else 'netsnmp'", "(C) 2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\" __version__ = \"2.0.0\" __description__", "1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess = None if netsnmp: try: name", "result == '---' else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}',", "= [] __help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should have", "int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6'", "snmp.get('%s.%u' % (oid, port - 1), host, snmp_port, community, _timeout, tries - 1,", "[] __help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should have port", "def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if", "phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161)", "(default: public)', 'type': 'str', 'required': False }, { 'name': 'retries', 'help': 'snmp retry", "tries = None if not host: host = self.snmp_host snmp_port = self.snmp_port if", "Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid, port", "- 1) if not name: return 'FAILED' if name and cmd == 'self':", "Altertech Group\" __license__ = \"Apache License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi", "= self.community if tries is None: tries = self.snmp_tries if not host or", "version = None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not", "inputs, t1-8 for temperature inputs. DIN events can be received by SNMP traps.", "None _timeout = timeout / tries port = str(port) if port.startswith('a'): oid =", "'name': 'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return l def", "== 'self' and self.snmp_host is None: return 'OK' if cmd == 'info' or", "community: community = self.community if tries is None: tries = self.snmp_tries if not", "Denkovi smartDEN IP-32IN Sensors should have port set 1-16 for digital inputs, a1-a8", "{} if not self.snmp_host: self.log_error('no host specified') self.ready = False self.community = self.phi_cfg.get('community')", "= ['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN'", "None: return 'OK' if cmd == 'info' or cmd == 'self': if netsnmp:", "tries is None: tries = self.snmp_tries if not host or not community: return", "version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED' return", "{ 'name': 'retries', 'help': 'snmp retry attemps (default: 0)', 'type': 'int', 'required': False", "% (oid, port - 1), host, snmp_port, community, _timeout, tries - 1, rf=int)", "can be received by SNMP traps. For production it is recommended to install", "start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg: host,", "data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value))", "= netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback()", "sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community,", "timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries =", "= None tries = None if not host: host = self.snmp_host snmp_port =", "or not community: return None _timeout = timeout / tries port = str(port)", "= int(port) except: return None if port < 1 or port > port_max:", "try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1)", "e: self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u' % (oid, port -", "else 'netsnmp' if cmd == 'self' and self.snmp_host is None: return 'OK' if", "community, _timeout, tries - 1, rf=int) if ret == 0: return result elif", "host, snmp_port, community, _timeout, tries - 1, rf=int) if ret == 0: return", "port #{}') for i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port", "self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def", "sess = None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name =", "__equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__ = [{ 'name': 'host', 'help':", "netsnmp.VarList('%s.%u' % (oid, port - 1)) result = sess.get(o)[0].decode() except Exception as e:", "self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host: self.log_error('no host specified') self.ready =", "if cmd == 'module': return 'default' if not netsnmp else 'netsnmp' if cmd", "'snmp default community (default: public)', 'type': 'str', 'required': False }, { 'name': 'retries',", "input port #{}'.format(i) }) return l def process_snmp_trap(self, host, data): if host !=", "install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp = None from", "% (name.strip(), version.strip()) return { 'info': 'returns relay ip module name and version',", "= '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version =", "self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) +", "[] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__ =", "'snmp retry attemps (default: 0)', 'type': 'int', 'required': False }] __get_help__ = []", "== '---' else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital", "'help': 'module host/ip', 'type': 'str', 'required': True }, { 'name': 'community', 'help': 'snmp", "= None community = None tries = None if not host: host =", "Group\" __license__ = \"Apache License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN", "'name': 'community', 'help': 'snmp default community (default: public)', 'type': 'str', 'required': False },", "if port.startswith('a'): oid = self.oid_ain port_max = 8 port = port[1:] ret =", "= self.oid_din port_max = 16 ret = 0 try: port = int(port) except:", "as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self,", "__features__ = [] __config_help__ = [{ 'name': 'host', 'help': 'module host/ip', 'type': 'str',", "2 else: oid = self.oid_din port_max = 16 ret = 0 try: port", "rf=int) if ret == 0: return result elif ret == 1: return int(result)", "None: tries = self.snmp_tries if not host or not community: return None _timeout", "eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161)", "self.port_state = {} if not self.snmp_host: self.log_error('no host specified') self.ready = False self.community", "return None else: result = snmp.get('%s.%u' % (oid, port - 1), host, snmp_port,", "port_max = 8 port = port[1:] ret = 2 else: oid = self.oid_din", "port, {port: value}) return def test(self, cmd=None): if cmd == 'module': return 'default'", "}) return l def process_snmp_trap(self, host, data): if host != self.snmp_host: return if", "port #{}', description='digital input port #{}') for i in range(1, 9): l.append({ 'port':", "= 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name =", "'info' or cmd == 'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port,", "self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return 'FAILED' if name", "try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name = snmp.get(self.oid_name,", "'required': False }, { 'name': 'retries', 'help': 'snmp retry attemps (default: 0)', 'type':", "False }, { 'name': 'retries', 'help': 'snmp retry attemps (default: 0)', 'type': 'int',", "None community = None tries = None if not host: host = self.snmp_host", "port.startswith('t'): oid = self.oid_temp port_max = 8 port = port[1:] ret = 2", "'help': 'snmp retry attemps (default: 0)', 'type': 'int', 'required': False }] __get_help__ =", "#{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return l def process_snmp_trap(self, host, data):", "**kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host:", "return None if port < 1 or port > port_max: return None if", "#{}') for i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i),", "i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog", "snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs):", "import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler from", "try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1)", "'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else:", "{} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port: value}) return def", "License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4", "events can be received by SNMP traps. For production it is recommended to", "1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0'", "name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name = snmp.get(self.oid_name, self.snmp_host,", "self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version", "self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries", "2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\" __version__ = \"2.0.0\" __description__ =", "traps. For production it is recommended to install python \"python3-netsnmp\" module. \"\"\" try:", "1 or port > port_max: return None if netsnmp: try: sess = netsnmp.Session(Version=2,", "#{}'.format(i) }) for i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port", "version: return 'FAILED' return '%s %s' % (name.strip(), version.strip()) return { 'info': 'returns", "9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i)", "port set 1-16 for digital inputs, a1-a8 for analog inputs, t1-8 for temperature", "= [] __set_help__ = [] __help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN", "= None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import log_traceback from", "except: log_traceback() sess = None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback()", "'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ =", "not host: host = self.snmp_host snmp_port = self.snmp_port if not community: community =", "self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not self.snmp_host: self.log_error('no", "'required': True }, { 'name': 'community', 'help': 'snmp default community (default: public)', 'type':", "1, rf=int) if ret == 0: return result elif ret == 1: return", "self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name", "else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port", "cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries", "False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries'))", "PHI as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi", "RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid,", "tries = cfg.get('retries') try: tries = int(tries) + 1 except: tries = None", "or port > port_max: return None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host,", "tries = None else: host = None community = None tries = None", "as e: self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u' % (oid, port", "#{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for i in range(1, 9): l.append({", "description='digital input port #{}') for i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name':", "port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return l def process_snmp_trap(self, host,", "= int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain =", "if cmd == 'self' and self.snmp_host is None: return 'OK' if cmd ==", "it is recommended to install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except:", "DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess =", "have port set 1-16 for digital inputs, a1-a8 for analog inputs, t1-8 for", "in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input", "(oid, port - 1), host, snmp_port, community, _timeout, tries - 1, rf=int) if", "/ 100 elif ret == 2: return None if result == '---' else", "__license__ = \"Apache License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\"", "smartDEN IP-32IN Sensors should have port set 1-16 for digital inputs, a1-a8 for", "= \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ = ['value',", "class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state", "__init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {} if not", "= port[1:] ret = 1 elif port.startswith('t'): oid = self.oid_temp port_max = 8", "l def process_snmp_trap(self, host, data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') !=", "= 8 port = port[1:] ret = 1 elif port.startswith('t'): oid = self.oid_temp", "self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return 'FAILED' if name and", "except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7'", "- 1, rf=int) if ret == 0: return result elif ret == 1:", "netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess", "if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1': return for i in", "self.community if tries is None: tries = self.snmp_tries if not host or not", "log_traceback() return None else: result = snmp.get('%s.%u' % (oid, port - 1), host,", "self.snmp_host snmp_port = self.snmp_port if not community: community = self.community if tries is", "8 port = port[1:] ret = 2 else: oid = self.oid_din port_max =", "'port': 'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for", "None if result == '---' else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN", "ret == 1: return int(result) / 100 elif ret == 2: return None", "retries=self.snmp_tries - 1) if not name: return 'FAILED' if name and cmd ==", "% (oid, port - 1)) result = sess.get(o)[0].decode() except Exception as e: self.log_error(e)", "= 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self,", "= data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port,", "None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if", "for digital inputs, a1-a8 for analog inputs, t1-8 for temperature inputs. DIN events", "port[1:] ret = 2 else: oid = self.oid_din port_max = 16 ret =", "return None _timeout = timeout / tries port = str(port) if port.startswith('a'): oid", "'default' if not netsnmp else 'netsnmp' if cmd == 'self' and self.snmp_host is", "netsnmp else 'netsnmp' if cmd == 'self' and self.snmp_host is None: return 'OK'", "version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version = snmp.get(self.oid_version, self.snmp_host,", "== 'info' or cmd == 'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host,", "return { 'info': 'returns relay ip module name and version', 'module': 'current SNMP", "None if not host: host = self.snmp_host snmp_port = self.snmp_port if not community:", "name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name:", "community (default: public)', 'type': 'str', 'required': False }, { 'name': 'retries', 'help': 'snmp", "= sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port,", "IP-32IN Sensors should have port set 1-16 for digital inputs, a1-a8 for analog", "Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess = None if", "t1-8 for temperature inputs. DIN events can be received by SNMP traps. For", "self.oid_din port_max = 16 ret = 0 try: port = int(port) except: return", "name: return 'FAILED' if name and cmd == 'self': return 'OK' if netsnmp:", "'str', 'required': True }, { 'name': 'community', 'help': 'snmp default community (default: public)',", "= '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp = '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self):", "result elif ret == 1: return int(result) / 100 elif ret == 2:", "cmd == 'self': if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout()", "input port #{}') for i in range(1, 9): l.append({ 'port': 'a{}'.format(i), 'name': 'AIN", "- 1)) result = sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return None", "__help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should have port set", "self.snmp_host: self.log_error('no host specified') self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community')", "1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp =", "value handle_phi_event(self, port, {port: value}) return def test(self, cmd=None): if cmd == 'module':", "snmp_port = self.snmp_port if not community: community = self.community if tries is None:", "return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None", "def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}') for", "== 'module': return 'default' if not netsnmp else 'netsnmp' if cmd == 'self'", "return 'FAILED' if name and cmd == 'self': return 'OK' if netsnmp: try:", "+ 1 except: self.snmp_tries = 1 self.oid_din = '.1.3.6.1.4.1.42505.7.2.1.1.7' self.oid_ain = '.1.3.6.1.4.1.42505.7.2.2.1.6' self.oid_temp", "- 1) o = netsnmp.VarList('%s.%u' % (oid, port - 1)) result = sess.get(o)[0].decode()", "be received by SNMP traps. For production it is recommended to install python", "1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port: value})", "for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i +", "and self.snmp_host is None: return 'OK' if cmd == 'info' or cmd ==", "else: result = snmp.get('%s.%u' % (oid, port - 1), host, snmp_port, community, _timeout,", "2: return None if result == '---' else result def get_ports(self): l =", "return 'default' if not netsnmp else 'netsnmp' if cmd == 'self' and self.snmp_host", "1) except: log_traceback() sess = None if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except:", "netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi", "\"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ = ['value', 'events']", "'t{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) }) return l", "'description': 'temperature input port #{}'.format(i) }) return l def process_snmp_trap(self, host, data): if", "False }] __get_help__ = [] __set_help__ = [] __help__ = \"\"\" PHI for", "True }, { 'name': 'community', 'help': 'snmp default community (default: public)', 'type': 'str',", "1), host, snmp_port, community, _timeout, tries - 1, rf=int) if ret == 0:", "self.oid_version))[0].decode() except: version = None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout())", "\"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__ = ['value', 'events'] __mods_required__ = []", "not host or not community: return None _timeout = timeout / tries port", "port_max: return None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout", "elif ret == 1: return int(result) / 100 elif ret == 2: return", "from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from", "eva.uc.drivers.tools.snmp as snmp import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def", "self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port: value}) return", "not name: return 'FAILED' if name and cmd == 'self': return 'OK' if", "if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=self.snmp_host, RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries", "a1-a8 for analog inputs, t1-8 for temperature inputs. DIN events can be received", "if tries is None: tries = self.snmp_tries if not host or not community:", "https://www.altertech.com/\" __copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\"", "> port_max: return None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community,", "from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import", "if value: port = 'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port]", "cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries') try:", "(default: 0)', 'type': 'int', 'required': False }] __get_help__ = [] __set_help__ = []", "= [] __config_help__ = [{ 'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required':", "def process_snmp_trap(self, host, data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0') != '1.3.6.1.4.1.42505.7.0.1':", "self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries =", "self.port_state[port] = value handle_phi_event(self, port, {port: value}) return def test(self, cmd=None): if cmd", "'name': 'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for i in", "input port #{}'.format(i) }) for i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name':", "not version: return 'FAILED' return '%s %s' % (name.strip(), version.strip()) return { 'info':", "is None: tries = self.snmp_tries if not host or not community: return None", "'temperature input port #{}'.format(i) }) return l def process_snmp_trap(self, host, data): if host", "{port: value}) return def test(self, cmd=None): if cmd == 'module': return 'default' if", "[] __set_help__ = [] __help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors", "by SNMP traps. For production it is recommended to install python \"python3-netsnmp\" module.", "timeout=get_timeout()) if not version: return 'FAILED' return '%s %s' % (name.strip(), version.strip()) return", "= snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED' return '%s", "= [{ 'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required': True }, {", "if not self.snmp_host: self.log_error('no host specified') self.ready = False self.community = self.phi_cfg.get('community') if", "Group, https://www.altertech.com/\" __copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache License", "{}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port, {port: value}) return def test(self, cmd=None):", "100 elif ret == 2: return None if result == '---' else result", "from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import", "public)', 'type': 'str', 'required': False }, { 'name': 'retries', 'help': 'snmp retry attemps", "'---' else result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input", "1-16 for digital inputs, a1-a8 for analog inputs, t1-8 for temperature inputs. DIN", "not community: return None _timeout = timeout / tries port = str(port) if", "set 1-16 for digital inputs, a1-a8 for analog inputs, t1-8 for temperature inputs.", "eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout", "if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries", "ret == 2: return None if result == '---' else result def get_ports(self):", "return None if result == '---' else result def get_ports(self): l = self.generate_port_list(port_max=16,", "= 0 try: port = int(port) except: return None if port < 1", "= 'smartDEN IP-32IN' __features__ = [] __config_help__ = [{ 'name': 'host', 'help': 'module", "IP-32IN\" __api__ = 4 __required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__ =", "= str(port) if port.startswith('a'): oid = self.oid_ain port_max = 8 port = port[1:]", "ret == 0: return result elif ret == 1: return int(result) / 100", "port_max = 8 port = port[1:] ret = 1 elif port.startswith('t'): oid =", "0)', 'type': 'int', 'required': False }] __get_help__ = [] __set_help__ = [] __help__", "specified') self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try:", "if ret == 0: return result elif ret == 1: return int(result) /", "self.oid_temp port_max = 8 port = port[1:] ret = 2 else: oid =", "for i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description':", "Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid, port -", "int(port) except: return None if port < 1 or port > port_max: return", "not self.snmp_host: self.log_error('no host specified') self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get(", "eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port(", "self.snmp_tries if not host or not community: return None _timeout = timeout /", "'info': 'returns relay ip module name and version', 'module': 'current SNMP module' }", "16 ret = 0 try: port = int(port) except: return None if port", "1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid, port - 1)) result", "port #{}'.format(i) }) return l def process_snmp_trap(self, host, data): if host != self.snmp_host:", "inputs, a1-a8 for analog inputs, t1-8 for temperature inputs. DIN events can be", "return int(result) / 100 elif ret == 2: return None if result ==", "161) self.port_state = {} if not self.snmp_host: self.log_error('no host specified') self.ready = False", "'OK' if cmd == 'info' or cmd == 'self': if netsnmp: try: sess", "elif ret == 2: return None if result == '---' else result def", "[] __config_help__ = [{ 'name': 'host', 'help': 'module host/ip', 'type': 'str', 'required': True", "import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from", "#{}', description='digital input port #{}') for i in range(1, 9): l.append({ 'port': 'a{}'.format(i),", "value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i + 1) self.log_debug('event {} =", "return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port = 'din{}'.format(i", "cmd == 'self' and self.snmp_host is None: return 'OK' if cmd == 'info'", "import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'),", "oid = self.oid_din port_max = 16 ret = 0 try: port = int(port)", "9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i)", "'netsnmp' if cmd == 'self' and self.snmp_host is None: return 'OK' if cmd", "try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version = snmp.get(self.oid_version,", "'int', 'required': False }] __get_help__ = [] __set_help__ = [] __help__ = \"\"\"", "= netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o =", "netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version =", "== 0: return result elif ret == 1: return int(result) / 100 elif", "For production it is recommended to install python \"python3-netsnmp\" module. \"\"\" try: import", "None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi", "cmd=None): if cmd == 'module': return 'default' if not netsnmp else 'netsnmp' if", "= None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1)", "self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}') for i in range(1, 9):", "'required': False }] __get_help__ = [] __set_help__ = [] __help__ = \"\"\" PHI", "else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version: return 'FAILED'", "return l def process_snmp_trap(self, host, data): if host != self.snmp_host: return if data.get('1.3.6.1.6.3.1.1.4.1.0')", "if not host: host = self.snmp_host snmp_port = self.snmp_port if not community: community", "else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except: self.snmp_tries = 1 self.oid_din", "\"Altertech Group, https://www.altertech.com/\" __copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache", "o = netsnmp.VarList('%s.%u' % (oid, port - 1)) result = sess.get(o)[0].decode() except Exception", "try: import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import PHI as GenericPHI", "log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port", "@phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port = parse_host_port( self.phi_cfg.get('host'), 161) self.port_state = {}", "}, { 'name': 'community', 'help': 'snmp default community (default: public)', 'type': 'str', 'required':", "= timeout / tries port = str(port) if port.startswith('a'): oid = self.oid_ain port_max", "port = int(port) except: return None if port < 1 or port >", "sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout * 1000000), Retries=self.snmp_tries - 1) o", "if netsnmp: try: name = sess.get(netsnmp.VarList(self.oid_name))[0].decode() except: log_traceback() name = None else: name", "self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else 'public' try: self.snmp_tries = int(self.phi_get('retries')) + 1 except:", "return None if netsnmp: try: sess = netsnmp.Session(Version=2, DestHost=host, RemotePort=snmp_port, Community=community, Timeout=int(_timeout *", "eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools", "{ 'info': 'returns relay ip module name and version', 'module': 'current SNMP module'", "= 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__ = [] __config_help__ = [{ 'name':", "'self' and self.snmp_host is None: return 'OK' if cmd == 'info' or cmd", "cmd == 'info' or cmd == 'self': if netsnmp: try: sess = netsnmp.Session(Version=2,", "if not version: return 'FAILED' return '%s %s' % (name.strip(), version.strip()) return {", "to install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp = None", "= value handle_phi_event(self, port, {port: value}) return def test(self, cmd=None): if cmd ==", "port_max = 16 ret = 0 try: port = int(port) except: return None", "'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for i in range(1,", "port.startswith('a'): oid = self.oid_ain port_max = 8 port = port[1:] ret = 1", "'din{}'.format(i + 1) self.log_debug('event {} = {}'.format(port, value)) self.port_state[port] = value handle_phi_event(self, port,", "'1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port =", "snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return 'FAILED'", "Retries=self.snmp_tries - 1) except: log_traceback() sess = None if netsnmp: try: name =", "= snmp.get('%s.%u' % (oid, port - 1), host, snmp_port, community, _timeout, tries -", "DIN events can be received by SNMP traps. For production it is recommended", "should have port set 1-16 for digital inputs, a1-a8 for analog inputs, t1-8", "2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__ = 4 __required__", "eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as snmp import eva.traphandler", "= snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return", "Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid, port - 1)) result =", "= \"Apache License 2.0\" __version__ = \"2.0.0\" __description__ = \"Denkovi smartDEN IP-32IN\" __api__", "}, { 'name': 'retries', 'help': 'snmp retry attemps (default: 0)', 'type': 'int', 'required':", "int(result) / 100 elif ret == 2: return None if result == '---'", "'self': return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version =", "1)) result = sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return None else:", "l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input port #{}'.format(i) })", "if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except: version = None else: version", "self.oid_ain port_max = 8 port = port[1:] ret = 1 elif port.startswith('t'): oid", "stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'),", "'a{}'.format(i), 'name': 'AIN port #{}'.format(i), 'description': 'analog input port #{}'.format(i) }) for i", "= None else: version = snmp.get(self.oid_version, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout()) if not version:", "'analog input port #{}'.format(i) }) for i in range(1, 9): l.append({ 'port': 't{}'.format(i),", "import get_timeout from eva.uc.driverapi import handle_phi_event from eva.tools import parse_host_port import eva.uc.drivers.tools.snmp as", "else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries - 1) if not", "< 1 or port > port_max: return None if netsnmp: try: sess =", "and cmd == 'self': return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode()", "port=None, cfg=None, timeout=0): if cfg: host, snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community')", "for temperature inputs. DIN events can be received by SNMP traps. For production", "for Denkovi smartDEN IP-32IN Sensors should have port set 1-16 for digital inputs,", "smartDEN IP-32IN\" __api__ = 4 __required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__", "from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host, self.snmp_port =", "* 1000000), Retries=self.snmp_tries - 1) o = netsnmp.VarList('%s.%u' % (oid, port - 1))", "eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if cfg: host, snmp_port", "inputs. DIN events can be received by SNMP traps. For production it is", "return def test(self, cmd=None): if cmd == 'module': return 'default' if not netsnmp", "\"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp = None from eva.uc.drivers.phi.generic_phi import", "= \"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\" __version__ =", "sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return None else: result = snmp.get('%s.%u'", "timeout=get_timeout(), retries=self.snmp_tries - 1) if not name: return 'FAILED' if name and cmd", "#{}'.format(i) }) return l def process_snmp_trap(self, host, data): if host != self.snmp_host: return", "__set_help__ = [] __help__ = \"\"\" PHI for Denkovi smartDEN IP-32IN Sensors should", "cmd == 'self': return 'OK' if netsnmp: try: version = sess.get(netsnmp.VarList( self.oid_version))[0].decode() except:", "result def get_ports(self): l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}')", "_timeout = timeout / tries port = str(port) if port.startswith('a'): oid = self.oid_ain", "'module': return 'default' if not netsnmp else 'netsnmp' if cmd == 'self' and", "!= '1.3.6.1.4.1.42505.7.0.1': return for i in range(16): value = data.get('1.3.6.1.4.1.42505.7.2.1.1.7.{}'.format(i)) if value: port", "['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN IP-32IN' __features__", "port #{}'.format(i) }) for i in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp", "str(port) if port.startswith('a'): oid = self.oid_ain port_max = 8 port = port[1:] ret", "as GenericPHI from eva.uc.driverapi import log_traceback from eva.uc.driverapi import get_timeout from eva.uc.driverapi import", "import eva.traphandler from eva.uc.driverapi import phi_constructor class PHI(GenericPHI): @phi_constructor def __init__(self, **kwargs): self.snmp_host,", "161) community = cfg.get('community') tries = cfg.get('retries') try: tries = int(tries) + 1", "l = self.generate_port_list(port_max=16, name='DIN port #{}', description='digital input port #{}') for i in", "RemotePort=self.snmp_port, Community=self.community, Timeout=int(get_timeout() * 1000000), Retries=self.snmp_tries - 1) except: log_traceback() sess = None", "snmp_port = parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries') try: tries =", "recommended to install python \"python3-netsnmp\" module. \"\"\" try: import netsnmp except: netsnmp =", "in range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input", "self.log_error('no host specified') self.ready = False self.community = self.phi_cfg.get('community') if self.phi_cfg.get( 'community') else", "__required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor' __equipment__ = 'smartDEN", "'.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self): eva.traphandler.unsubscribe(self) def get(self, port=None, cfg=None, timeout=0): if", "= '.1.3.6.1.4.1.42505.7.2.3.1.7' self.oid_name = '.1.3.6.1.4.1.42505.7.1.1.0' self.oid_version = '.1.3.6.1.4.1.42505.7.1.2.0' def start(self): eva.traphandler.subscribe(self) def stop(self):", "PHI for Denkovi smartDEN IP-32IN Sensors should have port set 1-16 for digital", "= None if not host: host = self.snmp_host snmp_port = self.snmp_port if not", "__api__ = 4 __required__ = ['value', 'events'] __mods_required__ = [] __lpi_default__ = 'sensor'", "= parse_host_port(cfg.get('host'), 161) community = cfg.get('community') tries = cfg.get('retries') try: tries = int(tries)", "'description': 'analog input port #{}'.format(i) }) for i in range(1, 9): l.append({ 'port':", "__copyright__ = \"Copyright (C) 2012-2018 Altertech Group\" __license__ = \"Apache License 2.0\" __version__", "range(1, 9): l.append({ 'port': 't{}'.format(i), 'name': 'Temp port #{}'.format(i), 'description': 'temperature input port", "name = None else: name = snmp.get(self.oid_name, self.snmp_host, self.snmp_port, self.community, timeout=get_timeout(), retries=self.snmp_tries -", "= cfg.get('retries') try: tries = int(tries) + 1 except: tries = None else:", "result = sess.get(o)[0].decode() except Exception as e: self.log_error(e) log_traceback() return None else: result" ]
[ "name (e.g. E coli - iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name", "FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True)", "*', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption", "model_db: raise ValidationError( 'A model with that name already exists, please use either", "make sure all the sheets are there and are not empty # make", "(e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True)", "exists, please use another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data", "self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies", "CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit')", "to specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs", "iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()],", "inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise", "name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with", "model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism", "change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme =", "ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name =", "http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *',", "not self.enzymes.data: raise ValidationError('If you add substrate binding order without specifying the catalyzing", "StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *',", "ID;\\n-a single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *',", "specify PDB structures you must also specify the organism name') def validate_strain(self, strain):", "validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain =", "bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list])", "> 1: raise ValidationError('Please select one and only one isoenzyme.') def validate_reaction_string(self, reaction_string):", "ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs (e.g.", "(if it is equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments", "the organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if", "mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add", "= SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model", "id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to specify the organism first) (e.g.", "ids and InChIs should have the same length. Also make sure you separated", "return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return", "len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either provide:\\n-the", "cannot be added to reactions alone, a model must be associated as well.", "else {} if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp id you", "= QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included in the", "that name already exists, please use another name') class ModelModifyForm(FlaskForm): def __init__(self, data):", "specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate)", "first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you need to specify the organism", "select one and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data)", "SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data) > 1: raise", "enzymes): if self.flag == 'modify': if len(enzymes.data) > 1: raise ValidationError('Please select one", "as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify", "validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c',", "ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query", "length. Also make sure you separated each value with a comma.') class ModelAssumptionsForm(FlaskForm):", "value with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption =", "= set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else {} if grasp_id.data in", "and only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()])", "{} if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg id you specified", "models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description", "pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self,", "specified compartment bigg_acronym' + met_compartment[0][ 1] + ' is not part of the", "ValidationError('If you specify PDB structures you must also specify the organism name') def", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order =", "2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment:", "otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self,", "ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] + ' is not part of", "raise ValidationError('If you specify PDB structures you must also specify the organism name')", "strain = StringField('Strain for the PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self,", "QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True)", "query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please use bigg IDs *',", "= flag name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme", "def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If you add a", "raise ValidationError( 'Please specify the metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.')", "for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise", "exists, please use another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data)", "must also specify the organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list", "structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or", "id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model',", "one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) !=", "well. Please add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify", "!= 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for", "!= 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for", "isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise", "comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g.", "= QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism =", "first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to specify the organism first)", "SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list", "metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else", "(e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs", "allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos,", "= QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme", "inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors',", "genes you must also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data", "for the above standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please", "another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name", "if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as", "submit = SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first()", "id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data", "(e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy =", "atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard", "IDs you must also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data", "Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] +", "ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)',", "self.enzymes.data: raise ValidationError('If you add product release order without specifying the catalyzing isoenzyme(s).')", "def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name", "choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942,", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme =", "organism_name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism", "def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def", "specified already exists. Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data", "self.enzymes.data: raise ValidationError('If you add substrate binding order without specifying the catalyzing isoenzyme(s).')", "= QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit", "E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites (you need", "metabolite grasp id you specified already exists. Please choose a different one.') def", "'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme", "add product release order without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for", "= set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else {} if bigg_id.data in", "= TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()])", "added to reactions alone, a model must be associated as well. Please add", "and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True,", "QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included in the model?',", "the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you need to specify", "IntegerField('Number of enzyme active sites (you need to specify the organism first)', validators=[Optional()])", "= QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g.", "StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True)", "TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self,", "validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise", "(you need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you", "metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else {} if bigg_id.data", "data=data) self.local_data = data self.flag = flag grasp_id = StringField('Grasp ID (will be", "and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either", "self.local_data = data name = StringField('Model name (e.g. E coli - iteration 1)", "topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level", "insert it first.') def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If", "same length. Also make sure you separated each value with a comma.') class", "product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' + product + 'does", "catalyzes the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def", "stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please specify the", "already exists. Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and", "QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c,", "order without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list:", "metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs", "= parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The", "adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating',", "parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) !=", "= QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please use bigg", "add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard", "choose a different one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data", "without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list: if", "validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify PDB structures", "flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Enzyme name", "self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' + product + 'does not match", "else {} if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg id you", "self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If", "post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm):", "query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please", "def validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data) > 1: raise ValidationError('Please", "= StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c + 1.5 adp_c <->", "flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Reaction name", "Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()])", "std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.')", "model): # # make sure all the sheets are there and are not", "*', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr)", "(e.g. 3H8A, 1UCW)') strain = StringField('Strain for the PDB structure', id='strain') submit =", "2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id", "catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot", "file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g.", "def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) !=", "allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites (you need to specify the", "validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string,", "max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username", "metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not", "also specify the organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list =", "validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): # #", "('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition", "need to specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you", "ValidationError( 'The metabolite grasp id you specified already exists. Please choose a different", "FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators", "query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met", "re from flask_wtf import FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField,", "validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If you specify encoding genes", "EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser", "uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify uniprot IDs you must also", "models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use", "wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField", "and not self.organism_name.data: raise ValidationError('If you specify the number of active sites you", "SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit", "class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions,", "raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if", "number of active sites you must also specify the organism name.') def validate_gene_names(self,", "specify the reference for the above standard Gibbs energy.') if std_gibbs_energy_references.data and not", "type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references", "Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else {} if", "organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting", "'.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies cannot be", "want to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm):", "the model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References, please use DOI", "raise ValidationError('If you specify uniprot IDs you must also specify the organism name')", "raise ValidationError('The isoenzyme you specified already exists. Please choose a different name.') def", "validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs)", "pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs", "pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify PDB structures you must also", "StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )')", "Bigg IDs (e.g. 1 pep_c + 1.5 adp_c <-> 1 pyr_c + 2.0", "user is not None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm): post", "metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not", "name already exists, please use another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self,", "active sites (you need to specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding", "and not self.organism_name.data: raise ValidationError('If you specify uniprot IDs you must also specify", "'Gibbs energies cannot be added to reactions alone, a model must be associated", "if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' + substrate + 'does not", "class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions,", "something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None,", "this assumption included in the model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField(", "submit = SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please select", "= SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism", "Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from", "Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query", "each value with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption", "pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids", "organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you", "isoenzyme): if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list", "sure you separated each value with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model", "validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g.", "*', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms,", "metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else", "Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism =", "the model excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id =", "to specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to", "the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to specify the", "*', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP", "metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment", "pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg", "def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def", "= StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def", "= FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs", "you add product release order without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data)", "if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not None: raise", "above standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the", "MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations", "SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db:", "in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError(", "= SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names,", "*', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain", "organism with that name already exists, please use another name') class ReactionForm(FlaskForm): def", "validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition", "if not self.models.data: raise ValidationError( 'Gibbs energies cannot be added to reactions alone,", "are there and are not empty # make sure enzyme_Reaction columns have the", "strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments =", "validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify evidence level", "ValidationError('If you specify encoding genes you must also specify the organism name.') def", "validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID')", "bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments,", "met_compartment[0][ 1] + ' is not part of the database, please insert it", "raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if", "class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit", "validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): # # make sure all the", "' is not part of the database, please insert it first.') def validate_mechanism(self,", "constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references", "StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)',", "please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class", "DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme", "= Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else {}", "in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' + substrate +", "name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify", "(e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type',", "data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag grasp_id = StringField('Grasp", "StringField( 'Reference for Gibbs energy (if it is equilibrator just type equilibrator, otherwise", "any metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and", "ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms)", "name already exists, please use another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'):", "query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites (you need to specify", "Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\", "reaction_string = StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c + 1.5 adp_c", "(e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme", "specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to specify", "*', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models", "max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data", "= QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos =", "model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): # # make", "if model_db: raise ValidationError('A model with that name already exists, please use another", "(you need to specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names", "that name already exists, please use another name') class ReactionForm(FlaskForm): def __init__(self, data=None,", "EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes():", "= StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6)", "name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction =", "StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit =", "= data name = StringField('Model name (e.g. E coli - iteration 1) *',", "Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs", "'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField(", "PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c", "IDs either provide:\\n-the corresponding strains for each PDB ID;\\n-a single strain name\\n-or no", "enzyme active sites (you need to specify the organism first)', validators=[Optional()]) gene_names =", "= parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The", "included_in_model = SelectField('Is this assumption included in the model?', choices=[('True', 'True'), ('False', 'False')])", "catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references (e.g.", "reactions alone, a model must be associated as well. Please add model name.')", "= StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g.", "specify the organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for the PDB", "ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding strains for each PDB ID;\\n-a", "validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References,", "coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions',", "validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please select only one model.') class", "or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in", "comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']:", "included in the model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References, please", "OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items():", "validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True)", "prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy", "get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return Organism.query def get_reactions():", "that name already exists, please use either the original name or another one.')", "ValidationError( 'Please specify the metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db", "name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) >", "return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return", "well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the", "get_models(): return Model.query def get_organisms(): return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm):", "met) if not met_compartment: raise ValidationError( 'Please specify the metabolite' + met +", "uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify uniprot IDs you", "for the PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag", "= SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')])", "= StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg", "('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in", "not self.enzymes.data: raise ValidationError('If you add a reaction mechanism, you need to specify", "bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments", "QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models,", "'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme", "specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and", "all the sheets are there and are not empty # make sure enzyme_Reaction", "IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please use bigg", "gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If you specify encoding genes you", "enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField(", "'The metabolite grasp id you specified already exists. Please choose a different one.')", "ValidationError('If you add substrate binding order without specifying the catalyzing isoenzyme(s).') substrate_list =", "StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name):", "name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A", "QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def", "type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit')", "reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m',", "QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()])", "(True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in", "not met_compartment: raise ValidationError( 'Please specify the metabolite' + met + 'as metabolite_compartmentAcronym,", "activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level',", "get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms():", "= TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def", "query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info',", "number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify the number of", "query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): #", "SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you only want to change the", "the organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for the PDB structure',", "= TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db:", "you must also specify the organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data)", "ValidationError('Please select one and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry =", "specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and", "already exists, please use either the original name or another one.') class ModelFormBase(FlaskForm):", "'The metabolite' + substrate + 'does not match any metabolite in' + self.reaction_string.data", "= QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g.", "please use another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data", "get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions():", "self.original_username = original_username def validate_username(self, username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first()", "id you specified already exists. Please choose a different one.') def validate_bigg_id(self, bigg_id):", "self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme", "= SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please select only", "StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c + 1.5 adp_c <-> 1", "User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please use a different username.') class", "grasp_id): if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list", "(e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism", "use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm):", "query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E", "metabolite bigg id you specified already exists. Please choose a different one.') def", "organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list)", "QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations',", "raise ValidationError('Please use a different username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[", "not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm):", "organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need to", "SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you only want to", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme =", "SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with", "QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active", "select only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model =", "organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you need to specify the", "get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions():", "class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit =", "StringField('Model name (e.g. E coli - iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism", "ValidationError('Please use a different username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(),", "single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes)", "= StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1)", "submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli) *',", "validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References,", "if len(enzymes.data) > 1: raise ValidationError('Please select one and only one isoenzyme.') def", "submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you only", "('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not", "PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC", "(e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'),", "choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references =", "def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify uniprot", "+ met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db:", "def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self,", "IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import", "def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model name (e.g.", "*', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please", "one and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) #", "phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id =", "substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' + substrate + 'does", "class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you only want to change", "raise ValidationError('Please specify the reference for the above standard Gibbs energy.') if std_gibbs_energy_references.data", "make sure enzyme_Reaction columns have the correct names # return 0 #validate model", "validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data", "(e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db =", "choose a different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data,", "SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli - iteration 1)", "ValidationError('Please select one and only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name", "= TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify': if", "the correct names # return 0 #validate model name # make sure kinetics1", "StringField('PDB structure IDs (you need to specify the organism first) (e.g. 3H8A, 1UCW)')", "model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db", "def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify PDB", "SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one)", "equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def", "Also make sure you separated each value with a comma.') class ModelAssumptionsForm(FlaskForm): model", "return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return", "alone, a model must be associated as well. Please add model name.') if", "to add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField(", "query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism", "kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph =", "std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for", "description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model =", "InChIs should have the same length. Also make sure you separated each value", "evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included in", "as well. Please add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please", "specify the number of active sites you must also specify the organism name.')", "another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data", "need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need", "raise ValidationError('You cannot specify evidence level for the mechanism without specifying a mechanism.')", "!= self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please use", "inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed',", "\\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return", "model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description", "(e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag !=", "sure all the sheets are there and are not empty # make sure", "get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names():", "if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list =", "metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation", "= QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g.", "already exists, please use another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self,", "pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify PDB structures you", "you must also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and", "enzyme in metabolite_list]) if metabolite_list else {} if bigg_id.data in metabolite_list: raise ValidationError(", "= QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use", "= StringField('Model name (e.g. E coli - iteration 1) *', validators=[DataRequired()]) organism_name =", "need to specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure", "equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit", "must also specify the organism name.') def validate_gene_names(self, gene_names): if gene_names.data and not", "organism = QuerySelectField('Organisms (leave blank if you only want to change the enzyme", "use either the original name or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models',", "if self.flag == 'modify': if len(enzymes.data) > 1: raise ValidationError('Please select one and", "> 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB", "organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector", "validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if you add the mechanism, you", "enzyme in metabolite_list]) if metabolite_list else {} if grasp_id.data in metabolite_list: raise ValidationError(", "= SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']:", "= parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The", "list of ChEBI ids and InChIs should have the same length. Also make", "about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args,", "strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list)", "to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data:", "'.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add", "catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1:", "substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError(", "ID (will be shown on the model excel file) *', validators=[DataRequired()]) name =", "must also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not", "EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def", "name (if you add the mechanism, you also need to add the isoenzyme(s)", "must be associated as well. Please add model name.') if std_gibbs_energy_std.data and not", "TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction", "description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references =", "order without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list:", "use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm):", "SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one) *', query_factory=get_enzymes,", "*', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp),", "'The metabolite bigg id you specified already exists. Please choose a different one.')", "'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified", "StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *',", "(e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id", "inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g.", "wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired from app.models", "IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level =", "= QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit')", "effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model", "== 'modify': if len(enzymes.data) > 1: raise ValidationError('Please select one and only one", "= Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that name already exists, please", "= FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy',", "the metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if", "= TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField(", "len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding strains", "set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else {} if bigg_id.data in metabolite_list:", "Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers", "standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard", "one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list", "a model must be associated as well. Please add model name.') if std_gibbs_energy_std.data", "self.mechanism.data: raise ValidationError('You cannot specify evidence level for the mechanism without specifying a", "validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models", "strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions =", "not part of the database, please insert it first.') def validate_mechanism(self, mechanism): if", "a different one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data !=", "structure IDs (you need to specify the organism first) (e.g. 3H8A, 1UCW)') strain", "id you specified already exists. Please choose a different one.') def validate_inchis(self, inchis):", "<-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id", "if len(model.data) > 1: raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism", "query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms)", "1UCW)') strain = StringField('Strain for the PDB structure', id='strain') submit = SubmitField('Submit') def", "*', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation", "len(chebi_list): raise ValidationError( 'The list of ChEBI ids and InChIs should have the", "StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments',", "def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify evidence", "validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please", "= SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']:", "validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'):", "QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField(", "a different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False)", "EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query", "mechanism_references = StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level =", "add the mechanism, you also need to add the isoenzyme(s) that catalyze the", "the mechanism, you also need to add the isoenzyme(s) that catalyze the reaction)',", "validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add substrate binding", "= SubmitField('Submit') #def validate_model(self, model): # # make sure all the sheets are", "is not None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm): post =", "you add a reaction mechanism, you need to specify the catalyzing isoenzyme(s).') def", "isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists. Please choose a", "in enzyme_list]) if enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme", "= QuerySelectField('Organisms (leave blank if you only want to change the enzyme info).',", "= StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment =", "= StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit", "'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please", "FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Enzyme name (e.g.", "have the correct names # return 0 #validate model name # make sure", "# make sure all the sheets are there and are not empty #", "'A model with that name already exists, please use either the original name", "Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query", "in metabolite_list]) if metabolite_list else {} if grasp_id.data in metabolite_list: raise ValidationError( 'The", "name = StringField('Model name (e.g. E coli - iteration 1) *', validators=[DataRequired()]) organism_name", "StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self,", "energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please", "self.organism_name.data: raise ValidationError('If you specify uniprot IDs you must also specify the organism", "if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify PDB structures you must", "reference for the above standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise", "id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type", "app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def", "organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of", "raise ValidationError('If you add a reaction mechanism, you need to specify the catalyzing", "metabolite' + product + 'does not match any metabolite in' + self.reaction_string.data +", "validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs", "def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return Organism.query def", "query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if you add the mechanism,", "met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise", "-1: raise ValidationError( 'The metabolite' + product + 'does not match any metabolite", "StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs", "import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations():", "self.flag = flag name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym =", "'True'), ('False', 'False')]) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)')", "query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the", "exists. Please choose a different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list", "def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that", "std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for", "binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)')", "QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g.", "raise ValidationError( 'A model with that name already exists, please use either the", "1] + ' is not part of the database, please insert it first.')", "(e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs (e.g. 1", "(e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant", "data): FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model name (e.g. E coli", "compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][", "the database, please insert it first.') def validate_mechanism(self, mechanism): if mechanism.data and not", "SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self,", "'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level", "validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use", "'The metabolite' + product + 'does not match any metabolite in' + self.reaction_string.data", "query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise", "= FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): # # make sure", "validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *',", "if gene_names.data and not self.organism_name.data: raise ValidationError('If you specify encoding genes you must", "you specified already exists. Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if", "ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name',", "*', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level", "isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c',", "query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments", "= FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard", "'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme", "= TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs):", "False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of ChEBI ids and", "raise ValidationError('If you specify the number of active sites you must also specify", "either provide:\\n-the corresponding strains for each PDB ID;\\n-a single strain name\\n-or no strain", "QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please use bigg IDs", "SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *',", "(you need to specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB", "= QuerySelectField( 'Enzyme mechanism name (if you add the mechanism, you also need", "metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector", "query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs", "model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs", "the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942,", "= QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self,", "Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite", "*', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction", "specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If", "__init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username):", "columns have the correct names # return 0 #validate model name # make", "'modify': if len(enzymes.data) > 1: raise ValidationError('Please select one and only one isoenzyme.')", "and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') class", "if not met_compartment: raise ValidationError( 'Please specify the metabolite' + met + 'as", "http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *',", "M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField(", "organism = QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes", "assumption included in the model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References,", "raise ValidationError( 'The list of ChEBI ids and InChIs should have the same", "enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that", "enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations =", "without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise", "= QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors =", "QuerySelectField('Organisms (leave blank if you only want to change the enzyme info).', query_factory=get_organisms,", "submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data !=", "= QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments", "reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0),", "subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add substrate binding order without specifying", "raise ValidationError('Please select one and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry", "= original_username def validate_username(self, username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if", "super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username): if username.data != self.original_username:", "if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists. Please choose", "SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit =", "query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the", "User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import", "= SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data", "need to add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references =", "return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return", "'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence", "class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag =", "pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs", "name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)')", "use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm):", "original name or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit", "name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def", "def validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please select only one model.')", "class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def", "one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0),", "return 0 #validate model name # make sure kinetics1 sheet has the right", "Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that name already exists, please use", "ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data", "substrate binding order without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate", "please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp),", "= parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of ChEBI", "Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with that name already exists, please", "data self.flag = flag name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym", "self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit", "with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption", "use another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data", "class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit =", "<filename>app/main/forms.py import re from flask_wtf import FlaskForm from wtforms import FloatField, IntegerField, SelectField,", "the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If", "mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names,", "StringField('Grasp ID (will be shown on the model excel file) *', validators=[DataRequired()]) name", "model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True)", "mechanism name (if you add the mechanism, you also need to add the", "if metabolite_list else {} if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp", "of enzyme active sites (you need to specify the organism first)', validators=[Optional()]) gene_names", "query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models,", "mechanism, you also need to add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms,", "(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph", "len(enzymes.data) > 1: raise ValidationError('Please select one and only one isoenzyme.') def validate_reaction_string(self,", "energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms", "adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g.", "'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence", "QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI", "def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select one and only", "exists. Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not", "TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise", "to specify the organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for the", "StringField('Strain for the PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if", "ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model", "(select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if", "== -1: raise ValidationError( 'The metabolite' + substrate + 'does not match any", "CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def", "for each PDB ID;\\n-a single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme", "StringField('Affected metabolite (e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type',", "Optional from flask_wtf.file import FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism,", "Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list else {} if", "= set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else {} if isoenzyme.data in", "compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models", "std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the", "validate_model(self, model): # # make sure all the sheets are there and are", "the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not", "is not part of the database, please insert it first.') def validate_mechanism(self, mechanism):", "len(enzyme.data) != 1: raise ValidationError('Please select one and only one isoenzyme.') class SelectModelForm(FlaskForm):", "Model.query def get_organisms(): return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username =", "product + 'does not match any metabolite in' + self.reaction_string.data + '.') def", "or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue')", "class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag =", "add a reaction mechanism, you need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self,", "you also need to add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True)", "ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met,", "use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes):", "specify the metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first()", "ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag", "ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model name", "return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return", "raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()])", "adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in", "*', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites =", "= flag name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction", "'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant", "coli - iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli)", "self.local_data = data self.flag = flag name = StringField('Reaction name (e.g. phosphofructokinase) *',", "model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True)", "+ 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The", "ValidationError( 'A model with that name already exists, please use either the original", "std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.')", "Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise", "QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism", "already exists. Please choose a different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data)", "= FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names,", "providing PDB IDs either provide:\\n-the corresponding strains for each PDB ID;\\n-a single strain", "= re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please specify the metabolite' +", "EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query", "use another name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data =", "you specified already exists. Please choose a different one.') def validate_inchis(self, inchis): chebi_list", "= QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self,", "std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy", "standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data:", "bigg_id): if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list", "= QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name", "use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm):", "data=data) self.local_data = data name = StringField('Model name (e.g. E coli - iteration", "organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs (you need to specify the organism", "exists, please use either the original name or another one.') class ModelFormBase(FlaskForm): model_base", "use Bigg IDs (e.g. 1 pep_c + 1.5 adp_c <-> 1 pyr_c +", "= StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain", "StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if", "coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions", "SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag", "allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True)", "if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as", "+ ' is not part of the database, please insert it first.') def", "= TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g. E", "QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery)", "{} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists. Please", "names (you need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot IDs", "SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list", "\\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list,", "!= self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if", "class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit')", "= StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK)", "class ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli - iteration 1) *',", "mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)')", "order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std", "Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me =", "isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list])", "SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True)", "-1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment", "QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g.", "(e.g. E coli - iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g.", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme =", "StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g.", "= SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data) > 1:", "allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names,", "not None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm): post = TextAreaField('Say", "query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models =", "**kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username): if username.data !=", "= QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite", "mechanism = QuerySelectField( 'Enzyme mechanism name (if you add the mechanism, you also", "return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0,", "with that name already exists, please use another name') class ReactionForm(FlaskForm): def __init__(self,", "'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit')", "class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag =", "first.') def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If you add", "StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c,", "subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add substrate binding order", "FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Reaction name (e.g.", "validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list):", "model excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg", "= StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True)", "*', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids =", "Length, Optional from flask_wtf.file import FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel,", "get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors():", "= StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *',", "import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file import", "ValidationError('You cannot specify evidence level for the mechanism without specifying a mechanism.') def", "'When providing PDB IDs either provide:\\n-the corresponding strains for each PDB ID;\\n-a single", "you must also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and", "be added to reactions alone, a model must be associated as well. Please", "std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.')", "= parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list)", "evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942,", "raise ValidationError('Please specify the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit =", "*', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True)", "product_list = parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError(", "and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def", "are not empty # make sure enzyme_Reaction columns have the correct names #", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag", "QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name):", "def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list =", "if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add product release order without", "= TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()])", "+ 'does not match any metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self,", "ValidationError('If you add a reaction mechanism, you need to specify the catalyzing isoenzyme(s).')", "exists. Please choose a different one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify'", "TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional", "grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use", "inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of", "specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you need to", "= data self.flag = flag name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()])", "of active sites you must also specify the organism name.') def validate_gene_names(self, gene_names):", "number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify the number of active sites", "ChEBI ids and InChIs should have the same length. Also make sure you", "ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments,", "query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please use bigg IDs *',", "in isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists. Please choose a different", "= QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI", "model must be associated as well. Please add model name.') if std_gibbs_energy_std.data and", "original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username): if", "Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that name already exists, please use", "StringField('Uniprot IDs (you need to specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids", "def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify the", "allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli)", "IDs (you need to specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids =", "met_compartment: raise ValidationError( 'Please specify the metabolite' + met + 'as metabolite_compartmentAcronym, e.g.", "QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired", "reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme):", "comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()])", "energies cannot be added to reactions alone, a model must be associated as", "mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify evidence level for", "UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit')", "model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with that name already", "def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def", "the above standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify", "select one and only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *',", "sites (you need to specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene", "if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify uniprot IDs you must", "+ 'does not match any metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self,", "else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists.", "return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return", "return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me", "standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength =", "validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add product release", "comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes,", "(e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string", "self.flag = flag grasp_id = StringField('Grasp ID (will be shown on the model", "active sites you must also specify the organism name.') def validate_gene_names(self, gene_names): if", "metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected", "evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI", "please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'),", "you add the mechanism, you also need to add the isoenzyme(s) that catalyze", "EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query", "validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met =", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name =", "organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic", "submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction =", "raise ValidationError('Please select one and only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model", "isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()])", "(e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need to specify the", "wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file", "flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag grasp_id = StringField('Grasp ID", "subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order", "http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag ==", "from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query", "get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models():", "validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the", "= QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models =", "Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo,", "submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data =", "allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True)", "use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please", "submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select", "the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not", "activator_met = StringField('Activating metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list')", "Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else {} if", "pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list):", "StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met =", "enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme", "order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy", "activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc", "with that name already exists, please use either the original name or another", "(will be shown on the model excel file) *', validators=[DataRequired()]) name = StringField('Name", "for enzyme in metabolite_list]) if metabolite_list else {} if bigg_id.data in metabolite_list: raise", "the same length. Also make sure you separated each value with a comma.')", "a reaction mechanism, you need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level):", "ValidationError('The isoenzyme you specified already exists. Please choose a different name.') def validate_number_of_active_sites(self,", "+ '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you", "*', validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c +", "+ product + 'does not match any metabolite in' + self.reaction_string.data + '.')", "= StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name", "TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm,", "of ChEBI ids and InChIs should have the same length. Also make sure", "http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *',", "if not compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] + '", "self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id for enzyme in metabolite_list]) if metabolite_list", "def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1", "(eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number =", "submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()])", "only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit", "just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit =", "to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name =", "*', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1:", "it first.') def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If you", "QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI", "QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model):", "TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli", "prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add product release order without specifying", "query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if name.data", "std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy", "isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue')", "('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level =", "def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference", "raise ValidationError('A model with that name already exists, please use another name') class", "Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data:", "= StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True)", "effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level',", "allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()],", "sure enzyme_Reaction columns have the correct names # return 0 #validate model name", "original_username def validate_username(self, username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user", "# return 0 #validate model name # make sure kinetics1 sheet has the", "allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()],", "StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()])", "shown on the model excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)')", "you specify the number of active sites you must also specify the organism", "specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and", "metabolite_list]) if metabolite_list else {} if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite", "= SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if", "*', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number", "std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if it is equilibrator just type", "EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit =", "DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme", "ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def", "def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard", "validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all()", "isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else {} if isoenzyme.data", "comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if", "you need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and", "number_of_active_sites = IntegerField('Number of enzyme active sites (you need to specify the organism", "allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first()", "metabolite_list else {} if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp id", "models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please use", "effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use", "E coli - iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E", "FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User,", "associated as well. Please add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise", "from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional from", "empty # make sure enzyme_Reaction columns have the correct names # return 0", "id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence", "DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self,", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene", "EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()])", "username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not None:", "class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description", "StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions',", "validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all()", "(e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std =", "self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.bigg_id", "0 #validate model name # make sure kinetics1 sheet has the right column", "*', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze", "self.flag == 'modify': if len(enzymes.data) > 1: raise ValidationError('Please select one and only", "energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please", "= QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use", "= StringField('Encoding gene names (you need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list", ")') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data", "def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def", "provide:\\n-the corresponding strains for each PDB ID;\\n-a single strain name\\n-or no strain names.')", "ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return Organism.query def get_reactions(): return Reaction.query", "comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes,", "+ self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs", "self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph):", "self.enzymes.data: raise ValidationError('If you add a reaction mechanism, you need to specify the", "InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or", "for enzyme in metabolite_list]) if metabolite_list else {} if grasp_id.data in metabolite_list: raise", "another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class", "organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you", "a different username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)])", "= StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in", "= SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit", "mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data:", "in the model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References, please use", "in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self,", "name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg.", "not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self,", "one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()])", "std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy", "number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites", "FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import", "-1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)',", "FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def validate_model(self, model): # # make sure all", "submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction =", "names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions)", "not match any metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if", "strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions,", "data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Reaction", "evidence level for the mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if", "FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True)", "from flask_wtf import FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField", "MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit", "= QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if", "well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the", "product in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' + product", "-1: raise ValidationError( 'The metabolite' + substrate + 'does not match any metabolite", "('False', 'False')]) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments", "import FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields", "the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for", "TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']: model_db =", "and not self.mechanism.data: raise ValidationError('You cannot specify evidence level for the mechanism without", "model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit", "Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise", "bigg id you specified already exists. Please choose a different one.') def validate_inchis(self,", "def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def", "EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query", "the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm):", "if user is not None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm):", "QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942,", "no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction", "raise ValidationError( 'Gibbs energies cannot be added to reactions alone, a model must", "validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met =", "Please add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the", "allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release", "SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag", "please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'),", "def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def", "def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list =", "1: raise ValidationError('Please select one and only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible,", "= SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction", "= SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data", "name') class ReactionForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag", "not empty # make sure enzyme_Reaction columns have the correct names # return", "blank if you only want to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit", "1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if", "= QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite", "metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else {} if grasp_id.data", "already exists, please use another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data)", "reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)',", "= data self.flag = flag name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()])", "chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError(", "enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified already", "activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please", "('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment =", "specified already exists. Please choose a different one.') def validate_bigg_id(self, bigg_id): if self.flag", "you specify uniprot IDs you must also specify the organism name') def validate_pdb_structure_ids(self,", "please use another name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data =", "query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product", "{} if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp id you specified", "only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data)", "compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] + ' is not", "StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names,", "ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli - iteration 1) *', validators=[DataRequired()])", "ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you", "import re from flask_wtf import FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField,", "if enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you specified", "enzyme in enzyme_list]) if enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The", "'False')]) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments =", "E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first()", "Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return Organism.query", "submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data =", "strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *',", "strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction", "= SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli - iteration", "IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level", "len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of ChEBI ids and InChIs should", "specify uniprot IDs you must also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids):", "if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as", "def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5),", "bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg id you specified already exists.", "to specify the organism first)', validators=[Optional()]) gene_names = StringField('Encoding gene names (you need", "http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name", "('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()])", "enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism", "first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for the PDB structure', id='strain') submit", "validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username,", "Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise", "StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *',", "'does not match any metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order):", "raise ValidationError('If you add product release order without specifying the catalyzing isoenzyme(s).') product_list", "acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g.", "EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions, EnzymeReactionMiscInfo, Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments():", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model", "query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1: raise", "the reference for the above standard Gibbs energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data:", "*', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data)", "mechanism.data and not self.enzymes.data: raise ValidationError('If you add a reaction mechanism, you need", "allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction", "specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product)", "chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6),", "EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query", "allow_blank=True) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments =", "*', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *',", "isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify", "ValidationError('A model with that name already exists, please use another name') class ModelModifyForm(FlaskForm):", "self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the above standard", "have the same length. Also make sure you separated each value with a", "len(model.data) > 1: raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism =", "also specify the organism name.') def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data:", "bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'),", "allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if name.data !=", "metabolite (e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown',", "ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism =", "there and are not empty # make sure enzyme_Reaction columns have the correct", "= StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK)", "if mechanism.data and not self.enzymes.data: raise ValidationError('If you add a reaction mechanism, you", "import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation,", "*', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *',", "compartment bigg_acronym' + met_compartment[0][ 1] + ' is not part of the database,", "query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included in the model?', choices=[('True', 'True'),", "StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name =", "kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength", "name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If you specify", "the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not", "__init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag grasp_id =", "name or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit =", "= ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for", "#def validate_model(self, model): # # make sure all the sheets are there and", "specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise", "Metabolite from app.utils.parsers import parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return", "use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()])", "(you need to specify the organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain", "specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise", "name (e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db", "'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition constant (in M)',", "StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism", "get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms():", "data self.flag = flag name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym", "def validate_name(self, name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise", "organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that name already exists,", "for enzyme in enzyme_list]) if enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise", "1: raise ValidationError('Please select one and only one isoenzyme.') class SelectModelForm(FlaskForm): model =", "gene_names = StringField('Encoding gene names (you need to specify the organism first)', id='gene_bigg_ids')", "= StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level',", "adp_c <-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID')", "id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions", "add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI", "P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need to specify the organism first)", "= StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme", "= StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g.", "EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism =", "raise ValidationError( 'The metabolite' + substrate + 'does not match any metabolite in'", "raise ValidationError('An organism with that name already exists, please use another name') class", "class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one) *',", "that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references", "allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()],", "name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()])", "for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if it", "= QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis =", "EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag", "level for the mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data", "QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please use bigg IDs", "the PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag !=", "validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for", "the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You", "FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag grasp_id = StringField('Grasp ID (will", "one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit =", "id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'),", "match any metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not", "*', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True)", "= TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is", "kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism", "(in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references =", "= StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id", "*', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in", "= StringField('Grasp ID (will be shown on the model excel file) *', validators=[DataRequired()])", "+ '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies cannot", "SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with", "energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if it is equilibrator", "and are not empty # make sure enzyme_Reaction columns have the correct names", "validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If you add a reaction", "need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not", "and not self.enzymes.data: raise ValidationError('If you add a reaction mechanism, you need to", "stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)]))", "SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant", "without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if", "def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If you specify encoding", "!= 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for", "query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ')", "if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as", "# make sure enzyme_Reaction columns have the correct names # return 0 #validate", "self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id", "SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def", "ValidationError('An organism with that name already exists, please use another name') class ReactionForm(FlaskForm):", "sheets are there and are not empty # make sure enzyme_Reaction columns have", "set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else {} if grasp_id.data in metabolite_list:", "validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please", "strains for each PDB ID;\\n-a single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm):", "you only want to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue')", "not self.organism_name.data: raise ValidationError('If you specify uniprot IDs you must also specify the", "validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please use bigg IDs', id='metabolite_list')", "inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self,", "a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you", "met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please specify the metabolite'", "flag name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym", "in metabolite_list]) if metabolite_list else {} if bigg_id.data in metabolite_list: raise ValidationError( 'The", "models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction", "ValidationError( 'The metabolite bigg id you specified already exists. Please choose a different", "well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the", "def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list =", "!= 1: raise ValidationError('Please select one and only one isoenzyme.') class SelectModelForm(FlaskForm): model", "model with that name already exists, please use another name') class ModelModifyForm(FlaskForm): def", "name = StringField('Reaction name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g.", "specify evidence level for the mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order):", "('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References,", "ValidationError( 'The list of ChEBI ids and InChIs should have the same length.", "specified already exists. Please choose a different one.') def validate_inchis(self, inchis): chebi_list =", "class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions,", "separated each value with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models)", "M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField(", "class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if", "validate_username(self, username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not", "ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data", "a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If", "PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()]) reaction_string =", "correct names # return 0 #validate model name # make sure kinetics1 sheet", "must also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not", "= QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use bigg", "strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and", "name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy", "+ 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID')", "= StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name", "specify the organism name.') def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise", "submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data) >", "return Model.query def get_organisms(): return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username", "name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm):", "= SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction", "be associated as well. Please add model name.') if std_gibbs_energy_std.data and not self.std_gibbs_energy.data:", "Please choose a different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list =", "references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True)", "also need to add the isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references", "for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references", "IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit", "energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField(", "submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify' or grasp_id.data !=", "IDs (you need to specify the organism first) (e.g. 3H8A, 1UCW)') strain =", "http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate", "get_organisms(): return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()])", "**kwargs) self.original_username = original_username def validate_username(self, username): if username.data != self.original_username: user =", "= Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else {}", "raise ValidationError('If you add substrate binding order without specifying the catalyzing isoenzyme(s).') substrate_list", "validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references", "raise ValidationError( 'The metabolite grasp id you specified already exists. Please choose a", "flag name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym", "first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need to specify", "= StringField('Strain for the PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme):", "QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms)", "*args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username): if username.data", "level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order =", "references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments')", "(e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX", "StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment = QuerySelectField('Compartment", "stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please", "EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query", "or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in", "validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference", "= StringField('PDB structure IDs (you need to specify the organism first) (e.g. 3H8A,", "std_gibbs_energy_std.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.')", "= SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username = original_username", "adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment bigg_acronym' +", "!= self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if", "need to specify the organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for", "*', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1:", "(e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'):", "import ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired from app.models import", "QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g.", "model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors", "e.g. adp_c.') compartment_db = Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment bigg_acronym'", "user = User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please use a different", "validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *',", "Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])", "query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors,", "inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list')", "and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding", "= StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments =", "allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g.", "*', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met", "organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating", "(e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite", "name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name',", "please use either the original name or another one.') class ModelFormBase(FlaskForm): model_base =", "# (True, OrderedDict([('m_pep_c', -1.0), ('m_adp_c', -1.5), ('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef", "SubmitField('Submit') #def validate_model(self, model): # # make sure all the sheets are there", "please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)',", "in metabolite_list: raise ValidationError( 'The metabolite bigg id you specified already exists. Please", "') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding", "release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()])", "name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()])", "for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level',", "= QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)',", "IDs (e.g. 1 pep_c + 1.5 adp_c <-> 1 pyr_c + 2.0 atp_m)", "submit = SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An", "QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField,", "SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *',", "if metabolite_list else {} if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg", "for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' +", "= SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank if you only want", "parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError(", "not self.mechanism.data: raise ValidationError('You cannot specify evidence level for the mechanism without specifying", "StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *',", "part of the database, please insert it first.') def validate_mechanism(self, mechanism): if mechanism.data", "acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID (e.g. PFK1) *', validators=[DataRequired()])", "isoenzyme you specified already exists. Please choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites):", "= TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA)", "def validate_username(self, username): if username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is", "use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive',", "DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name", "use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm):", "raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] + ' is not part", "parse_input_list, ReactionParser def get_compartments(): return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return", "= SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction", "enzyme_list]) if enzyme_list else {} if isoenzyme.data in isoenzyme_list: raise ValidationError('The isoenzyme you", "bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please use", "parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list", "use a different username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1,", "Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need to specify the organism", "mechanism, you need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data", "StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments", "(e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments')", "one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm):", "flask_wtf.file import FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism,", "(e.g. CHEBI:86354, CHEBI:8685)') inchis = StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit =", "ValidationError('If you add product release order without specifying the catalyzing isoenzyme(s).') product_list =", "std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies cannot be added to reactions", "len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing", "query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs *',", "the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) ==", "http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name", "*', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg", "def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About", "QuerySelectField('Compartment name', query_factory=get_compartments, allow_blank=True) organism = QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model", "std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the above standard Gibbs energy.') if", "also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data:", "not compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1] + ' is", "'does not match any metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std):", "= QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description =", "def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def", "for the mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and", "if self.flag != 'modify' or isoenzyme.data != self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list =", "StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354,", "= StringField( 'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id):", "you add substrate binding order without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data)", "in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please specify", "metabolite' + substrate + 'does not match any metabolite in' + self.reaction_string.data +", "StringField('Encoding gene names (you need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list =", "= StringField( 'Reference for Gibbs energy (if it is equilibrator just type equilibrator,", "= QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme", "not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self,", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme", "database, please insert it first.') def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data:", "metabolite_list else {} if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg id", "PDB IDs either provide:\\n-the corresponding strains for each PDB ID;\\n-a single strain name\\n-or", "bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1) *', validators=[DataRequired()]) ec_number", "choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant = FloatField('Inhibition", "if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify the number of active", "comments = TextAreaField('Comments') submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g.", "atp), please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive',", "submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction =", "query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): model_db =", "= StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme", "= QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *',", "= Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list else {}", "isoenzyme(s) that catalyze the reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism", "from wtforms.validators import ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired from", "= StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def", "name') class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name =", "organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model', validators=[FileRequired()]) submit = SubmitField('Submit') #def", "ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description =", "enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism", "the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme", "SubmitField('Continue') def validate_model(self, model): if len(model.data) > 1: raise ValidationError('Please select only one", "query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations,", "('m_pyr_c', 1.0), ('m_atp_m', 2.0)])) for met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met)", "type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive', 'Noncompetitive'), ('Mixed', 'Mixed')]) inhibition_constant =", "phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme =", "model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def", "use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting',", "not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self,", "self.models.data: raise ValidationError( 'Gibbs energies cannot be added to reactions alone, a model", "1.5 adp_c <-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx", "+ 1.5 adp_c <-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id =", "TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this", "'The list of ChEBI ids and InChIs should have the same length. Also", "import FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction,", "app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition,", "from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism,", "QuerySelectField('Effector evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g.", "*', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme", "QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g.", "StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id =", "organism_db: raise ValidationError('An organism with that name already exists, please use another name')", "!= self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if", "as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify", "the mechanism without specifying a mechanism.') def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not", "enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select one and only one isoenzyme.')", "re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError( 'Please specify the metabolite' + met", "validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that name", "if len(enzyme.data) != 1: raise ValidationError('Please select one and only one isoenzyme.') class", "def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag grasp_id", "TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data)", "also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data:", "StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self,", "= StringField('Affected metabolite (e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition", "validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E", "username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit =", "get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos():", "= StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level =", "model with that name already exists, please use either the original name or", "each PDB ID;\\n-a single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme =", "model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos", "isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) == -1: raise", "with that name already exists, please use another name') class ModelModifyForm(FlaskForm): def __init__(self,", "+ met_compartment[0][ 1] + ' is not part of the database, please insert", "submit = SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select", "validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model", "on the model excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id", "if you only want to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit =", "enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()])", "QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if len(model.data)", "def get_models(): return Model.query def get_organisms(): return Organism.query def get_reactions(): return Reaction.query class", "different username.') class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit", "(eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites (you", "in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' + product +", "not self.enzymes.data: raise ValidationError('If you add product release order without specifying the catalyzing", "reaction)', query_factory=get_mechanisms, allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)", "as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify", "if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp id you specified already", "the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if pdb_structure_ids.data and not self.organism_name.data: raise ValidationError('If", "met, stoich_coef in stoichiometry.items(): met_compartment = re.findall('(\\w+)_(\\w+)', met) if not met_compartment: raise ValidationError(", "if self.flag != 'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list =", "query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please", "self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength):", "= StringField('Effector metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type", "the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) ==", "if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of ChEBI ids and InChIs", "def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def", "= flag grasp_id = StringField('Grasp ID (will be shown on the model excel", "class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism", "class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True) submit = SubmitField('Continue') class OrganismForm(FlaskForm): name", "validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number", "QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions =", "StringField('Activating metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant =", "string, use Bigg IDs (e.g. 1 pep_c + 1.5 adp_c <-> 1 pyr_c", "level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included in the model?', choices=[('True',", "raise ValidationError('If you specify encoding genes you must also specify the organism name.')", "FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy", "that catalyzes the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue')", "= SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select one", "EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()])", "pep_c + 1.5 adp_c <-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id", "FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy',", "constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references", "ValidationError('If you specify the number of active sites you must also specify the", "validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic =", "one and only one isoenzyme.') class SelectModelForm(FlaskForm): model = QuerySelectMultipleField('Model name *', query_factory=get_models,", "comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if self.flag == 'modify':", "you specified already exists. Please choose a different one.') def validate_bigg_id(self, bigg_id): if", "len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding strains for each", "specify the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class", "you specify encoding genes you must also specify the organism name.') def validate_uniprot_id_list(self,", "= SelectField('Is this assumption included in the model?', choices=[('True', 'True'), ('False', 'False')]) references", "PFK1) *', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name", "validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) included_in_model = SelectField('Is this assumption included", "release order without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in", "name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db: raise ValidationError('An organism with that name already", "reaction mechanism, you need to specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if", "metabolite_list: raise ValidationError( 'The metabolite bigg id you specified already exists. Please choose", "EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()])", "= QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite", "def get_organisms(): return Organism.query def get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username',", "or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in", "either the original name or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models,", "mechanism): if mechanism.data and not self.enzymes.data: raise ValidationError('If you add a reaction mechanism,", "name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that name already", "catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if", "reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if you add", "names # return 0 #validate model name # make sure kinetics1 sheet has", "info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes", "effector_met = StringField('Effector metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list')", "substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' + substrate", "the number of active sites you must also specify the organism name.') def", "raise ValidationError( 'The metabolite' + product + 'does not match any metabolite in'", "self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please use a", "sites you must also specify the organism name.') def validate_gene_names(self, gene_names): if gene_names.data", "standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism", "ValidationError('Please specify the reference for the above standard Gibbs energy.') if std_gibbs_energy_references.data and", "'Please specify the metabolite' + met + 'as metabolite_compartmentAcronym, e.g. adp_c.') compartment_db =", "= TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()])", "submit = SubmitField('Submit') class ModelForm(FlaskForm): name = StringField('Model name (e.g. E coli -", "StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired,", "1 pep_c + 1.5 adp_c <-> 1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()])", "name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class MetaboliteForm(FlaskForm): def __init__(self, data=None,", "(if you add the mechanism, you also need to add the isoenzyme(s) that", "not self.organism_name.data: raise ValidationError('If you specify encoding genes you must also specify the", "energy (if it is equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236')", "ValidationError( 'The metabolite' + substrate + 'does not match any metabolite in' +", "query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions',", "= QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models,", "atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id =", "QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s)", "DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired from app.models import Compartment, Enzyme,", "FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model name (e.g. E coli -", "inhibition_constant = FloatField('Inhibition constant (in M)', validators=[Optional()]) inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level',", "is equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments')", "*', validators=[DataRequired()]) ec_number = StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg.", "metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise", "validate_uniprot_id_list(self, uniprot_id_list): if uniprot_id_list.data and not self.organism_name.data: raise ValidationError('If you specify uniprot IDs", "well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave blank", "the organism name.') def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If", "= StringField('Activating metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant", "and not self.organism_name.data: raise ValidationError('If you specify encoding genes you must also specify", "FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\", "def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies cannot be added", "you must also specify the organism name.') def validate_gene_names(self, gene_names): if gene_names.data and", "catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) == -1:", "= SubmitField('Continue') class OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()])", "and InChIs should have the same length. Also make sure you separated each", "please insert it first.') def validate_mechanism(self, mechanism): if mechanism.data and not self.enzymes.data: raise", "TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction", "query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit =", "gene names (you need to specify the organism first)', id='gene_bigg_ids') uniprot_id_list = StringField('Uniprot", "+ self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise", "validate_enzymes(self, enzymes): if self.flag == 'modify': if len(enzymes.data) > 1: raise ValidationError('Please select", "name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model): if len(model.data) >", "PDB ID;\\n-a single strain name\\n-or no strain names.') class EnzymeInhibitionForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme", "validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']: metabolite_list = Metabolite.query.all()", "validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs", "self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references):", "DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name", "= QuerySelectMultipleField('Reactions', query_factory=get_enzyme_reaction_organisms, allow_blank=True) model_inhibitions = QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme", "energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()])", "misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments')", "= FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names,", "self.local_data = data self.flag = flag grasp_id = StringField('Grasp ID (will be shown", "data=data) self.local_data = data self.flag = flag name = StringField('Enzyme name (e.g. phosphofructokinase)", "class ModelModifyForm(FlaskForm): def __init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model", "PDB structures you must also specify the organism name') def validate_strain(self, strain): strain_list", "self.organism_name.data: raise ValidationError('If you specify PDB structures you must also specify the organism", "'Enzyme mechanism name (if you add the mechanism, you also need to add", "and not self.organism_name.data: raise ValidationError('If you specify PDB structures you must also specify", "QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description", "QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments =", "QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit =", "from flask_wtf.file import FileField, FileRequired from app.models import Compartment, Enzyme, EvidenceLevel, Mechanism, Model,", "ValidationError( 'Gibbs energies cannot be added to reactions alone, a model must be", "PDB structure', id='strain') submit = SubmitField('Submit') def validate_isoenzyme(self, isoenzyme): if self.flag != 'modify'", "= QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions", "model): if len(model.data) > 1: raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm):", "validators=[Optional()]) gene_names = StringField('Encoding gene names (you need to specify the organism first)',", "and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the above standard Gibbs", "standard Gibbs energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data:", "if mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify evidence level for the", "QuerySelectField( 'Enzyme mechanism name (if you add the mechanism, you also need to", "make sure you separated each value with a comma.') class ModelAssumptionsForm(FlaskForm): model =", "acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()]) isoenzyme = StringField('Isoenzyme (e.g. PFK1)", "the reaction (select only one) *', query_factory=get_enzymes, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_enzyme(self,", "cannot specify evidence level for the mechanism without specifying a mechanism.') def validate_subs_binding_order(self,", "StringField('Effector metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type =", "return Compartment.query def get_enzymes(): return Enzyme.query def get_enzyme_activations(): return EnzymeReactionActivation.query def get_enzyme_effectors(): return", "+ substrate + 'does not match any metabolite in' + self.reaction_string.data + '.')", "Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references =", "submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.original_username =", "(leave blank if you only want to change the enzyme info).', query_factory=get_organisms, allow_blank=True)", "grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list])", "should have the same length. Also make sure you separated each value with", "compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)') inchis", "specify the organism name') def validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data)", "name (eg. E coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites", "'modify' or grasp_id.data != self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme", "bigg IDs *', validators=[DataRequired()], id='metabolite_list') activation_constant = FloatField('Activation constant (in M)', validators=[Optional()]) activation_evidence_level", "= StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self,", "from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField,", "raise ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if", "binding order without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for substrate in", "- iteration 1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli) *',", "*', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level =", "(e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order", "model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that name already exists,", "the sheets are there and are not empty # make sure enzyme_Reaction columns", "energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength", "validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select one and only one", "self).__init__(*args, **kwargs) self.original_username = original_username def validate_username(self, username): if username.data != self.original_username: user", "= data self.flag = flag grasp_id = StringField('Grasp ID (will be shown on", "ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI IDs (e.g. CHEBI:86354, CHEBI:8685)')", "not match any metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if", "username.data != self.original_username: user = User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please", "pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID')", "the original name or another one.') class ModelFormBase(FlaskForm): model_base = QuerySelectField('Models', query_factory=get_models, allow_blank=True)", "= TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if name.data != self.local_data['name']: model_db", "name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym = StringField('Enzyme bigg_acronym (eg. PFK) *', validators=[DataRequired()])", "!= len(pdb_id_list): raise ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding strains for", "QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism", "substrate + 'does not match any metabolite in' + self.reaction_string.data + '.') def", "self.flag = flag name = StringField('Enzyme name (e.g. phosphofructokinase) *', validators=[DataRequired()]) acronym =", "DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme", "data=data) self.local_data = data self.flag = flag name = StringField('Reaction name (e.g. phosphofructokinase)", "data self.flag = flag grasp_id = StringField('Grasp ID (will be shown on the", "only want to change the enzyme info).', query_factory=get_organisms, allow_blank=True) submit = SubmitField('Continue') class", "validators=[DataRequired()]) reaction_string = StringField('Reaction string, use Bigg IDs (e.g. 1 pep_c + 1.5", "metabolite_list]) if metabolite_list else {} if grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite", "TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References,", "= FloatField('Ionic strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs", "not self.organism_name.data: raise ValidationError('If you specify PDB structures you must also specify the", "uniprot IDs you must also specify the organism name') def validate_pdb_structure_ids(self, pdb_structure_ids): if", "add substrate binding order without specifying the catalyzing isoenzyme(s).') substrate_list = parse_input_list(subs_binding_order.data) for", "name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID (e.g. pyr) *', validators=[DataRequired()])", "get_reactions(): return Reaction.query class EditProfileForm(FlaskForm): username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me',", "DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_enzymes(self, enzymes): if", "flask_wtf import FlaskForm from wtforms import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from", "evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order (e.g. adp_c, pep_c)') prod_release_order", "energy.') if std_gibbs_energy_references.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard Gibbs energy", "models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) activator_met = StringField('Activating metabolite (e.g. adp), please use", "enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit =", "corresponding strains for each PDB ID;\\n-a single strain name\\n-or no strain names.') class", "if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When", "QuerySelectMultipleField('Enzyme inhibitions', query_factory=get_enzyme_inhibitions, allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme", "> 1: raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism',", "organism first) (e.g. 3H8A, 1UCW)') strain = StringField('Strain for the PDB structure', id='strain')", "*', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if you add the", "ValidationError, DataRequired, Length, Optional from flask_wtf.file import FileField, FileRequired from app.models import Compartment,", "if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model", "def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data: raise ValidationError('Please specify the standard", "return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return", "model = QuerySelectMultipleField('Model name *', query_factory=get_models, validators=[DataRequired()]) submit = SubmitField('Continue') def validate_model(self, model):", "*', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp),", "https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)') comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme", "= User.query.filter_by(username=self.username.data).first() if user is not None: raise ValidationError('Please use a different username.')", "as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify') class SelectOrganismForm(FlaskForm): organism = QuerySelectField('Organisms (leave", "specify the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you", "= StringField('Uniprot IDs (you need to specify the organism first) (e.g. Q5FKG6, P21777)')", "info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit", "= QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp), please use bigg", "PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit') class", "product release order without specifying the catalyzing isoenzyme(s).') product_list = parse_input_list(prod_release_order.data) for product", "id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector evidence", "validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify the number", "validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if it is equilibrator just", "if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the above", "isoenzyme_list: raise ValidationError('The isoenzyme you specified already exists. Please choose a different name.')", "(e.g. 1 pep_c + 1.5 adp_c <-> 1 pyr_c + 2.0 atp_m) *',", "in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data:", "'InChIs (e.g. InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag", "= StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs *', validators=[DataRequired()], id='metabolite_list') affected_met", "query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic", "SubmitField('Submit') class EnzymeEffectorForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction = QuerySelectField('Reaction *',", "validate_strain(self, strain): strain_list = parse_input_list(strain.data) pdb_id_list = parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and", "!= self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with that", "query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *',", "a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *',", "1 pyr_c + 2.0 atp_m) *', validators=[DataRequired()]) metanetx_id = StringField('Metanetx ID') bigg_id =", "= SubmitField('Continue') class SelectIsoenzymeForm(FlaskForm): enzyme = QuerySelectMultipleField('Isoenzyme that catalyzes the reaction (select only", "query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level =", "ValidationError('Please specify the standard Gibbs energy as well.') def validate_std_gibbs_energy_ph(self, std_gibbs_energy_ph): if std_gibbs_energy_ph.data", "name.') def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If you specify", "not self.organism_name.data: raise ValidationError('If you specify the number of active sites you must", "SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError, DataRequired, Length,", "excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g. pyruvate)') bigg_id = StringField('Bigg ID", "metabolite_list: raise ValidationError( 'The metabolite grasp id you specified already exists. Please choose", "Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if it is", "def validate_prod_release_order(self, prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add product", "data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name = StringField('Enzyme", "self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with that name", "enzyme_Reaction columns have the correct names # return 0 #validate model name #", "different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you", "metanetx_id = StringField('Metanetx ID') bigg_id = StringField('Bigg ID') kegg_id = StringField('Kegg ID') compartment", "the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name (if you", "QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes,", "query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met", "GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *', validators=[DataRequired()]) submit = SubmitField('Submit') class", "= Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that name already exists, please", "different one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or bigg_id.data != self.local_data['bigg_id']:", "OrganismForm(FlaskForm): name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()]) submit = SubmitField('Submit')", "match any metabolite in' + self.reaction_string.data + '.') def validate_prod_release_order(self, prod_release_order): if prod_release_order.data", "query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()])", "get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query def get_organisms():", "validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')]) effector_evidence_level = QuerySelectField('Effector", "grasp_id = StringField('Grasp ID (will be shown on the model excel file) *',", "different one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if", "name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that", "validate_name(self, name): if name.data != self.local_data['name']: model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError(", "allow_blank=True) topic = StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()])", "coli) *', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if", "E coli) *', validators=[DataRequired()], id='organism_name') strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs =", "QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme", "ValidationError( 'The metabolite' + product + 'does not match any metabolite in' +", "it is equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236') comments =", "QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please use bigg IDs", "None: raise ValidationError('Please use a different username.') class PostForm(FlaskForm): post = TextAreaField('Say something',", "not self.models.data: raise ValidationError( 'Gibbs energies cannot be added to reactions alone, a", "def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that", "for Gibbs energy (if it is equilibrator just type equilibrator, otherwise use DOI,", "def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return EnzymeReactionOrganism.query def get_evidence_names(): return EvidenceLevel.query def", "SubmitField('Continue') def validate_enzyme(self, enzyme): if len(enzyme.data) != 1: raise ValidationError('Please select one and", "FloatField('Standard Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in", "import FloatField, IntegerField, SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from", "strain = StringField('Organism strain (e.g. MG1655)') enz_rxn_orgs = QuerySelectMultipleField('Reactions in the model', query_factory=get_enzyme_reaction_organisms,", "inhibition_evidence_level = QuerySelectField('Enzyme inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please", "assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name): if", "already exists. Please choose a different one.') def validate_bigg_id(self, bigg_id): if self.flag !=", "mechanism_evidence_level.data and not self.mechanism.data: raise ValidationError('You cannot specify evidence level for the mechanism", "StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level = QuerySelectField('Enzyme mechanism", "(in M)', validators=[Optional()]) activation_evidence_level = QuerySelectField('Activation inhibition evidence level', query_factory=get_evidence_names, allow_blank=True) references =", "allow_blank=True) model_activations = QuerySelectMultipleField('Enzyme activations', query_factory=get_enzyme_activations, allow_blank=True) model_effectors = QuerySelectMultipleField('Enzyme effectors', query_factory=get_enzyme_effectors, allow_blank=True)", "return EnzymeReactionEffector.query def get_enzyme_inhibitions(): return EnzymeReactionInhibition.query def get_enzyme_misc_infos(): return EnzymeReactionMiscInfo.query def get_enzyme_reaction_organisms(): return", "#validate model name # make sure kinetics1 sheet has the right column names", "choose a different name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise", "if bigg_id.data in metabolite_list: raise ValidationError( 'The metabolite bigg id you specified already", "__init__(self, data): FlaskForm.__init__(self, data=data) self.local_data = data name = StringField('Model name (e.g. E", "submit = SubmitField('Submit') def validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A", "= StringField('EC number *', validators=[DataRequired()]) organism_name = QuerySelectField('Organism name (eg. E coli)', query_factory=get_organisms,", "standard Gibbs energy as well.') def validate_std_gibbs_energy_ionic_strength(self, std_gibbs_energy_ionic_strength): if std_gibbs_energy_ionic_strength.data and not self.std_gibbs_energy.data:", "to reactions alone, a model must be associated as well. Please add model", "deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic", "assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence", "only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms, validators=[DataRequired()]) model = FileField('Model',", "class PostForm(FlaskForm): post = TextAreaField('Say something', validators=[ DataRequired(), Length(min=1, max=140)]) submit = SubmitField('Submit')", "encoding genes you must also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list): if", "= Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError( 'A model with that name already exists,", "grasp_id.data in metabolite_list: raise ValidationError( 'The metabolite grasp id you specified already exists.", "validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for", "of the database, please insert it first.') def validate_mechanism(self, mechanism): if mechanism.data and", "organism name.') def validate_gene_names(self, gene_names): if gene_names.data and not self.organism_name.data: raise ValidationError('If you", "and not self.enzymes.data: raise ValidationError('If you add product release order without specifying the", "grasp id you specified already exists. Please choose a different one.') def validate_bigg_id(self,", "validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data: raise ValidationError( 'Gibbs energies cannot be added to", "self.local_data['isoenzyme']: enzyme_list = Enzyme.query.all() isoenzyme_list = set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list", "Please choose a different one.') def validate_bigg_id(self, bigg_id): if self.flag != 'modify' or", "adp_c, pep_c)') prod_release_order = StringField('Product release order (e.g. atp_c, pyr_c)') std_gibbs_energy = FloatField('Standard", "StringField('Topic (e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence", "'Reference for Gibbs energy (if it is equilibrator just type equilibrator, otherwise use", "data name = StringField('Model name (e.g. E coli - iteration 1) *', validators=[DataRequired()])", "== -1: raise ValidationError( 'The metabolite' + product + 'does not match any", "= QuerySelectField('Isoenzyme *', query_factory=get_enzymes) reaction = QuerySelectField('Reaction *', query_factory=get_reactions) organism = QuerySelectField('Organism *',", "parse_input_list(inchis.data, False) if len(inchi_list) != len(chebi_list): raise ValidationError( 'The list of ChEBI ids", "coli)', query_factory=get_organisms, allow_blank=True) number_of_active_sites = IntegerField('Number of enzyme active sites (you need to", "SelectField('Is this assumption included in the model?', choices=[('True', 'True'), ('False', 'False')]) references =", "std_gibbs_energy_ph = FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs", "you specify PDB structures you must also specify the organism name') def validate_strain(self,", "validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)', validators=[Optional()]) std_gibbs_energy_ph = FloatField('pH", "if model_db: raise ValidationError( 'A model with that name already exists, please use", "allow_blank=True) mechanism_references = StringField( 'DOI for mechanism references (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236) ') mechanism_evidence_level", "the model', query_factory=get_enzyme_reaction_organisms, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit') def validate_name(self, name):", "return ModelAssumptions.query def get_models(): return Model.query def get_organisms(): return Organism.query def get_reactions(): return", "= Compartment.query.filter_by(bigg_id=met_compartment[0][1]).first() if not compartment_db: raise ValidationError('The specified compartment bigg_acronym' + met_compartment[0][ 1]", "1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise ValidationError( 'When providing PDB IDs", "uniprot_id_list = StringField('Uniprot IDs (you need to specify the organism first) (e.g. Q5FKG6,", "IDs', id='metabolite_list') inhibition_type = SelectField('Inhibition type', choices=[('Unknown', 'Unknown'), ('Competitive', 'Competitive'), ('Uncompetitive', 'Uncompetitive'), ('Noncompetitive',", "any metabolite in' + self.reaction_string.data + '.') def validate_std_gibbs_energy_std(self, std_gibbs_energy_std): if not self.models.data:", "EvidenceLevel.query def get_mechanisms(): return Mechanism.query def get_model_assumptions(): return ModelAssumptions.query def get_models(): return Model.query", "the organism first) (e.g. Q5FKG6, P21777)') pdb_structure_ids = StringField('PDB structure IDs (you need", "level', query_factory=get_evidence_names, allow_blank=True) references = StringField( 'References, please use DOI (e.g. https://doi.org/10.1093/bioinformatics/bty942, http://doi.org/10.5334/jors.236)')", "flag grasp_id = StringField('Grasp ID (will be shown on the model excel file)", "specify the catalyzing isoenzyme(s).') def validate_mechanism_evidence_level(self, mechanism_evidence_level): if mechanism_evidence_level.data and not self.mechanism.data: raise", "be shown on the model excel file) *', validators=[DataRequired()]) name = StringField('Name (e.g.", "self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite' + substrate + 'does not match", "EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector, ModelAssumptions,", "only one isoenzyme.') def validate_reaction_string(self, reaction_string): reversible, stoichiometry = ReactionParser().parse_reaction(reaction_string.data) # (True, OrderedDict([('m_pep_c',", "if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add substrate binding order without", "allow_blank=True) model_misc_infos = QuerySelectMultipleField('Enzyme misc info', query_factory=get_enzyme_misc_infos, allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions,", "MetaboliteForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag", "model?', choices=[('True', 'True'), ('False', 'False')]) references = StringField( 'References, please use DOI (e.g.", "you separated each value with a comma.') class ModelAssumptionsForm(FlaskForm): model = QuerySelectField('Model *',", "mechanism_evidence_level = QuerySelectField('Enzyme mechanism evidence level', query_factory=get_evidence_names, allow_blank=True) subs_binding_order = StringField('Substrate binding order", "self.organism_name.data: raise ValidationError('If you specify encoding genes you must also specify the organism", "parse_input_list(subs_binding_order.data) for substrate in substrate_list: if self.reaction_string.data.find(substrate) == -1: raise ValidationError( 'The metabolite'", "Gibbs energy (if it is equilibrator just type equilibrator, otherwise use DOI, https://doi.org/10.1093/bioinformatics/bty942,", "and not self.enzymes.data: raise ValidationError('If you add substrate binding order without specifying the", "structures you must also specify the organism name') def validate_strain(self, strain): strain_list =", "if organism_db: raise ValidationError('An organism with that name already exists, please use another", "SelectField, StringField, SubmitField, TextAreaField from wtforms.ext.sqlalchemy.fields import QuerySelectField, QuerySelectMultipleField from wtforms.validators import ValidationError,", "allow_blank=True) included_in_model = SelectField('Is this assumption included in the model?', choices=[('True', 'True'), ('False',", "ValidationError('Please specify the standard Gibbs energy as well.') class ModifyDataForm(FlaskForm): submit = SubmitField('Modify')", "set([enzyme.isoenzyme for enzyme in enzyme_list]) if enzyme_list else {} if isoenzyme.data in isoenzyme_list:", "energy as well.') def validate_std_gibbs_energy_references(self, std_gibbs_energy_references): if self.std_gibbs_energy.data and not std_gibbs_energy_references.data: raise ValidationError('Please", "Gibbs energy (in kJ/mol)', validators=[Optional()]) std_gibbs_energy_std = FloatField('Standard Gibbs energy standard deviation(in kJ/mol)',", "3H8A, 1UCW)') strain = StringField('Strain for the PDB structure', id='strain') submit = SubmitField('Submit')", "prod_release_order): if prod_release_order.data and not self.enzymes.data: raise ValidationError('If you add product release order", "comments = TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeActivationForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes,", "1) *', validators=[DataRequired()]) organism_name = StringField('Organism name (e.g. E coli) *', validators=[DataRequired()], id='organism_name')", "FloatField('pH for Gibbs energy', validators=[Optional()]) std_gibbs_energy_ionic_strength = FloatField('Ionic strength for Gibbs energy', validators=[Optional()])", "me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit') def __init__(self, original_username, *args, **kwargs): super(EditProfileForm, self).__init__(*args,", "one.') def validate_inchis(self, inchis): chebi_list = parse_input_list(self.chebi_ids.data) inchi_list = parse_input_list(inchis.data, False) if len(inchi_list)", "self.local_data = data self.flag = flag name = StringField('Enzyme name (e.g. phosphofructokinase) *',", "affected_met = StringField('Affected metabolite (e.g. atp), please use bigg IDs', id='metabolite_list') inhibition_type =", "reaction = QuerySelectField('Reaction *', query_factory=get_reactions, validators=[DataRequired()]) organism = QuerySelectField('Organism *', query_factory=get_organisms) models =", "name.') def validate_number_of_active_sites(self, number_of_active_sites): if number_of_active_sites.data and not self.organism_name.data: raise ValidationError('If you specify", "1: raise ValidationError('Please select only one model.') class UploadModelForm(FlaskForm): organism = QuerySelectField('Organism', query_factory=get_organisms,", "not std_gibbs_energy_references.data: raise ValidationError('Please specify the reference for the above standard Gibbs energy.')", "(e.g. allostery) *', validators=[DataRequired()]) description = TextAreaField('Description *', validators=[DataRequired()]) evidence_level = QuerySelectField('Evidence level',", "!= len(chebi_list): raise ValidationError( 'The list of ChEBI ids and InChIs should have", "raise ValidationError( 'The metabolite bigg id you specified already exists. Please choose a", "query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met = StringField('Inhibiting metabolite (e.g. adp), please", "# # make sure all the sheets are there and are not empty", "= parse_input_list(self.pdb_structure_ids.data) if len(strain_list) > 1 and len(pdb_id_list) and len(strain_list) != len(pdb_id_list): raise", "gene_names.data and not self.organism_name.data: raise ValidationError('If you specify encoding genes you must also", "ValidationError('If you specify uniprot IDs you must also specify the organism name') def", "validate_name(self, name): model_db = Model.query.filter_by(name=name.data).first() if model_db: raise ValidationError('A model with that name", "submit = SubmitField('Submit') #def validate_model(self, model): # # make sure all the sheets", "query_factory=get_reactions) organism = QuerySelectField('Organism *', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) inhibitor_met =", "= QuerySelectField('Organism name *', query_factory=get_organisms) models = QuerySelectMultipleField('Model name', query_factory=get_models, allow_blank=True) enzymes =", "TextAreaField('Comments') submit = SubmitField('Submit') class GeneForm(FlaskForm): name = StringField('Gene name (e.g. pfkA) *',", "for product in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' +", "username = StringField('Username', validators=[DataRequired()]) about_me = TextAreaField('About me', validators=[Length(min=0, max=140)]) submit = SubmitField('Submit')", "pdb_structure_ids = StringField('PDB structure IDs (you need to specify the organism first) (e.g.", "raise ValidationError( 'When providing PDB IDs either provide:\\n-the corresponding strains for each PDB", "def validate_subs_binding_order(self, subs_binding_order): if subs_binding_order.data and not self.enzymes.data: raise ValidationError('If you add substrate", "bigg_acronym' + met_compartment[0][ 1] + ' is not part of the database, please", "model_db: raise ValidationError('A model with that name already exists, please use another name')", "if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite' + product + 'does not", "self.local_data['grasp_id']: metabolite_list = Metabolite.query.all() metabolite_list = set([enzyme.grasp_id for enzyme in metabolite_list]) if metabolite_list", "Enzyme, EvidenceLevel, Mechanism, Model, Organism, Reaction, User, \\ EnzymeReactionOrganism, EnzymeReactionInhibition, EnzymeReactionActivation, \\ EnzymeReactionEffector,", "= QuerySelectField('Model *', query_factory=get_models) assumption = StringField('Assumption *', validators=[DataRequired()]) description = TextAreaField('Description *',", "__init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data) self.local_data = data self.flag = flag name =", "InChI=1S/C3H4O3/c1-2(4)3(5)6/h4H,1H2,(H,5,6), InChI=1S/C3H4O4/c1-2(4)3(5)6/h4H,1H2,(H,5,6) )') submit = SubmitField('Submit') def validate_grasp_id(self, grasp_id): if self.flag != 'modify'", "*', validators=[DataRequired()], id='metabolite_list') affected_met = StringField('Affected metabolite (e.g. atp), please use bigg IDs',", "allow_blank=True) enzymes = QuerySelectMultipleField('Isoenzyme(s) that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism =", "name already exists, please use either the original name or another one.') class", "parse_input_list(prod_release_order.data) for product in product_list: if self.reaction_string.data.find(product) == -1: raise ValidationError( 'The metabolite'", "self.organism_name.data: raise ValidationError('If you specify the number of active sites you must also", "bigg IDs *', validators=[DataRequired()], id='metabolite_list') effector_type = SelectField('Effector type', choices=[('Activating', 'Activating'), ('Inhibiting', 'Inhibiting')])", "validators=[DataRequired()]) acronym = StringField('Reaction acronym (e.g. PFK) *', validators=[DataRequired()]) grasp_id = StringField('GRASP ID", "strength for Gibbs energy', validators=[Optional()]) std_gibbs_energy_references = StringField( 'Reference for Gibbs energy (if", "Length(min=1, max=140)]) submit = SubmitField('Submit') class EnzymeForm(FlaskForm): def __init__(self, data=None, flag='insert'): FlaskForm.__init__(self, data=data)", "TextAreaField('Comments') submit = SubmitField('Submit') class EnzymeMiscInfoForm(FlaskForm): enzyme = QuerySelectField('Isoenzyme *', query_factory=get_enzymes, validators=[DataRequired()]) reaction", "allow_blank=True) model_assumptions = QuerySelectMultipleField('Model assumptions', query_factory=get_model_assumptions, allow_blank=True) comments = TextAreaField('Comments') submit = SubmitField('Submit')", "(e.g. pyr) *', validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True)", "= IntegerField('Number of enzyme active sites (you need to specify the organism first)',", "*', query_factory=get_organisms) models = QuerySelectMultipleField('Model(s)', query_factory=get_models, allow_blank=True) effector_met = StringField('Effector metabolite (e.g. adp),", "validators=[DataRequired()]) metanetx_id = StringField('MetaNetX ID') compartments = QuerySelectMultipleField('Compartments', query_factory=get_compartments, allow_blank=True) chebi_ids = StringField('ChEBI", "*', validators=[DataRequired()]) submit = SubmitField('Submit') def validate_name(self, name): organism_db = Organism.query.filter_by(name=name.data).first() if organism_db:", "specify encoding genes you must also specify the organism name.') def validate_uniprot_id_list(self, uniprot_id_list):", "in metabolite_list: raise ValidationError( 'The metabolite grasp id you specified already exists. Please", "that catalyze the reaction *', query_factory=get_enzymes, validators=[DataRequired()]) mechanism = QuerySelectField( 'Enzyme mechanism name" ]
[ "__init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation", "rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation rotation =", "stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" )", "Transform import Transform from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped", "geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message,", "TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self,", "rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation", "from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\",", "lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation return [translation.x,", "import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def", "labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform):", "data): translation = data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y, translation.z, rotation.x, rotation.y,", "def ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y, translation.z,", "as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\"", ") def ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y,", "from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as stdmessage class", "import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage,", "<gh_stars>0 from Transform import Transform from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg", "as message from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform,", "Transform from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as stdmessage", "TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7,", "message from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__(", "translation = data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y, translation.z, rotation.x, rotation.y, rotation.z,", "from Transform import Transform from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import", "= data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y, translation.z, rotation.x, rotation.y, rotation.z, rotation.w]", "LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as stdmessage class TransformStamped(Transform): def __init__(self):", "lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation return", "import Transform from labstreaminglayer_ros.msg import LSLTransformStamped as message from geometry_msgs.msg import TransformStamped as", "self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation", "def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data):", "class TransformStamped(Transform): def __init__(self): super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def", "ToLSL(self, data): translation = data.transform.translation rotation = data.transform.rotation return [translation.x, translation.y, translation.z, rotation.x,", "super(Transform, self).__init__( commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation =", "commonType=\"TransformStamped\", rosType=message, rosStdType=stdmessage, lslChannels=7, lslType=\"float32\" ) def ToLSL(self, data): translation = data.transform.translation rotation" ]
[ "3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58]", "-*- from jd_assistant import Assistant if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode()", "# 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') #", "\"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59]", "asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58]", "asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() #", "asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3,", "__name__ == '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666')", "登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功!", "2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False)", "Assistant if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() #", "asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 #", "# 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19", "retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功", "<reponame>arvinzhang815/jd-assistant<filename>main.py<gh_stars>1-10 #!/usr/bin/env python # -*- coding:utf-8 -*- from jd_assistant import Assistant if __name__", "-*- coding:utf-8 -*- from jd_assistant import Assistant if __name__ == '__main__': asst =", "添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id", "[2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************ 订单号:811545xxxxx----下单时间:2018-10-19 02:38:59----商品列表:1626336666 x 1----订单状态:等待付款----总金额:89.90元----付款方式:在线支付 \"\"\"", "[2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx", "# 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5)", "area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单", "# 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\"", "02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************", "asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) #", "00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58]", "02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59]", "if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车", "asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单", "interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19", "asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821')", "== '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') #", "清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666',", "# asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500',", "输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单……", "jd_assistant import Assistant if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆", "python # -*- coding:utf-8 -*- from jd_assistant import Assistant if __name__ == '__main__':", "# 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id #", "1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************ 订单号:811545xxxxx----下单时间:2018-10-19 02:38:59----商品列表:1626336666 x 1----订单状态:等待付款----总金额:89.90元----付款方式:在线支付", "= Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式:", "coding:utf-8 -*- from jd_assistant import Assistant if __name__ == '__main__': asst = Assistant()", "扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order()", "'__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车", "3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单", "# asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功", "#!/usr/bin/env python # -*- coding:utf-8 -*- from jd_assistant import Assistant if __name__ ==", "# 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 #", "# -*- coding:utf-8 -*- from jd_assistant import Assistant if __name__ == '__main__': asst", "# 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 #", "asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19", "# 查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车", "import Assistant if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart()", "1.直接提交订单 # asst.submit_order() # 2.有货时提交订单 asst.submit_order_by_stock(sku_id='1626336666', area='1_2802_2821') # 监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19", "# 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: # 1.直接提交订单 # asst.submit_order() # 2.有货时提交订单", "[2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19", "购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************ 订单号:811545xxxxx----下单时间:2018-10-19", "02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************ 订单号:811545xxxxx----下单时间:2018-10-19 02:38:59----商品列表:1626336666 x", "查询未付款订单 \"\"\" 输出实例: [2018-10-19 02:38:58] 登录成功 [2018-10-19 02:38:58] 购物车清空成功 [2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19", "from jd_assistant import Assistant if __name__ == '__main__': asst = Assistant() asst.login_by_QRcode() #", "监控的商品id和地址id # 3.定时提交订单 # asst.submit_order_by_time(buy_time='2018-10-19 00:00:00.500', retry=3, interval=5) asst.get_order_info(unpaid=False) # 查询未付款订单 \"\"\" 输出实例:", "Assistant() asst.login_by_QRcode() # 扫码登陆 asst.clear_cart() # 清空购物车 asst.add_item_to_cart(sku_id='1626336666') # 添加到购物车 # 3种订单提交方式: #", "[2018-10-19 02:38:58] 1626336666已成功加入购物车 [2018-10-19 02:38:59] 1626336666有货了,正在提交订单…… [2018-10-19 02:38:59] 订单提交成功! 订单号:811545xxxxx ************************订单列表页查询************************ 订单号:811545xxxxx----下单时间:2018-10-19 02:38:59----商品列表:1626336666" ]
[ "data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket,", ".field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org,", "data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry: \"+ str(i))", "SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for", "class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i", "DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in", "import ConnData import pandas import os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS", ".field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry: \"+ str(i)) continue", "#influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data", "influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\",", ".tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\", "influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName)", "os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName):", "try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\", "fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try:", "pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\", "init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)):", ".time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry: \"+ str(i)) continue return True", ".field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry: \"+", "self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\", "\"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\",", "ConnData import pandas import os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class", "import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data =", "= pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p =", "import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS)", "pandas import os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def", "data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p", "for i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\",", ".field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except:", "data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p)", "(len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\",", "write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\",", "from datahandler import ConnData import pandas import os #influx import influxdb_client from influxdb_client.client.write_api", "data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry: \"+ str(i)) continue return", "= self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\")", "datahandler import ConnData import pandas import os #influx import influxdb_client from influxdb_client.client.write_api import", "from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api", "range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\", "def init(self, fileName): data = pandas.read_csv(fileName) write_api = self.influx_client.write_api(write_options=SYNCHRONOUS) for i in range", "in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\",", "import os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self,", "import pandas import os #influx import influxdb_client from influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData):", "\\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\", "data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at entry:", "p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\",", "= influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\", ".field(\"power\", data[\"power\"][i])\\ .field(\"temp\", data[\"temp\"][i])\\ .field(\"humidity\", data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i])", ".field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed at", "data[\"humidity\"][i])\\ .field(\"light\", data[\"light\"][i])\\ .field(\"CO2\", data[\"CO2\"][i])\\ .field(\"dust\", data[\"dust\"][i])\\ .time(data[\"time\"][i]) write_api.write(bucket=self.influx_bucket, org=self.influx_org, record=p) except: print(\"failed", "influxdb_client.client.write_api import SYNCHRONOUS class DataLoader(ConnData): def init(self, fileName): data = pandas.read_csv(fileName) write_api =", "i in range (len(data)): try: p = influxdb_client.Point(\"test_Mote\")\\ .tag(\"type\", \"multi_sensor_dev\") \\ .field(\"power\", data[\"power\"][i])\\" ]
[ "player in self.players]: return f\"Player {player_name} is not in the guild.\" player =", "import Player class Guild: def __init__(self, name: str): self.name = name self.players: list", "player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info()) guild = Guild(\"UGT\") print(guild.assign_player(player))", "player.guild == \"Unaffiliated\": return f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild =", "in self.players]: return f\"Player {player_name} is not in the guild.\" player = [player", "name: str): self.name = name self.players: list = [] def assign_player(self, player: Player):", "def __init__(self, name: str): self.name = name self.players: list = [] def assign_player(self,", "f\"Player {player_name} is not in the guild.\" player = [player for player in", "Player class Guild: def __init__(self, name: str): self.name = name self.players: list =", "= name self.players: list = [] def assign_player(self, player: Player): if player in", "is in another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player {player.name} to", "f\"Player {player.name} is already in the guild.\" if not player.guild == \"Unaffiliated\": return", "been removed from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player in", "guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\"", "in the guild.\" if not player.guild == \"Unaffiliated\": return f\"Player {player.name} is in", "player in self.players if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has been", "already in the guild.\" if not player.guild == \"Unaffiliated\": return f\"Player {player.name} is", "the guild.\" if not player.guild == \"Unaffiliated\": return f\"Player {player.name} is in another", "return f\"Player {player_name} is not in the guild.\" player = [player for player", "for player in self.players if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has", "name self.players: list = [] def assign_player(self, player: Player): if player in self.players:", "{player_name} is not in the guild.\" player = [player for player in self.players", "Player): if player in self.players: return f\"Player {player.name} is already in the guild.\"", "self.players]: return f\"Player {player_name} is not in the guild.\" player = [player for", "guild_info(self): players_details = \"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\"", "guild {self.name}\" def kick_player(self, player_name: str): if player_name not in [player.name for player", "for player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50,", "self.players.remove(player) return f\"Player {player.name} has been removed from the guild.\" def guild_info(self): players_details", "return f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome", "Guild: def __init__(self, name: str): self.name = name self.players: list = [] def", "[player for player in self.players if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name}", "if player_name not in [player.name for player in self.players]: return f\"Player {player_name} is", "{player.name} has been removed from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for", "guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player {player.name} to the guild {self.name}\"", "self.players.append(player) player.guild = self.name return f\"Welcome player {player.name} to the guild {self.name}\" def", "in self.players: return f\"Player {player.name} is already in the guild.\" if not player.guild", "f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info()) guild = Guild(\"UGT\")", "player_name not in [player.name for player in self.players]: return f\"Player {player_name} is not", "__init__(self, name: str): self.name = name self.players: list = [] def assign_player(self, player:", "in [player.name for player in self.players]: return f\"Player {player_name} is not in the", "return f\"Player {player.name} has been removed from the guild.\" def guild_info(self): players_details =", "from guild_system_07.project.player import Player class Guild: def __init__(self, name: str): self.name = name", "self.name return f\"Welcome player {player.name} to the guild {self.name}\" def kick_player(self, player_name: str):", "f\"Player {player.name} has been removed from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info()", "[] def assign_player(self, player: Player): if player in self.players: return f\"Player {player.name} is", "self.name = name self.players: list = [] def assign_player(self, player: Player): if player", "if player in self.players: return f\"Player {player.name} is already in the guild.\" if", "return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20))", "player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed from the guild.\"", "player.guild = self.name return f\"Welcome player {player.name} to the guild {self.name}\" def kick_player(self,", "== \"Unaffiliated\": return f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild = self.name", "player_name: str): if player_name not in [player.name for player in self.players]: return f\"Player", "player: Player): if player in self.players: return f\"Player {player.name} is already in the", "player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100)", "self.players: return f\"Player {player.name} is already in the guild.\" if not player.guild ==", "def guild_info(self): players_details = \"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\" \\", "{self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info()) guild", "not in [player.name for player in self.players]: return f\"Player {player_name} is not in", "def assign_player(self, player: Player): if player in self.players: return f\"Player {player.name} is already", "another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player {player.name} to the guild", "has been removed from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player", "is not in the guild.\" player = [player for player in self.players if", "for player in self.players]: return f\"Player {player_name} is not in the guild.\" player", "self.players if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed from", "players_details = \"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player", "in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield", "f\"Welcome player {player.name} to the guild {self.name}\" def kick_player(self, player_name: str): if player_name", "assign_player(self, player: Player): if player in self.players: return f\"Player {player.name} is already in", "\"Unaffiliated\": return f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild = self.name return", "the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player in self.players]) return f\"Guild:", "{self.name}\" def kick_player(self, player_name: str): if player_name not in [player.name for player in", "[player.name for player in self.players]: return f\"Player {player_name} is not in the guild.\"", "if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed from the", "in self.players if player.name == player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed", "from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player in self.players]) return", "f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info())", "{player.name} is already in the guild.\" if not player.guild == \"Unaffiliated\": return f\"Player", "in the guild.\" player = [player for player in self.players if player.name ==", "the guild {self.name}\" def kick_player(self, player_name: str): if player_name not in [player.name for", "if not player.guild == \"Unaffiliated\": return f\"Player {player.name} is in another guild.\" self.players.append(player)", "str): if player_name not in [player.name for player in self.players]: return f\"Player {player_name}", "return f\"Player {player.name} is already in the guild.\" if not player.guild == \"Unaffiliated\":", "return f\"Welcome player {player.name} to the guild {self.name}\" def kick_player(self, player_name: str): if", "= [] def assign_player(self, player: Player): if player in self.players: return f\"Player {player.name}", "{player.name} to the guild {self.name}\" def kick_player(self, player_name: str): if player_name not in", "str): self.name = name self.players: list = [] def assign_player(self, player: Player): if", "= Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info()) guild = Guild(\"UGT\") print(guild.assign_player(player)) print(guild.guild_info())", "is already in the guild.\" if not player.guild == \"Unaffiliated\": return f\"Player {player.name}", "in another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player {player.name} to the", "self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\",", "def kick_player(self, player_name: str): if player_name not in [player.name for player in self.players]:", "kick_player(self, player_name: str): if player_name not in [player.name for player in self.players]: return", "removed from the guild.\" def guild_info(self): players_details = \"\".join([player.player_info() for player in self.players])", "guild.\" if not player.guild == \"Unaffiliated\": return f\"Player {player.name} is in another guild.\"", "class Guild: def __init__(self, name: str): self.name = name self.players: list = []", "the guild.\" player = [player for player in self.players if player.name == player_name][0]", "not in the guild.\" player = [player for player in self.players if player.name", "f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player", "list = [] def assign_player(self, player: Player): if player in self.players: return f\"Player", "player {player.name} to the guild {self.name}\" def kick_player(self, player_name: str): if player_name not", "\\ f\"{players_details}\" player = Player(\"George\", 50, 100) print(player.add_skill(\"Shield Break\", 20)) print(player.player_info()) guild =", "== player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed from the guild.\" def", "= \"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player =", "{player.name} is in another guild.\" self.players.append(player) player.guild = self.name return f\"Welcome player {player.name}", "guild.\" player = [player for player in self.players if player.name == player_name][0] self.players.remove(player)", "= [player for player in self.players if player.name == player_name][0] self.players.remove(player) return f\"Player", "player_name][0] self.players.remove(player) return f\"Player {player.name} has been removed from the guild.\" def guild_info(self):", "not player.guild == \"Unaffiliated\": return f\"Player {player.name} is in another guild.\" self.players.append(player) player.guild", "guild_system_07.project.player import Player class Guild: def __init__(self, name: str): self.name = name self.players:", "player in self.players: return f\"Player {player.name} is already in the guild.\" if not", "= self.name return f\"Welcome player {player.name} to the guild {self.name}\" def kick_player(self, player_name:", "player = [player for player in self.players if player.name == player_name][0] self.players.remove(player) return", "to the guild {self.name}\" def kick_player(self, player_name: str): if player_name not in [player.name", "self.players: list = [] def assign_player(self, player: Player): if player in self.players: return", "\"\".join([player.player_info() for player in self.players]) return f\"Guild: {self.name}\\n\" \\ f\"{players_details}\" player = Player(\"George\",", "<gh_stars>1-10 from guild_system_07.project.player import Player class Guild: def __init__(self, name: str): self.name =" ]
[ "complex and innovative infrastructure layer that radically simplifies the development of any Blockchain", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from", "cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum", "construct object with mandatory attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() #", "2.0 is a complex and innovative infrastructure layer that radically simplifies the development", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash']", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import", "assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] =", "TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self):", "Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist", "of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from", "tokens and coins forwardings, callback functionalities, and much more. # noqa: E501 The", "import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import", "2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis", "with the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints", "of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice", "a complex and innovative infrastructure layer that radically simplifies the development of any", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin']", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin", "The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\"", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin", "and innovative infrastructure layer that radically simplifies the development of any Blockchain and", "unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum']", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass", "the development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and", "is a complex and innovative infrastructure layer that radically simplifies the development of", "Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with", "callback functionalities, and much more. # noqa: E501 The version of the OpenAPI", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from", "with mandatory attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501", "applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts", "Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications. Crypto", "by: https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin", "REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts", "version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test", "automatic tokens and coins forwardings, callback functionalities, and much more. # noqa: E501", "raw data, automatic tokens and coins forwardings, callback functionalities, and much more. #", "# model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass if __name__ == '__main__': unittest.main()", "Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and", "object with mandatory attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa:", "development of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data,", "and data, raw data, automatic tokens and coins forwardings, callback functionalities, and much", "Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis from", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] =", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] =", "simplifies the development of any Blockchain and Crypto related applications. Organized around REST,", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash']", "related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum", "class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def", "# FIXME: construct object with mandatory attributes with example values # model =", "more. # noqa: E501 The version of the OpenAPI document: 2.0.0 Contact: <EMAIL>", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import", "layer that radically simplifies the development of any Blockchain and Crypto related applications.", "and crypto experts with the development of their blockchain applications. Crypto APIs 2.0", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin']", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin", "can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from", "both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import", "provides unified endpoints and data, raw data, automatic tokens and coins forwardings, callback", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific", "noqa: E501 The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by:", "\"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes with example values #", "Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic", "functionalities, and much more. # noqa: E501 The version of the OpenAPI document:", "novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of their blockchain applications.", "radically simplifies the development of any Blockchain and Crypto related applications. Organized around", "unified endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities,", "OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import unittest", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit", "<EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin", "their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data,", "FIXME: construct object with mandatory attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific()", "<gh_stars>0 \"\"\" CryptoAPIs Crypto APIs 2.0 is a complex and innovative infrastructure layer", "the development of any Blockchain and Crypto related applications. Organized around REST, Crypto", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import", "setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class", "the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import", "APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the", "unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\"", "endpoints and data, raw data, automatic tokens and coins forwardings, callback functionalities, and", "values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass if __name__ == '__main__':", "blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic", "and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin']", "2.0 provides unified endpoints and data, raw data, automatic tokens and coins forwardings,", "forwardings, callback functionalities, and much more. # noqa: E501 The version of the", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] =", "pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with", "def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase):", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin", "that radically simplifies the development of any Blockchain and Crypto related applications. Organized", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] =", "import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from", "testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes with example values", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin", "example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass if __name__ ==", "innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] =", "\"\"\" import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum", "def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct", "stubs\"\"\" def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME:", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout", "data, raw data, automatic tokens and coins forwardings, callback functionalities, and much more.", "experts with the development of their blockchain applications. Crypto APIs 2.0 provides unified", "E501 The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin']", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin", "of their blockchain applications. Crypto APIs 2.0 provides unified endpoints and data, raw", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from", "with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass if __name__", "around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto", "test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" #", "attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass if", "data, automatic tokens and coins forwardings, callback functionalities, and much more. # noqa:", "and much more. # noqa: E501 The version of the OpenAPI document: 2.0.0", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout']", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] =", "APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the", "2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development", "sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash", "Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies", "document: 2.0.0 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" import sys import unittest import", "Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and", "and coins forwardings, callback functionalities, and much more. # noqa: E501 The version", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from", "tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes", "Generated by: https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import", "pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes with", "APIs 2.0 provides unified endpoints and data, raw data, automatic tokens and coins", "# noqa: E501 The version of the OpenAPI document: 2.0.0 Contact: <EMAIL> Generated", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic']", "development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs", "coins forwardings, callback functionalities, and much more. # noqa: E501 The version of", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vout import", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def tearDown(self):", "\"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass def tearDown(self): pass def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test", "\"\"\" CryptoAPIs Crypto APIs 2.0 is a complex and innovative infrastructure layer that", "mandatory attributes with example values # model = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific() # noqa: E501 pass", "CryptoAPIs Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes with example values # model", "import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import", "any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout", "= GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] =", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin import", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin", "import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin'] =", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic_gas_price import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_litecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash'] =", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\"", "crypto experts with the development of their blockchain applications. Crypto APIs 2.0 provides", "infrastructure layer that radically simplifies the development of any Blockchain and Crypto related", "much more. # noqa: E501 The version of the OpenAPI document: 2.0.0 Contact:", "globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassicGasPrice']", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dogecoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_ethereum_classic import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic", "from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self): pass", "https://openapi-generator.tech \"\"\" import sys import unittest import cryptoapis from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from", "def testGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(self): \"\"\"Test GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific\"\"\" # FIXME: construct object with mandatory attributes with example", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDashVout globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDogecoin globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereum globals()['GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic'] = GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificEthereumClassic", "cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_bitcoin_cash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificBitcoinCash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificDash from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific_dash_vin", "applications. Crypto APIs 2.0 provides unified endpoints and data, raw data, automatic tokens", "GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecificLitecoin from cryptoapis.model.get_transaction_details_by_transaction_id_response_item_blockchain_specific import GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific class TestGetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific(unittest.TestCase): \"\"\"GetTransactionDetailsByTransactionIDResponseItemBlockchainSpecific unit test stubs\"\"\" def setUp(self):", "enthusiasts and crypto experts with the development of their blockchain applications. Crypto APIs" ]
[ "computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self,", "setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance,", "PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as", "fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field]", "update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for field_name, value in input_dict.items(): field", "= fae for field in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value))", "in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict):", "super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for fieldname, value", "other): return any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields )", "self._get_value(other, field) for field in self._fields if field.name in instance and field.name in", "= self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self): return len(self._fields) def __getitem__(self,", "instance, other): return any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields", "NotImplementedError # # Used in unittests # def as_dict(self, instance): return { field.name:", "else self.__class__ return field_group_class( [ field.derive(transformation) for field in self._fields ] ) def", "__init__(self, fields, container_type): self._fields = fields self._container_type = container_type def __iter__(self): self._current_field_index =", "TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with", "__init__(self, fields, container_type=None): container_type = dict if not container_type else container_type super().__init__(fields, container_type)", "ex)) def _get_field_index(self, field): for i, item in enumerate(self._fields): if item == field:", "result def __len__(self): return len(self._fields) def __getitem__(self, key): for field in self._fields: if", "self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation", "field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance, key) def set_value(self,", "raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setattr(instance, key, value) class", "return result def __len__(self): return len(self._fields) def __getitem__(self, key): for field in self._fields:", "field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for field in self._fields ] )", "def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance,", "return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance, field): if", "return len(self._fields) def __getitem__(self, key): for field in self._fields: if field.name == key:", "key): return getitem(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed:", "OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for fieldname, value in", "input_dict): with field_errors_check() as errors: for field_name, value in input_dict.items(): field = self[field_name]", "else: errors[field] = fae def set_value(self, instance, field, value): raise NotImplementedError def _mutator(self,", "!= self._get_value(other, field) for field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict):", "instance, key): raise NotImplementedError # # Used in unittests # def as_dict(self, instance):", "self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self): return len(self._fields) def __getitem__(self, key):", "per_field_map): with field_errors_check() as errors: for fieldname, value in instance.items(): field = self[fieldname]", "raise except Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value):", "return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self,", "field = self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception,", "field in enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field break def derive(self,", "key): raise NotImplementedError # # Used in unittests # def as_dict(self, instance): return", "_ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple)", "def __init__(self, fields, container_type): self._fields = fields self._container_type = container_type def __iter__(self): self._current_field_index", "len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict if not container_type", "try: if field.name in input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict)", "raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields,", "_accessor(self, instance, key): return getattr(instance, key) def set_value(self, instance, field, value): try: if", "if field.name in instance ) def instances_differ(self, instance, other): return any( self._get_value(instance, field)", "key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae for field in self._fields:", "def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index +=", "self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self,", "= field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise", "try: if not field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance,", "value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with", "AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else: errors[field] = fae def", "ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) def empty_instance(self): return", "value): try: if not field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field) return", "import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields =", "return self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError # # Used in", "self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self, instance, field): index,", "= field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance):", ") def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field) for", "errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item in enumerate(self._fields): if item ==", "in input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except", "name.' # replace field for i, field in enumerate(self._fields): if field.name == key:", "i, item return None, None def _type_cast(self, input_dict): cast_values = [] with field_errors_check()", "NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for field, destination_field in", "in unittests # def as_dict(self, instance): return { field.name: self._get_value(instance, field) for field", "match field name.' # replace field for i, field in enumerate(self._fields): if field.name", "collections import OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check,", "logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields self._container_type = container_type", "= 0 return self def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result", "input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field,", "def _mutator(self, instance, key, value): return setitem(instance, key, value) def empty_instance(self): return [None]", "self.set_value(instance, field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign", "fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance,", "raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS", "values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key) def", "def as_dict(self, instance): return { field.name: self._get_value(instance, field) for field in self._fields }", "[ field.derive(transformation) for field in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError", "return setitem(instance, key, value) def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def", "input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance,", "set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance,", "SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key):", "super().__init__(fields, list) def set_value(self, instance, field, value): try: if not field.is_computed: value =", "if item == field: return i, item return None, None def _type_cast(self, input_dict):", "field_group_class if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for field in self._fields", "instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field) for field in", "tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for field_name,", "self._fields = fields self._container_type = container_type def __iter__(self): self._current_field_index = 0 return self", "if field.name in input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name,", "def __getitem__(self, key): for field in self._fields: if field.name == key: return field", "fields): super().__init__(fields, list) def set_value(self, instance, field, value): try: if not field.is_computed: value", "def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check()", "__getitem__(self, key): for field in self._fields: if field.name == key: return field raise", "index, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex) def", "instance, key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return", "if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self, instance, key):", "def set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) return", "empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type =", "for field in self._fields if field.name in instance and field.name in other )", "<NAME> 2017' \"\"\" \"\"\" import logging from collections import OrderedDict from operator import", "container_type): self._fields = fields self._container_type = container_type def __iter__(self): self._current_field_index = 0 return", ">= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return result def", "\"\"\" \"\"\" import logging from collections import OrderedDict from operator import getitem, setitem", "# replace field for i, field in enumerate(self._fields): if field.name == key: self._fields[i]", "with field_errors_check() as errors: for field_name, value in input_dict.items(): field = self[field_name] try:", "_type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value) for fieldname, value in input_dict.items()", "'Key does not match field name.' # replace field for i, field in", "def __setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key does not match field", "return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key):", "field) != self._get_value(other, field) for field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self,", "DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError", "errors: for field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except", "as errors: for field_name, value in input_dict.items(): field = self[field_name] try: self.set_value(instance, field,", "instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields if field.name in", "FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field):", "= input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae:", "field for i, field in enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field", "except FieldAssignmentError as fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value = (", "instance, input_dict): with field_errors_check() as errors: for field_name, value in input_dict.items(): field =", "if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for field in self._fields ]", "field_group_class=None): transformation = copy_field if transformation is None else transformation field_group_class = field_group_class", "def set_value(self, instance, field, value): raise NotImplementedError def _mutator(self, instance, key, value): raise", "input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as fae: if", "field_errors_check() as errors: for field in self._fields: try: if field.name in input_dict: raw_value", "!= self._get_value(other, field) for field in self._fields if field.name in instance and field.name", "fae def set_value(self, instance, field, value): raise NotImplementedError def _mutator(self, instance, key, value):", "input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError", "self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return", "def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self,", "not field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index, value)", "destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def", "in enumerate(self._fields): if item == field: return i, item return None, None def", "_group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance, key)", "def set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) index,", "__next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1", "key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name,", "instance, key): return getattr(instance, key) def set_value(self, instance, field, value): try: if not", "def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for field, destination_field in per_field_map.items():", "per_field_map): with field_errors_check() as errors: for field, destination_field in per_field_map.items(): try: yield field,", "raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) class", "copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields", "ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key, value)", "def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def", "getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG", "except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item in", "errors: for field in self._fields: try: if field.name in input_dict: raw_value = input_dict[field.name]", "self._get_value(instance, field) != self._get_value(other, field) for field in self._fields if field.name in instance", "as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item in enumerate(self._fields): if", "[None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict if", "input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map):", "if not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def", "for fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae:", "except FieldAssignmentError as fae: errors[field] = fae for field in self._fields: try: computed_value", "def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as", "{ field.name: self._get_value(instance, field) for field in self._fields } def instances_differ(self, instance, other):", "[] with field_errors_check() as errors: for fieldname, field, value in field_and_value: try: key_values.append((fieldname,", "import OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS", "== key: self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None): transformation = copy_field", "def _get_field_index(self, field): for i, item in enumerate(self._fields): if item == field: return", "any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields ) class SequenceFieldGroup(FieldGroup):", "assert key == replacement_field.name, 'Key does not match field name.' # replace field", "= [] with field_errors_check() as errors: for field in self._fields: try: if field.name", "field)) for field in self._fields if field.name in instance ) def instances_differ(self, instance,", "as fae: errors[field] = fae for field in self._fields: try: computed_value = field.get_value(self,", "destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error:", "for field_name, value in input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value) except", "field.name == key: self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None): transformation =", "result = self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self): return len(self._fields) def", "field name.' # replace field for i, field in enumerate(self._fields): if field.name ==", "errors[field] = fae def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value) for", "return self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance, key) def set_value(self, instance,", "return any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields if field.name", "return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field,", "other): return any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields if", "for field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError", "field_errors_check() as errors: for field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field),", "in instance.items(): field = self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError as", "2017' \"\"\" \"\"\" import logging from collections import OrderedDict from operator import getitem,", "value): try: if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value) except", "computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance,", "for fieldname, value in instance.items(): field = self[fieldname] try: yield field, value, per_field_map.get(field)", "FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) def empty_instance(self):", "input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key)", "class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check()", "fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value)", "def _group_get_value(self, instance, field): index, _ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup):", "field) def _accessor(self, instance, key): raise NotImplementedError # # Used in unittests #", "self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex)", "None else transformation field_group_class = field_group_class if field_group_class else self.__class__ return field_group_class( [", "with field_errors_check() as errors: for fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value)))", "instance, field, value): raise NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError def", "field_and_value = ( (fieldname, self[fieldname], value) for fieldname, value in input_dict.items() ) key_values", "index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance,", "field): if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self, instance,", "return i, item return None, None def _type_cast(self, input_dict): cast_values = [] with", "in self._fields } def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other,", "self def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index", "_group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance, field): if field.is_computed: return field.get_value(self,", "errors[field] = fae def set_value(self, instance, field, value): raise NotImplementedError def _mutator(self, instance,", "value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value", "def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field, value): try: if not", "container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name)", "instance, key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields,", "does not match field name.' # replace field for i, field in enumerate(self._fields):", "container_type = dict if not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict):", "value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def", "field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return", "ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self,", "_get_field_index(self, field): for i, item in enumerate(self._fields): if item == field: return i,", "None, None def _type_cast(self, input_dict): cast_values = [] with field_errors_check() as errors: for", "field.name) def _accessor(self, instance, key): return getattr(instance, key) def set_value(self, instance, field, value):", "StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self): return len(self._fields)", "field.name, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex) def", "not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except", "__copyright__ = 'Copyright(c) <NAME> 2017' \"\"\" \"\"\" import logging from collections import OrderedDict", "yield field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae def _type_cast(self,", "value) for fieldname, value in input_dict.items() ) key_values = [] with field_errors_check() as", "def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors:", "return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self, instance, field):", "return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance,", "in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae for", "instance, key, value): raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def", "return self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance, key) def set_value(self, instance,", "LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else: errors[field] = fae def set_value(self,", "{}'.format(value, field_name)) else: errors[field] = fae def set_value(self, instance, field, value): raise NotImplementedError", "field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return", "per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value =", "return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key):", "self._fields } def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field)", "errors: for field_name, value in input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value)", "derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation is None else transformation field_group_class", "transformation is None else transformation field_group_class = field_group_class if field_group_class else self.__class__ return", "self[fieldname], value) for fieldname, value in input_dict.items() ) key_values = [] with field_errors_check()", "instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance, key) def", "raise NotImplementedError def _get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance) else: return", "NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list)", "FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup):", "as fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname],", "except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values)", "field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key == replacement_field.name,", "field_name, value in input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError", "Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance,", "in input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as fae:", "as errors: for field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field", "== key: return field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert", "replacement_field.name, 'Key does not match field name.' # replace field for i, field", "ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance, field):", "field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex:", "DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields,", "_accessor(self, instance, key): return getitem(instance, key) def set_value(self, instance, field, value): try: if", "return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field in", "copy_field if transformation is None else transformation field_group_class = field_group_class if field_group_class else", "field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index, value) except", "key): return getattr(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed:", "if self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return", "not match field name.' # replace field for i, field in enumerate(self._fields): if", "<gh_stars>0 __copyright__ = 'Copyright(c) <NAME> 2017' \"\"\" \"\"\" import logging from collections import", "def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def", "as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self,", "value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae", "field.derive(transformation) for field in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def", "field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as", "self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return", "def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for fieldname, value in instance.items():", "a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class", "if transformation is None else transformation field_group_class = field_group_class if field_group_class else self.__class__", "= field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as", ") class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self,", "self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field,", "raise NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self): return self._container_type()", "field = self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field]", "__setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key does not match field name.'", "fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance,", "self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return result", "{} to {}'.format(value, field_name)) else: errors[field] = fae def set_value(self, instance, field, value):", "isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else: errors[field] = fae", "ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def", "key_values = [] with field_errors_check() as errors: for fieldname, field, value in field_and_value:", "in enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field break def derive(self, transformation=None,", "field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex))", "i, item in enumerate(self._fields): if item == field: return i, item return None,", "setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG =", "i, field in enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field break def", "field.name in input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value)))", "key) def _group_get_value(self, instance, field): index, _ = self._get_field_index(field) return self._accessor(instance, index) class", "container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return", "input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae)", "= ( (fieldname, self[fieldname], value) for fieldname, value in input_dict.items() ) key_values =", "FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def", "cast_values = [] with field_errors_check() as errors: for field in self._fields: try: if", "__init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as", "for field in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self,", "* len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict if not", "field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance, key) def set_value(self,", "key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map):", "field in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass", "field.name in instance ) def instances_differ(self, instance, other): return any( self._get_value(instance, field) !=", "field in self._fields if field.name in instance ) def instances_differ(self, instance, other): return", "value): raise NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self): return", "key: self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None): transformation = copy_field if", "not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self,", "return None, None def _type_cast(self, input_dict): cast_values = [] with field_errors_check() as errors:", "self._fields if field.name in instance ) def instances_differ(self, instance, other): return any( self._get_value(instance,", "key, value): return setitem(instance, key, value) def empty_instance(self): return [None] * len(self) class", "def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def", "len(self._fields) def __getitem__(self, key): for field in self._fields: if field.name == key: return", "as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for", "from collections import OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError,", "fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance,", "__init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field, value): try: if not field.is_computed:", "return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict", "key == replacement_field.name, 'Key does not match field name.' # replace field for", "LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields self._container_type", "super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for", "fieldname, value in input_dict.items() ) key_values = [] with field_errors_check() as errors: for", "_get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field) def", "= fae def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value) for fieldname,", "instance.items(): field = self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError as fae:", "fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for fieldname,", "field.name) def _accessor(self, instance, key): return getitem(instance, key) def set_value(self, instance, field, value):", "except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance,", "raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) def", "fae for field in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except", "self._container_type = container_type def __iter__(self): self._current_field_index = 0 return self def __next__(self): if", "logging from collections import OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions import", "except Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return", "key): for field in self._fields: if field.name == key: return field raise KeyError('{}", "Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item in enumerate(self._fields):", "instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name,", "# def as_dict(self, instance): return { field.name: self._get_value(instance, field) for field in self._fields", "field in self._fields: try: if field.name in input_dict: raw_value = input_dict[field.name] else: raw_value", "FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields self._container_type = container_type def __iter__(self):", "getitem(instance, key) def _group_get_value(self, instance, field): index, _ = self._get_field_index(field) return self._accessor(instance, index)", "in self._fields: if field.name == key: return field raise KeyError('{} not found.'.format(key)) def", "def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance, field): if field.is_computed: return", "else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field):", "FieldAssignmentError as fae: errors[field] = fae def _type_cast(self, input_dict): field_and_value = ( (fieldname,", "field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] =", "field_errors_check() as errors: for field_name, value in input_dict.items(): field = self[field_name] try: self.set_value(instance,", "except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value,", "= [] with field_errors_check() as errors: for fieldname, field, value in field_and_value: try:", "instance ) def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field)", "ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setattr(instance, key, value)", "with field_errors_check() as errors: for field in self._fields: try: if field.name in input_dict:", "def _get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field)", "field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self,", "== field: return i, item return None, None def _type_cast(self, input_dict): cast_values =", "= 'Copyright(c) <NAME> 2017' \"\"\" \"\"\" import logging from collections import OrderedDict from", "getattr(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed: value =", "return getitem(instance, key) def _group_get_value(self, instance, field): index, _ = self._get_field_index(field) return self._accessor(instance,", "self._fields: if field.name == key: return field raise KeyError('{} not found.'.format(key)) def __setitem__(self,", "index, _ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields,", "field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i,", "MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for field_name, value in", "OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance, field): if field.is_computed:", "yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception as", "as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setattr(instance, key,", "value in input_dict.items() ) key_values = [] with field_errors_check() as errors: for fieldname,", "def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields if", "self._current_field_index = 0 return self def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration", "as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key,", "ex) def _mutator(self, instance, key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def", "field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae for field", "= self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception as ex:", "(field.name, self._get_value(instance, field)) for field in self._fields if field.name in instance ) def", "return self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field,", "dict if not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict))", "self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex)", "self._get_value(instance, field)) for field in self._fields if field.name in instance ) def instances_differ(self,", "field) for field in self._fields if field.name in instance and field.name in other", "fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self,", "FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def", "field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self, instance, key): raise", "field_group_class = field_group_class if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for field", "'Copyright(c) <NAME> 2017' \"\"\" \"\"\" import logging from collections import OrderedDict from operator", "index, _ = self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception", "field) for field in self._fields } def instances_differ(self, instance, other): return any( self._get_value(instance,", "} def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field) for", "transformation=None, field_group_class=None): transformation = copy_field if transformation is None else transformation field_group_class =", "errors: for fieldname, value in instance.items(): field = self[fieldname] try: yield field, value,", "def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other, field) for field", "key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field):", "in self._fields if field.name in instance ) def instances_differ(self, instance, other): return any(", "errors: for fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as", "value): raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields):", "from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type):", "_group_get_value(self, instance, field): index, _ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def", "fields self._container_type = container_type def __iter__(self): self._current_field_index = 0 return self def __next__(self):", "return field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key ==", "instance, field): raise NotImplementedError def _get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance)", "# Used in unittests # def as_dict(self, instance): return { field.name: self._get_value(instance, field)", "as errors: for fieldname, value in instance.items(): field = self[fieldname] try: yield field,", "instance, field): if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self,", "KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for", "return OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields if field.name in instance", "ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name)", "self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup):", "import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object):", "any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields if field.name in", "self._current_field_index += 1 return result def __len__(self): return len(self._fields) def __getitem__(self, key): for", "transformation field_group_class = field_group_class if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for", "from operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations", "_ = self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception as", "item in enumerate(self._fields): if item == field: return i, item return None, None", "if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise", "transformation = copy_field if transformation is None else transformation field_group_class = field_group_class if", "SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field, value): try: if", "field) != self._get_value(other, field) for field in self._fields if field.name in instance and", "self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable", "operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import", "field_errors_check() as errors: for fieldname, value in instance.items(): field = self[fieldname] try: yield", "raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key", "key: return field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key", "key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict)", "self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance, key) def set_value(self, instance, field,", "setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance,", "return self def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result = self._fields[self._current_field_index]", ") def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def", "for fieldname, value in input_dict.items() ) key_values = [] with field_errors_check() as errors:", "1 return result def __len__(self): return len(self._fields) def __getitem__(self, key): for field in", "enumerate(self._fields): if item == field: return i, item return None, None def _type_cast(self,", "update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors:", ") key_values = [] with field_errors_check() as errors: for fieldname, field, value in", "field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError #", "_mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup):", "enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None):", "if field.name == key: return field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key,", "( (fieldname, self[fieldname], value) for fieldname, value in input_dict.items() ) key_values = []", "= logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields self._container_type =", "value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def", "fields, container_type): self._fields = fields self._container_type = container_type def __iter__(self): self._current_field_index = 0", "try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception", "field_group_class( [ field.derive(transformation) for field in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise", "def _mutator(self, instance, key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self,", "# # Used in unittests # def as_dict(self, instance): return { field.name: self._get_value(instance,", "self.__class__ return field_group_class( [ field.derive(transformation) for field in self._fields ] ) def fill_instance_from_dict(self,", "OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields", "fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self,", "= fields self._container_type = container_type def __iter__(self): self._current_field_index = 0 return self def", "value): return setitem(instance, key, value) def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup):", "def _type_cast(self, input_dict): cast_values = [] with field_errors_check() as errors: for field in", "key, value) def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields,", "raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self): return", "FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup):", "field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae for field in self._fields: try:", "instance, key): return getitem(instance, key) def _group_get_value(self, instance, field): index, _ = self._get_field_index(field)", "def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for field_name, value in input_dict.items():", "field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise except", "input_dict): field_and_value = ( (fieldname, self[fieldname], value) for fieldname, value in input_dict.items() )", "= dict if not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return", "errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field):", "FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name))", "value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return", "in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return", "return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def", "FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key,", "self._get_value(other, field) for field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order", "getitem(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed: value =", "input_dict): cast_values = [] with field_errors_check() as errors: for field in self._fields: try:", "key) def set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value)", "OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from", "except FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self,", "value in input_dict.items(): field = self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as", "self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError: raise except Exception as ex: raise", "+= 1 return result def __len__(self): return len(self._fields) def __getitem__(self, key): for field", "field in self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance,", "0 return self def __next__(self): if self._current_field_index >= len(self._fields): raise StopIteration result =", "unittests # def as_dict(self, instance): return { field.name: self._get_value(instance, field) for field in", "instance): return { field.name: self._get_value(instance, field) for field in self._fields } def instances_differ(self,", "def _mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup,", "Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self, instance, key, value): return setattr(instance,", "not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key does not", "with field_errors_check() as errors: for fieldname, value in instance.items(): field = self[fieldname] try:", "for field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict)", "= fae def set_value(self, instance, field, value): raise NotImplementedError def _mutator(self, instance, key,", "field) for field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order =", "replacement_field break def derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation is None", "else: return self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError # # Used", "class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors: for field_name, value", "input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance,", "None def _type_cast(self, input_dict): cast_values = [] with field_errors_check() as errors: for field", "if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else: errors[field] =", "NotImplementedError def _get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance) else: return self._group_get_value(instance,", "instance, per_field_map): with field_errors_check() as errors: for fieldname, value in instance.items(): field =", "fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict): with field_errors_check() as errors:", "import logging from collections import OrderedDict from operator import getitem, setitem from a_tuin.metadata.exceptions", "self._get_value(instance, field) != self._get_value(other, field) for field in self._fields ) class SequenceFieldGroup(FieldGroup): def", "key, value): raise NotImplementedError def empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self,", "__init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for", "self._fields ] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise", "instance, key, value): return setitem(instance, key, value) def empty_instance(self): return [None] * len(self)", "_mutator(self, instance, key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields):", "def derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation is None else transformation", "raise NotImplementedError # # Used in unittests # def as_dict(self, instance): return {", "import getitem, setitem from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field", "replace field for i, field in enumerate(self._fields): if field.name == key: self._fields[i] =", "in instance ) def instances_differ(self, instance, other): return any( self._get_value(instance, field) != self._get_value(other,", "field.name == key: return field raise KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field):", "field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception", "container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance,", "set_value(self, instance, field, value): raise NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError", "as errors: for field in self._fields: try: if field.name in input_dict: raw_value =", "= self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] =", "len(self._fields): raise StopIteration result = self._fields[self._current_field_index] self._current_field_index += 1 return result def __len__(self):", "def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value) for fieldname, value in", "key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict))", "field, value): try: if not field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field)", "instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for", "in input_dict.items() ) key_values = [] with field_errors_check() as errors: for fieldname, field,", "for field in self._fields: try: if field.name in input_dict: raw_value = input_dict[field.name] else:", "instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance, key) def", "raw_value = input_dict[field.name] else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as", "def _accessor(self, instance, key): return getattr(instance, key) def set_value(self, instance, field, value): try:", "return field_group_class( [ field.derive(transformation) for field in self._fields ] ) def fill_instance_from_dict(self, input_dict):", "self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self, instance,", "def __init__(self, fields, container_type=None): container_type = dict if not container_type else container_type super().__init__(fields,", "fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else: errors[field]", "except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field))", "return { field.name: self._get_value(instance, field) for field in self._fields } def instances_differ(self, instance,", "try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError as fae: errors[field] = fae for field in", "_group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getitem(instance, key)", "pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field", "for i, field in enumerate(self._fields): if field.name == key: self._fields[i] = replacement_field break", "field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae def _type_cast(self, input_dict):", "field_errors_check() as errors: for fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except", "class FieldGroup(object): def __init__(self, fields, container_type): self._fields = fields self._container_type = container_type def", "field, value): raise NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self):", "value = field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index, value) except FieldAssignmentError:", "return getitem(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed: value", "instance, key): return getitem(instance, key) def set_value(self, instance, field, value): try: if not", "to {}'.format(value, field_name)) else: errors[field] = fae def set_value(self, instance, field, value): raise", "to assign {} to {}'.format(value, field_name)) else: errors[field] = fae def set_value(self, instance,", "field_name)) else: errors[field] = fae def set_value(self, instance, field, value): raise NotImplementedError def", "in self._fields: try: if field.name in input_dict: raw_value = input_dict[field.name] else: raw_value =", "OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields if field.name in instance )", "== replacement_field.name, 'Key does not match field name.' # replace field for i,", "field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex:", "with field_errors_check() as errors: for field, destination_field in per_field_map.items(): try: yield field, self._get_value(instance,", "item return None, None def _type_cast(self, input_dict): cast_values = [] with field_errors_check() as", "input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def as_dict(self, instance): return OrderedDict(", "for field in self._fields } def instances_differ(self, instance, other): return any( self._get_value(instance, field)", "def _group_get_value(self, instance, field): return self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance,", "DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict if not container_type else container_type", "field): for i, item in enumerate(self._fields): if item == field: return i, item", "in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values())", "ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item in enumerate(self._fields): if item", "self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError # # Used in unittests", "as_dict(self, instance): return { field.name: self._get_value(instance, field) for field in self._fields } def", "empty_instance(self): return self._container_type() class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self,", "as_dict(self, instance): return OrderedDict( (field.name, self._get_value(instance, field)) for field in self._fields if field.name", "as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def", "field): index, _ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields):", "setitem(instance, key, value) def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self,", "def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return", "NotImplementedError def _mutator(self, instance, key, value): raise NotImplementedError def empty_instance(self): return self._container_type() class", "from a_tuin.metadata.exceptions import FieldAssignmentError, field_errors_check, DATA_LOAD_ERRORS from a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__)", "field, value): try: if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value)", "def _accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self, instance, field): index, _", "field: return i, item return None, None def _type_cast(self, input_dict): cast_values = []", "value) def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None):", "found.'.format(key)) def __setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key does not match", "field.name: self._get_value(instance, field) for field in self._fields } def instances_differ(self, instance, other): return", "(fieldname, self[fieldname], value) for fieldname, value in input_dict.items() ) key_values = [] with", "per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except", "try: if not field.is_computed: value = field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError:", "value = field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception as", "= self[field_name] try: self.set_value(instance, field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError):", "_mutator(self, instance, key, value): return setitem(instance, key, value) def empty_instance(self): return [None] *", "return getattr(instance, key) def set_value(self, instance, field, value): try: if not field.is_computed: value", "container_type def __iter__(self): self._current_field_index = 0 return self def __next__(self): if self._current_field_index >=", "] ) def fill_instance_from_dict(self, input_dict): raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError", "self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def", "list) def set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value)", "FieldAssignmentError as fae: errors[field] = fae for field in self._fields: try: computed_value =", "[] with field_errors_check() as errors: for field in self._fields: try: if field.name in", "instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) index, _ =", "self._fields: try: if field.name in input_dict: raw_value = input_dict[field.name] else: raw_value = field.get_value(self,", "fieldname, value in instance.items(): field = self[fieldname] try: yield field, value, per_field_map.get(field) except", "self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field,", "try: self.set_value(instance, field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to", "for field in self._fields: if field.name == key: return field raise KeyError('{} not", "field in self._fields } def instances_differ(self, instance, other): return any( self._get_value(instance, field) !=", "field in self._fields ) class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return", "return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self, fields): super().__init__(fields, OrderedDict) def iterate_instance(self,", "for i, item in enumerate(self._fields): if item == field: return i, item return", "raise NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with", "def _accessor(self, instance, key): return getitem(instance, key) def set_value(self, instance, field, value): try:", "class ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field, value):", "for field in self._fields if field.name in instance ) def instances_differ(self, instance, other):", "ListFieldGroup(MutableSequenceFieldGroup, SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, list) def set_value(self, instance, field, value): try:", "class SequenceFieldGroup(FieldGroup): def fill_instance_from_dict(self, input_dict): values_in_order = self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance,", "__iter__(self): self._current_field_index = 0 return self def __next__(self): if self._current_field_index >= len(self._fields): raise", "try: yield field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae def", "field): raise NotImplementedError def _get_value(self, instance, field): if field.is_computed: return field.get_value(self, instance) else:", "_accessor(self, instance, key): raise NotImplementedError # # Used in unittests # def as_dict(self,", "\"\"\" import logging from collections import OrderedDict from operator import getitem, setitem from", "errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise NotImplementedError def _get_value(self, instance,", "__len__(self): return len(self._fields) def __getitem__(self, key): for field in self._fields: if field.name ==", "return any( self._get_value(instance, field) != self._get_value(other, field) for field in self._fields ) class", "iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for field, destination_field in per_field_map.items(): try:", "input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for field,", "NotImplementedError def update_instance_from_dict(self, instance, input_dict): raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check()", "as errors: for fieldname, field, value in field_and_value: try: key_values.append((fieldname, field.type_cast(value))) except FieldAssignmentError", "fae: errors[field] = fae for field in self._fields: try: computed_value = field.get_value(self, input_dict)", "KeyError('{} not found.'.format(key)) def __setitem__(self, key, replacement_field): assert key == replacement_field.name, 'Key does", "class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class MutableSequenceFieldGroup(FieldGroup): def update_instance_from_dict(self, instance, input_dict):", "instance) else: return self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError # #", "assign {} to {}'.format(value, field_name)) else: errors[field] = fae def set_value(self, instance, field,", "_accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self, instance, field): index, _ =", "replacement_field): assert key == replacement_field.name, 'Key does not match field name.' # replace", "if field.name == key: self._fields[i] = replacement_field break def derive(self, transformation=None, field_group_class=None): transformation", "class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type = dict if not container_type else", "= replacement_field break def derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation is", "field in self._fields: if field.name == key: return field raise KeyError('{} not found.'.format(key))", "cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex))", "Used in unittests # def as_dict(self, instance): return { field.name: self._get_value(instance, field) for", "return field.get_value(self, instance) else: return self._group_get_value(instance, field) def _accessor(self, instance, key): raise NotImplementedError", "instance, field): index, _ = self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self,", "as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to {}'.format(value, field_name)) else:", "super().__init__(fields, container_type) def fill_instance_from_dict(self, input_dict): return self._container_type(self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance,", "except DATA_LOAD_ERRORS as ex: errors.append(FieldAssignmentError(field, ex)) return OrderedDict(cast_values) def _group_get_value(self, instance, field): raise", "for field in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError:", "self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values)", "errors[field] = fae for field in self._fields: try: computed_value = field.get_value(self, input_dict) key_values.append((field.name,", "value in instance.items(): field = self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError", "iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for fieldname, value in instance.items(): field", "_mutator(self, instance, key, value): return setitem(instance, key, value) class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict):", "value) except FieldAssignmentError: raise except Exception as ex: raise FieldAssignmentError(field, ex) def _mutator(self,", "key, replacement_field): assert key == replacement_field.name, 'Key does not match field name.' #", "if not field.is_computed: value = field.prepare_value(value) index, _ = self._get_field_index(field) return self._mutator(instance, index,", "else transformation field_group_class = field_group_class if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation)", "fae def _type_cast(self, input_dict): field_and_value = ( (fieldname, self[fieldname], value) for fieldname, value", "field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception as ex: raise", "self._accessor(instance, field.name) def _accessor(self, instance, key): return getattr(instance, key) def set_value(self, instance, field,", "field, value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {}", "break def derive(self, transformation=None, field_group_class=None): transformation = copy_field if transformation is None else", "= copy_field if transformation is None else transformation field_group_class = field_group_class if field_group_class", "key): return getitem(instance, key) def _group_get_value(self, instance, field): index, _ = self._get_field_index(field) return", "a_tuin.metadata.field_transformations import copy_field LOG = logging.getLogger(__name__) class FieldGroup(object): def __init__(self, fields, container_type): self._fields", "def __len__(self): return len(self._fields) def __getitem__(self, key): for field in self._fields: if field.name", "def _accessor(self, instance, key): raise NotImplementedError # # Used in unittests # def", "= self._type_cast(input_dict) return self._container_type(values_in_order.values()) def _accessor(self, instance, key): return getitem(instance, key) def _group_get_value(self,", "fields, container_type=None): container_type = dict if not container_type else container_type super().__init__(fields, container_type) def", "input_dict.items() ) key_values = [] with field_errors_check() as errors: for fieldname, field, value", "def _mutator(self, instance, key, value): return setattr(instance, key, value) class PartialDictFieldGroup(DictFieldGroup): def __init__(self,", "class ObjectFieldGroup(MutableSequenceFieldGroup): def fill_instance_from_dict(self, input_dict): return self._container_type(**self._type_cast(input_dict)) def _group_get_value(self, instance, field): return self._accessor(instance,", "item == field: return i, item return None, None def _type_cast(self, input_dict): cast_values", "def __iter__(self): self._current_field_index = 0 return self def __next__(self): if self._current_field_index >= len(self._fields):", "is None else transformation field_group_class = field_group_class if field_group_class else self.__class__ return field_group_class(", "value) except FieldAssignmentError as fae: if isinstance(fae.original_exception, AttributeError): LOG.warning('Unable to assign {} to", "set_value(self, instance, field, value): try: if not field.is_computed: value = field.prepare_value(value) index, _", "= container_type def __iter__(self): self._current_field_index = 0 return self def __next__(self): if self._current_field_index", "instance, per_field_map): with field_errors_check() as errors: for field, destination_field in per_field_map.items(): try: yield", "raise NotImplementedError def iterate_instance(self, instance, per_field_map): with field_errors_check() as errors: for field, destination_field", "in per_field_map.items(): try: yield field, self._get_value(instance, field), destination_field except FieldAssignmentError as field_error: errors.append(field_error)", "_type_cast(self, input_dict): cast_values = [] with field_errors_check() as errors: for field in self._fields:", "= field_group_class if field_group_class else self.__class__ return field_group_class( [ field.derive(transformation) for field in", "def empty_instance(self): return [None] * len(self) class DictFieldGroup(MutableSequenceFieldGroup): def __init__(self, fields, container_type=None): container_type", "self[fieldname] try: yield field, value, per_field_map.get(field) except FieldAssignmentError as fae: errors[field] = fae", "try: computed_value = field.get_value(self, input_dict) key_values.append((field.name, computed_value)) except KeyError: pass return OrderedDict(key_values) def", "= field.prepare_value(value) return self._mutator(instance, field.name, value) except FieldAssignmentError: raise except Exception as ex:", "self._get_value(instance, field) for field in self._fields } def instances_differ(self, instance, other): return any(", "else: raw_value = field.get_value(self, input_dict) cast_values.append((field.name, field.type_cast(raw_value))) except FieldAssignmentError as fae: errors.append(fae) except", "errors.append(field_error) except Exception as ex: errors.append(FieldAssignmentError(field, ex)) def _get_field_index(self, field): for i, item", "container_type=None): container_type = dict if not container_type else container_type super().__init__(fields, container_type) def fill_instance_from_dict(self,", "= self._get_field_index(field) return self._accessor(instance, index) class TupleFieldGroup(SequenceFieldGroup): def __init__(self, fields): super().__init__(fields, tuple) class" ]
[ "np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 * np.pi * 16 * t)+100*np.sin(2", "1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]')", "t)+100*np.sin(2 * np.pi *0.1 * t) for i in range(50): sig[50+i] = sig1[i]", "\"\"\" from scipy import signal import matplotlib.pyplot as plt import numpy as np", "in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname,", "* np.pi *0.1 * t) for i in range(50): sig[50+i] = sig1[i] +", "range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1)", "= range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi", "* t)+100*np.sin(2 * np.pi *0.1 * t) for i in range(50): sig[50+i] =", "1, 50, endpoint=False) sig1 = np.sin(2 * np.pi * 16 * t)+100*np.sin(2 *", "t = np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 * np.pi * 16", "[s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f,", "t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure()", "endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t -", "between WT and STFT \"\"\" from scipy import signal import matplotlib.pyplot as plt", "* t) + signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False)", "plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t", "signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2", "t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7", "WT and STFT \"\"\" from scipy import signal import matplotlib.pyplot as plt import", "t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t, f,", "+ sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200,", "endpoint=False) sig1 = np.sin(2 * np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1", "scales, waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude')", "plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f", "matplotlib.pyplot as plt import numpy as np import pywt waveletname = 'morl' scales", "0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 * np.pi", "(Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg =", "scales = range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 *", "t) + signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1", "plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t,", "t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)')", "sig[50+i] = sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t", "t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)') plt.ylabel('f [Hz]')", "plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig,", "7 * t) + signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1, 50,", "np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) t", "= sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t =", "200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t", "= pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed", "i in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales,", "plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t = t*400", "pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal')", "f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t,", "* 16 * t)+100*np.sin(2 * np.pi *0.1 * t) for i in range(50):", "range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi *", "np.sin(2 * np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1 * t) for", "Zxx = signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx),", "16 * t)+100*np.sin(2 * np.pi *0.1 * t) for i in range(50): sig[50+i]", "for i in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig,", "np.pi *0.1 * t) for i in range(50): sig[50+i] = sig1[i] + sig[50+i]", "200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform", "= np.sin(2 * np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1 * t)", "Show differences between WT and STFT \"\"\" from scipy import signal import matplotlib.pyplot", "pywt waveletname = 'morl' scales = range(1,200) t = np.linspace(-1, 1, 200, endpoint=False)", "t) for i in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq =", "= np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2)", "signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]')", "*0.1 * t) for i in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff,", "plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx", "50, endpoint=False) sig1 = np.sin(2 * np.pi * 16 * t)+100*np.sin(2 * np.pi", "np import pywt waveletname = 'morl' scales = range(1,200) t = np.linspace(-1, 1,", "np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma')", "\"\"\" Show differences between WT and STFT \"\"\" from scipy import signal import", "sig = np.cos(2 * np.pi * 7 * t) + signal.gausspulse(t - 0.4,", "np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t)", "+ signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1 =", "'morl' scales = range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2", "Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg", "1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 * t) +", "* t) for i in range(50): sig[50+i] = sig1[i] + sig[50+i] coeff, freq", "coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False)", "plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)')", "scipy import signal import matplotlib.pyplot as plt import numpy as np import pywt", "endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett", "* np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) t =", "= t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)') plt.ylabel('f", "waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t", "signal import matplotlib.pyplot as plt import numpy as np import pywt waveletname =", "kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8)", "= 'morl' scales = range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig =", "STFT \"\"\" from scipy import signal import matplotlib.pyplot as plt import numpy as", "= np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff,", "np.pi * 7 * t) + signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1,", "= np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 * np.pi * 16 *", "sig1[i] + sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0,", "np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1 * t) for i in", "200, 200, endpoint=False) plt.plot(t,sig,color='k') plt.title('Transformed signal') plt.ylabel('Amplitude') plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet", "waveletname = 'morl' scales = range(1,200) t = np.linspace(-1, 1, 200, endpoint=False) sig", "numpy as np import pywt waveletname = 'morl' scales = range(1,200) t =", "[Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t =", "* 7 * t) + signal.gausspulse(t - 0.4, fc=2) t = np.linspace(-1, 1,", "differences between WT and STFT \"\"\" from scipy import signal import matplotlib.pyplot as", "fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 * np.pi *", "import pywt waveletname = 'morl' scales = range(1,200) t = np.linspace(-1, 1, 200,", "= signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma')", "import numpy as np import pywt waveletname = 'morl' scales = range(1,200) t", "fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time", "plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)') plt.ylabel('f [Hz]') plt.xlabel('t", "and STFT \"\"\" from scipy import signal import matplotlib.pyplot as plt import numpy", "import matplotlib.pyplot as plt import numpy as np import pywt waveletname = 'morl'", "= 8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier", "plt.xlabel('t [s]') plt.figure() plt.pcolormesh(coeff, cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]')", "plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)') plt.ylabel('f [Hz]') plt.xlabel('t [s]')", "plt import numpy as np import pywt waveletname = 'morl' scales = range(1,200)", "import signal import matplotlib.pyplot as plt import numpy as np import pywt waveletname", "plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t", "- 0.4, fc=2) t = np.linspace(-1, 1, 50, endpoint=False) sig1 = np.sin(2 *", "from scipy import signal import matplotlib.pyplot as plt import numpy as np import", "* np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1 * t) for i", "8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform", "as np import pywt waveletname = 'morl' scales = range(1,200) t = np.linspace(-1,", "sig[50+i] coeff, freq = pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200, 200,", "cmap='plasma') plt.title('Wavelet Transform (Morlett kernel)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') f, t, Zxx =", "= np.linspace(-1, 1, 200, endpoint=False) sig = np.cos(2 * np.pi * 7 *", "[s]') f, t, Zxx = signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure()", "as plt import numpy as np import pywt waveletname = 'morl' scales =", "sig1 = np.sin(2 * np.pi * 16 * t)+100*np.sin(2 * np.pi *0.1 *", "f, np.abs(Zxx), cmap='plasma') plt.title('Short Time Fourier Transform (STFT)') plt.ylabel('f [Hz]') plt.xlabel('t [s]') plt.show()", "freq = pywt.cwt(sig, scales, waveletname, 1) t = np.linspace(0, 200, 200, endpoint=False) plt.plot(t,sig,color='k')", "signal.stft(sig, fs=400,nperseg = 8) t = t*400 plt.figure() plt.pcolormesh(t, f, np.abs(Zxx), cmap='plasma') plt.title('Short" ]
[ "14 15] # [16 17 18 19 20] # [21 22 23 24", "def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i return value2 def function_c(self):", "2 3 4 5] # [ 6 7 8 9 10] # [11", "return value #2 def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value", "def __init__(self): pass def function_a(self): value1=0 for i in range(1,1000+1): value1+=i return value1", "function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) #", "i in range(1,m+1): value+=i return value #2 def function3(): value=0 for i in", "# [11 12 13 14 15] # [16 17 18 19 20] #", "12 13 14 15] # [16 17 18 19 20] # [21 22", "return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512", "i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500", "# 500500 # 500500 # 77.51389798916512 #oriented object programming class physic_calculation: def __init__(self):", "9 10] # [11 12 13 14 15] # [16 17 18 19", "i in range(1,1000+1): value+=i return value #1-b def function2(m): value=0 for i in", "500500 # 500500 # 77.51389798916512 #oriented object programming class physic_calculation: def __init__(self): pass", "print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[", "print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented object programming class physic_calculation: def", "return value1 def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i return value2", "value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented object programming", "object programming class physic_calculation: def __init__(self): pass def function_a(self): value1=0 for i in", "value+=i return value #1-b def function2(m): value=0 for i in range(1,m+1): value+=i return", "pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5)", "#1-b def function2(m): value=0 for i in range(1,m+1): value+=i return value #2 def", "value2 def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\")", "value #1-b def function2(m): value=0 for i in range(1,m+1): value+=i return value #2", "print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1", "# [[ 1 2 3 4 5] # [ 6 7 8 9", "for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500 #", "physic_calculation: def __init__(self): pass def function_a(self): value1=0 for i in range(1,1000+1): value1+=i return", "8 9 10] # [11 12 13 14 15] # [16 17 18", "import numpy as np #1-a def function1(): value=0 for i in range(1,1000+1): value+=i", "function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000))", "for i in range(1,1000+1): value+=i return value #1-b def function2(m): value=0 for i", "7 8 9 10] # [11 12 13 14 15] # [16 17", "function2(m): value=0 for i in range(1,m+1): value+=i return value #2 def function3(): value=0", "def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a())", "for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) #", "np #1-a def function1(): value=0 for i in range(1,1000+1): value+=i return value #1-b", "in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100)", "in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 #", "value #2 def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1())", "[11 12 13 14 15] # [16 17 18 19 20] # [21", "value2+=i return value2 def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3", "value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500", "77.51389798916512 #oriented object programming class physic_calculation: def __init__(self): pass def function_a(self): value1=0 for", "function1(): value=0 for i in range(1,1000+1): value+=i return value #1-b def function2(m): value=0", "as np #1-a def function1(): value=0 for i in range(1,1000+1): value+=i return value", "value2=0 for i in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for i", "print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a)", "500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4 5]", "# 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2", "pass def function_a(self): value1=0 for i in range(1,1000+1): value1+=i return value1 def function_b(self,m):", "function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0", "value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 #", "value1=0 for i in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0 for", "for i in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for i in", "math import numpy as np #1-a def function1(): value=0 for i in range(1,1000+1):", "500500 # 77.51389798916512 #oriented object programming class physic_calculation: def __init__(self): pass def function_a(self):", "range(1,m+1): value+=i return value #2 def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100)", "__init__(self): pass def function_a(self): value1=0 for i in range(1,1000+1): value1+=i return value1 def", "in range(1,m+1): value+=i return value #2 def function3(): value=0 for i in range(1,100+1):", "[ 6 7 8 9 10] # [11 12 13 14 15] #", "a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4 5] # [ 6 7", "numpy as np #1-a def function1(): value=0 for i in range(1,1000+1): value+=i return", "function_a(self): value1=0 for i in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0", "value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\")", "range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i", "programming class physic_calculation: def __init__(self): pass def function_a(self): value1=0 for i in range(1,1000+1):", "value1 def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i return value2 def", "500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3", "10] # [11 12 13 14 15] # [16 17 18 19 20]", "range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512", "value=0 for i in range(1,m+1): value+=i return value #2 def function3(): value=0 for", "77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4 5] # [", "print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented object programming class physic_calculation:", "value=0 for i in range(1,1000+1): value+=i return value #1-b def function2(m): value=0 for", "5] # [ 6 7 8 9 10] # [11 12 13 14", "# 77.51389798916512 #oriented object programming class physic_calculation: def __init__(self): pass def function_a(self): value1=0", "print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented object programming class", "class physic_calculation: def __init__(self): pass def function_a(self): value1=0 for i in range(1,1000+1): value1+=i", "range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return", "def function1(): value=0 for i in range(1,1000+1): value+=i return value #1-b def function2(m):", "#1-a def function1(): value=0 for i in range(1,1000+1): value+=i return value #1-b def", "value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented", "in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1):", "for i in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0 for i", "13 14 15] # [16 17 18 19 20] # [21 22 23", "range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500", "def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3())", "#2 def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000))", "15] # [16 17 18 19 20] # [21 22 23 24 25]]", "# 500500 # 77.51389798916512 #oriented object programming class physic_calculation: def __init__(self): pass def", "print(a) # [[ 1 2 3 4 5] # [ 6 7 8", "6 7 8 9 10] # [11 12 13 14 15] # [16", "def function_a(self): value1=0 for i in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m", "4 5] # [ 6 7 8 9 10] # [11 12 13", "# [ 6 7 8 9 10] # [11 12 13 14 15]", "value+=i return value #2 def function3(): value=0 for i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return", "#oriented object programming class physic_calculation: def __init__(self): pass def function_a(self): value1=0 for i", "# 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4 5] #", "# 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4", "3 4 5] # [ 6 7 8 9 10] # [11 12", "1 2 3 4 5] # [ 6 7 8 9 10] #", "self.m=m value2=0 for i in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for", "in range(1,1000+1): value+=i return value #1-b def function2(m): value=0 for i in range(1,m+1):", "for i in range(1,m+1): value+=i return value #2 def function3(): value=0 for i", "import math import numpy as np #1-a def function1(): value=0 for i in", "value1+=i return value1 def function_b(self,m): self.m=m value2=0 for i in range(1,self.m+1): value2+=i return", "[[ 1 2 3 4 5] # [ 6 7 8 9 10]", "in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 #", "i in range(1,100+1): value+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500", "return value #1-b def function2(m): value=0 for i in range(1,m+1): value+=i return value", "print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c()) # 500500 # 500500 # 77.51389798916512 print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) #", "return value print(function1()) print(function2(1000)) print(function3()) # 500500 # 500500 # 77.51389798916512 #oriented object", "value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation() print(\"---------------OOP----------------\") print(pc.function_a()) print(pc.function_b(1000)) print(pc.function_c())", "def function2(m): value=0 for i in range(1,m+1): value+=i return value #2 def function3():", "i in range(1,self.m+1): value2+=i return value2 def function_c(self): value3=0 for i in range(1,100+1):", "print(\"---------------numpy----------------\") a=np.arange(1,26).reshape(5,5) print(a) # [[ 1 2 3 4 5] # [ 6", "range(1,1000+1): value+=i return value #1-b def function2(m): value=0 for i in range(1,m+1): value+=i", "return value2 def function_c(self): value3=0 for i in range(1,100+1): value3+=math.sqrt(i*math.pi/100)*math.sin(i*math.pi/100) return value3 pc=physic_calculation()", "i in range(1,1000+1): value1+=i return value1 def function_b(self,m): self.m=m value2=0 for i in" ]
[ "from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\",", "company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\", company=\"3\", address=\"4\",", "email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\", company=\"3\", address=\"4\", mobile=\"5\", email=\"6\")) app.session.logout()", "app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\",", "-*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\",", "utf-8 -*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\",", "coding: utf-8 -*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\",", "mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\", company=\"3\", address=\"4\", mobile=\"5\", email=\"6\"))", "Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\",", "-*- coding: utf-8 -*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(", "address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\", company=\"3\", address=\"4\", mobile=\"5\",", "def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def", "app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\",", "model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\",", "<gh_stars>0 # -*- coding: utf-8 -*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\",", "import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\"))", "password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\")", "lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact(Contact(name=\"1\", lastname=\"2\", company=\"3\",", "Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout()", "test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\") app.contact.create_contact( Contact(name=\"Yevhen\", lastname=\"Hurtovyi\", company=\"Sidley\", address=\"Chicago\", mobile=\"7733311608\", email=\"<EMAIL>\")) app.session.logout() def test_add_digits_contact(app):", "# -*- coding: utf-8 -*- from model.contact import Contact def test_add_contact(app): app.session.login(username=\"admin\", password=\"<PASSWORD>\")" ]
[ "result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects =", "for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0]", "= ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles", "[\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs: if", "= ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle =", "result += dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result)", ") def _webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"):", "ctx.attr.mode == 'prod': args += ['-p'] args += ['--config', config.path] args += ['--env.bin_dir',", "= _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"),", "else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js')", "s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills =", "polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True,", "hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if", "\"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources =", "target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"],", "set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config =", "+= ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label, inputs =", "styles], executable = ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles]))", "rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\":", "main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs", "if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources", "ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs", "_collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for s", "arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation =", "def _collect_es5_sources_impl(target, ctx): result = set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs:", "styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\":", "ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles", "hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources", "+= s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills", "for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"):", "result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs", "ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills =", "[config] args = [] if ctx.attr.mode == 'prod': args += ['-p'] args +=", "outputs = [main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments = args, )", "= [main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments = args, ) return", "\"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills, vendor,", "polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args", "ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor =", "== 'prod': args += ['-p'] args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path]", "+= ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args +=", "% ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable =", "args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action(", "_collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs =", "args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling", "vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if", "def _webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs", "ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode ==", "\"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects", "{ \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\": attr.label(default=Label(\"@nrwl//:webpack\"), executable=True, cfg=\"host\")", "'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js')", "['-p'] args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package]", "= set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config", "[] if ctx.attr.mode == 'prod': args += ['-p'] args += ['--config', config.path] args", "= args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl,", "ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if ctx.attr.mode == 'prod': args +=", "vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]),", "= ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args =", "= ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main", "+= [config] args = [] if ctx.attr.mode == 'prod': args += ['-p'] args", "= set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result", "if ctx.attr.mode == 'prod': args += ['-p'] args += ['--config', config.path] args +=", "ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label,", "if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod':", "s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if", "\"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main =", "ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main =", "attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\": attr.label(default=Label(\"@nrwl//:webpack\"),", "ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor =", "struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def", "= \"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills,", "= ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs +=", "inputs = inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments", "aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for", "+= ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\"", "dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result", "config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js')", "main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else:", "args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label, inputs", "= ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor", "args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args", "polyfills, vendor, styles], executable = ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills,", "attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for s in", "['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" %", "ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config]", "inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments = args,", "config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode]", "result = set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"):", "= ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills", "vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js')", "args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs", "_collect_es5_sources_impl(target, ctx): result = set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if", "in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result +=", "hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main", "styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js')", "styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if ctx.attr.mode == 'prod':", "= ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor", "if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return", "ctx): result = set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep,", "bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills, vendor, styles],", "hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl,", "ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs =", "= ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if ctx.attr.mode == 'prod': args", "= result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx):", "inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js')", "+= target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\",", "'prod': args += ['-p'] args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args", "== 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles =", "ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = []", "ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable = ctx.executable._webpack,", "inputs = set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources", "ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation", "ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources", "= aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set()", "+= ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message", "ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js') polyfills = ctx.new_file('bundles/polyfills.bundle.js') vendor = ctx.new_file('bundles/vendor.bundle.js') styles =", "\"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result += dep.es5_sources if hasattr(target,", "attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\": attr.label(default=Label(\"@nrwl//:webpack\"), executable=True, cfg=\"host\") } )", "\"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs: if hasattr(s,", "ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if ctx.attr.mode ==", "return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = {", "dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources =", "%s\" % ctx.label, inputs = inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable", "executable = ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle", "['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message =", "[main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main,", "inputs += [config] args = [] if ctx.attr.mode == 'prod': args += ['-p']", "DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\":", "vendor, styles], executable = ctx.executable._webpack, arguments = args, ) return DefaultInfo(files=depset([main, polyfills, vendor,", "+= ['-p'] args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package',", "args = [] if ctx.attr.mode == 'prod': args += ['-p'] args += ['--config',", ") return DefaultInfo(files=depset([main, polyfills, vendor, styles])) webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs =", "= [] if ctx.attr.mode == 'prod': args += ['-p'] args += ['--config', config.path]", "= inputs.to_list(), outputs = [main, polyfills, vendor, styles], executable = ctx.executable._webpack, arguments =", "_webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\":", "set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in ctx.rule.attr.srcs: if hasattr(dep, \"es5_sources\"): result +=", "<filename>packages/bazel/src/utils/webpack.bzl def _collect_es5_sources_impl(target, ctx): result = set() if hasattr(ctx.rule.attr, \"srcs\"): for dep in", "in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs += s.es5_sources config = ctx.attr.config.files.to_list()[0] if ctx.attr.mode", "ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack", "= rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True),", "= [\"deps\", \"srcs\"], ) def _webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs:", "\"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\": attr.label(default=Label(\"@nrwl//:webpack\"), executable=True, cfg=\"host\") }", "+= dep.es5_sources if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources", "return struct(es5_sources = result) _collect_es5_sources = aspect( _collect_es5_sources_impl, attr_aspects = [\"deps\", \"srcs\"], )", "if ctx.attr.mode == 'prod': main = ctx.new_file('bundles/main.bundle.prod.js') polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js')", "= ctx.new_file('bundles/vendor.bundle.js') styles = ctx.new_file('bundles/styles.bundle.js') inputs += [config] args = [] if ctx.attr.mode", "['--env.mode', ctx.attr.mode] ctx.action( progress_message = \"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(),", "args += ['-p'] args += ['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args +=", "polyfills = ctx.new_file('bundles/polyfills.bundle.prod.js') vendor = ctx.new_file('bundles/vendor.bundle.prod.js') styles = ctx.new_file('bundles/styles.bundle.prod.js') else: main = ctx.new_file('bundles/main.bundle.js')", "progress_message = \"Webpack bundling %s\" % ctx.label, inputs = inputs.to_list(), outputs = [main,", "webpack_bundle = rule(implementation = _webpack_bundle_impl, attrs = { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True,", "= { \"srcs\": attr.label_list(allow_files=True, aspects=[_collect_es5_sources]), \"config\": attr.label(allow_single_file=True, mandatory=True), \"mode\": attr.string(default=\"dev\"), \"_webpack\": attr.label(default=Label(\"@nrwl//:webpack\"), executable=True,", "if hasattr(target, \"typescript\"): result += target.typescript.es5_sources return struct(es5_sources = result) _collect_es5_sources = aspect(", "_webpack_bundle_impl(ctx): inputs = set() for s in ctx.attr.srcs: if hasattr(s, \"es5_sources\"): inputs +=", "['--config', config.path] args += ['--env.bin_dir', ctx.configuration.bin_dir.path] args += ['--env.package', ctx.label.package] args += ['--env.mode'," ]
[ "adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame = None savedTime = 0", "= scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1", "else: if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\")", "(255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if", "int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth,", "= scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r", "128 numKeys = len(NOTES) playing = numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports())", "cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame,", "5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys = len(NOTES)", "= 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok,", "cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] =", "cv2 import numpy as np import rtmidi NOTES = [ 60, 62, 64,", "import numpy as np import rtmidi NOTES = [ 60, 62, 64, 65,", "midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1 or 'through'", "overlay = blankOverlay.copy() for i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in", "None: save = True lastCheckTime = t else: if t >= lastCheckTime +", "0) t = time.time() save = False if savedFrame is None: save =", "t if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save =", "cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects = [] for i", "if len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video", "if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90,", "lastCheckTime = t if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred", "for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8)", "= 1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing =", "lastCheckTime = t else: if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in", "if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred", "import rtmidi NOTES = [ 60, 62, 64, 65, 67, 69, 71, 72,", "blurred): print(\"saving\") save = True lastCheckTime = t if t >= savedTime +", "scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred =", "76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25", "= True lastCheckTime = t if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame", "savedTime = t if comparisonFrame is None: comparisonFrame = blurred continue delta =", "i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1],", "= [] for i in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r", "sum = keys+delta overlay = blankOverlay.copy() for i in range(numKeys): r = frameRects[i]", "for r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r", "= keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys):", "numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) ==", "as np import rtmidi NOTES = [ 60, 62, 64, 65, 67, 69,", "= keys+delta overlay = blankOverlay.copy() for i in range(numKeys): r = frameRects[i] if", "video.read() if not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1],", "= frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not", "[(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for r in frameRects))", "True lastCheckTime = t if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame =", "scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame =", "savedFrame = None savedTime = 0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a,", "cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if not", "for r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r", "True if save: savedFrame = blurred savedTime = t if comparisonFrame is None:", "[] for i in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r =", "= cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame =", "= frameHeight else: aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight =", "keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame", "blurred save = True if save: savedFrame = blurred savedTime = t if", "delta = compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy() for i in", "!= frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame,", "= t if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save", "in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for r in frameRects))", "1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1: break", "savedFrame = blurred savedTime = t if comparisonFrame is None: comparisonFrame = blurred", "rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1 or 'through' not in", "save = False if savedFrame is None: save = True lastCheckTime = t", "= int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight", "comparisonFrame = None savedFrame = None savedTime = 0 lastCheckTime = 0 def", "keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r =", "cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or", "THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing = numKeys *", "= [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r)", "aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect)", "= None savedTime = 0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b),", "print(\"resetting\") comparisonFrame = blurred save = True if save: savedFrame = blurred savedTime", "* [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1", "sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i]", "comparisonFrame is None: comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred) sum =", "comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred) sum = keys+delta overlay =", "r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True", "0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1", "while True: ok, frame = video.read() if not ok: time.sleep(0.05) continue frame =", "in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime = t if t >=", "for r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r", "= keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for", "= False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0))", "= 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE =", "frameHeight else: aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH", "= True lastCheckTime = t else: if t >= lastCheckTime + SAVE_CHECK_TIME: if", "KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE", "playing = numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if", "savedFrame is None: save = True lastCheckTime = t else: if t >=", "frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame,", "savedTime = 0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE,", "if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save", "69, 71, 72, 74 ] # , 76, 77, 79 ] NOTE_VELOCITY =", "scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE)", "= (max(r[1][0] for r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0]", "= video.read() if not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame =", "video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth:", "in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1]", "= frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for", "= frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1]", "return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if", "x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0]", "# , 76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT", "save = True lastCheckTime = t else: if t >= lastCheckTime + SAVE_CHECK_TIME:", "= True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0],", "71, 72, 74 ] # , 76, 77, 79 ] NOTE_VELOCITY = 127", "cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects = [] for i in", "scaledWidth = frameWidth scaledHeight = frameHeight else: aspect = frameWidth / frameHeight scaledWidth", "keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in", "x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1", "midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >=", "= blurred save = True if save: savedFrame = blurred savedTime = t", "blurred) sum = keys+delta overlay = blankOverlay.copy() for i in range(numKeys): r =", "in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight =", "for r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled =", "= [] frameRects = [] for i in range(numKeys): x0 = scaledWidth*i//numKeys x1", "/ frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1", "return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1,", "keys+delta overlay = blankOverlay.copy() for i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE", "= cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save", "i+1, cv2.FILLED) comparisonFrame = None savedFrame = None savedTime = 0 lastCheckTime =", "in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for r in scaledRects))", "in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None", "aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects", "= 500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD =", "25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing = numKeys * [False] midiout", "if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else: aspect =", "NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False", "NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] =", "= 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME =", "frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame", "if save: savedFrame = blurred savedTime = t if comparisonFrame is None: comparisonFrame", "= \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME =", "r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))]", "(min(r[0][0] for r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for", "scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return", "adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]),", "0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay,", "500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25", "time.time() save = False if savedFrame is None: save = True lastCheckTime =", "r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in", "cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save = False", "else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if", "(xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED)", "= 25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing = numKeys * [False]", "blurred savedTime = t if comparisonFrame is None: comparisonFrame = blurred continue delta", "in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255),", "1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0)", "frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]:", "= None savedFrame = None savedTime = 0 lastCheckTime = 0 def compare(a,b):", "[ 60, 62, 64, 65, 67, 69, 71, 72, 74 ] # ,", "= frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame =", "r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else:", ">= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else: aspect = frameWidth /", "1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH", "= 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = []", "t = time.time() save = False if savedFrame is None: save = True", "(keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t =", "assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower()", "r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame =", "NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1,", "else: aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH /", "(0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) ==", "cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth =", "continue delta = compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy() for i", "for i in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))]", "= time.time() save = False if savedFrame is None: save = True lastCheckTime", "kernelSize), 0) t = time.time() save = False if savedFrame is None: save", "blurred continue delta = compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy() for", "lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True:", "RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME,", "kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects =", "scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay =", ">= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True", "frameHeight) scaledRects = [] frameRects = [] for i in range(numKeys): x0 =", "range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 =", "x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys", "t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save =", "= frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize", "range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame", "frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for", "= np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i]", "r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if", "ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth", "[] frameRects = [] for i in range(numKeys): x0 = scaledWidth*i//numKeys x1 =", "frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled", "compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy() for i in range(numKeys): r", "0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while", "keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled =", "t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True if", "save = True lastCheckTime = t if t >= savedTime + RESET_TIME: print(\"resetting\")", "numKeys = len(NOTES) playing = numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber", "midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i]", "RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True if save: savedFrame = blurred", "cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME,", "np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys,", ">= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True if save:", "NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE", "COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if not ok: time.sleep(0.05) continue", "/ aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight)", "= (max(r[1][0] for r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0]", "= np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects = []", "= (min(r[0][0] for r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0]", "frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize =", "in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for r in scaledRects))", "if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2)", "r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for r", "savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True if save: savedFrame", "= blurred savedTime = t if comparisonFrame is None: comparisonFrame = blurred continue", "+ SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime =", "frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else: aspect = frameWidth / frameHeight", "frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize,", "(max(r[1][0] for r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled", "r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for r in", "overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) ==", "60, 62, 64, 65, 67, 69, 71, 72, 74 ] # , 76,", "keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY)", "for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for r", "<reponame>arpruss/motionpiano<filename>simplemotionpiano.py import time, cv2 import numpy as np import rtmidi NOTES = [", "cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects = [] for i in range(numKeys):", "frameRects = [] for i in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1", "time, cv2 import numpy as np import rtmidi NOTES = [ 60, 62,", "= t else: if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame,", "2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27", "r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in", "= cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0)", "True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1],", "= blankOverlay.copy() for i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum:", "in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1]", "[False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1 or", "1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i],", "len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video =", "in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0", "ok, frame = video.read() if not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1)", "COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime = t if t", ", 76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT =", "scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys =", "in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys", "= (min(r[0][0] for r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0]", "blankOverlay.copy() for i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay,", "keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled =", "continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth:", "comparisonFrame = blurred save = True if save: savedFrame = blurred savedTime =", "keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame =", "playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay,", "(cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1: break video.release() cv2.destroyAllWindows()", "for i in range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0],", "keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1])", "False if savedFrame is None: save = True lastCheckTime = t else: if", "if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime = t if", "0 if len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber)", "keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time()", "= cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth", "playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME,", "cv2.FILLED) comparisonFrame = None savedFrame = None savedTime = 0 lastCheckTime = 0", "for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for r", "print(\"saving\") save = True lastCheckTime = t if t >= savedTime + RESET_TIME:", "cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame = None savedTime =", "x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in", "COMPARISON_VALUE = 128 numKeys = len(NOTES) playing = numKeys * [False] midiout =", "frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r", "= 0 if len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1", "save: savedFrame = blurred savedTime = t if comparisonFrame is None: comparisonFrame =", "r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in", "scaledHeight = frameHeight else: aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight", "= blurred continue delta = compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy()", "= 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE =", "blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects =", "None savedFrame = None savedTime = 0 lastCheckTime = 0 def compare(a,b): return", "= True if save: savedFrame = blurred savedTime = t if comparisonFrame is", "0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1: break video.release() cv2.destroyAllWindows() del midiout", "if savedFrame is None: save = True lastCheckTime = t else: if t", "0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE = 128", "[(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame", "in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy):", "WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME", "= int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else:", "127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042", "import time, cv2 import numpy as np import rtmidi NOTES = [ 60,", "= 0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1]", "if comparisonFrame is None: comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred) sum", "RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else: aspect = frameWidth", "np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects = [] for", "scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame = None savedTime", "keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i", "THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if not ok: time.sleep(0.05)", "not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i],", "if not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]]", "int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight =", "= [ 60, 62, 64, 65, 67, 69, 71, 72, 74 ] #", "compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime = t if t >= savedTime", "range(numKeys): r = frameRects[i] if 1+i+COMPARISON_VALUE in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED)", "keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize),", "None: comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred) sum = keys+delta overlay", "r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) & 0xFF)", "def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]),", "frameWidth, frameHeight) scaledRects = [] frameRects = [] for i in range(numKeys): x0", "frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth", "0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame", "cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save =", "keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def adjustToKeys(xy): return (xy[0]-keysTopLeftScaled[0],xy[1]-keysTopLeftScaled[1]) for i in range(numKeys): r", "scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 =", "= scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame = None", "= [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for r in", "64, 65, 67, 69, 71, 72, 74 ] # , 76, 77, 79", "blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save = False if", "cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if not ok: time.sleep(0.05) continue frame", "not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if", "= 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys =", "r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1] keys = np.zeros((keysHeightScaled,keysWidthScaled),dtype=np.uint8) def", "RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys", "= len(NOTES) playing = numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber =", "\"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME = 5", "scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r) x0 = frameWidth*i//numKeys x1 = frameWidth*(i+1)//numKeys-1 r =", "cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled)) keysFrame = cv2.cvtColor(keysFrame, cv2.COLOR_BGR2GRAY) blurred = cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t", "if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80,", "= False if savedFrame is None: save = True lastCheckTime = t else:", "keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled =", "2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME, frameWidth, frameHeight) scaledRects = [] frameRects", "in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1]", "frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled", "scaledRects),min(r[0][1] for r in scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for", "t else: if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred):", "time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth !=", "= RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8)", "frameWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*frameHeight))] frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for", "or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth =", "save = True if save: savedFrame = blurred savedTime = t if comparisonFrame", "= cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save = False if savedFrame", "67, 69, 71, 72, 74 ] # , 76, 77, 79 ] NOTE_VELOCITY", "lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime", "== 1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0)", "KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME", "def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame =", "for i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame", "in sum: cv2.rectangle(overlay, r[0], r[1], (255,255,255), cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY])", "frameWidth scaledHeight = frameHeight else: aspect = frameWidth / frameHeight scaledWidth = RECOGNIZER_WIDTH", "b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read() if not ok:", "True lastCheckTime = t else: if t >= lastCheckTime + SAVE_CHECK_TIME: if COMPARISON_VALUE", "= int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay = np.zeros((frameHeight,frameWidth,3),dtype=np.uint8) cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_AUTOSIZE) cv2.resizeWindow(WINDOW_NAME,", "True: ok, frame = video.read() if not ok: time.sleep(0.05) continue frame = cv2.flip(frame,", "rtmidi NOTES = [ 60, 62, 64, 65, 67, 69, 71, 72, 74", "portNumber = 0 if len(midiout.get_ports()) == 1 or 'through' not in str(midiout.get_ports()[0]).lower() else", "r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1) &", "= t if comparisonFrame is None: comparisonFrame = blurred continue delta = compare(comparisonFrame,", "frame = video.read() if not ok: time.sleep(0.05) continue frame = cv2.flip(frame, 1) keysFrame", "playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0])", "int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight else: aspect", "79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH =", "compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD, COMPARISON_VALUE, cv2.THRESH_BINARY)[1] while True: ok, frame = video.read()", "if t >= savedTime + RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True", "'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))", "(kernelSize, kernelSize), 0) t = time.time() save = False if savedFrame is None:", "(max(r[1][0] for r in frameRects),max(r[1][1] for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for", "1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing = numKeys", "adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame = None savedFrame = None savedTime = 0 lastCheckTime", "77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH", "numpy as np import rtmidi NOTES = [ 60, 62, 64, 65, 67,", "= 128 numKeys = len(NOTES) playing = numKeys * [False] midiout = rtmidi.MidiOut()", "72, 74 ] # , 76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME", "frameRects.append(r) keysTopLeftFrame = (min(r[0][0] for r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame", "midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame,", "False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if", "frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) if RECOGNIZER_WIDTH >= frameWidth: scaledWidth = frameWidth scaledHeight = frameHeight", "RECOGNIZER_WIDTH = 500 KERNEL_SIZE = 0.042 RESET_TIME = 5 SAVE_CHECK_TIME = 1 THRESHOLD", "& 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1: break video.release() cv2.destroyAllWindows() del", "= numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports())", "= frameWidth scaledHeight = frameHeight else: aspect = frameWidth / frameHeight scaledWidth =", "i in range(numKeys): x0 = scaledWidth*i//numKeys x1 = scaledWidth*(i+1)//numKeys-1 r = [(x0,0),(x1,int(KEY_HEIGHT*scaledHeight))] scaledRects.append(r)", "+ RESET_TIME: print(\"resetting\") comparisonFrame = blurred save = True if save: savedFrame =", "is None: comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred) sum = keys+delta", "cv2.GaussianBlur(keysFrame, (kernelSize, kernelSize), 0) t = time.time() save = False if savedFrame is", "] # , 76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\"", "] NOTE_VELOCITY = 127 WINDOW_NAME = \"MotionPiano\" KEY_HEIGHT = 0.25 RECOGNIZER_WIDTH = 500", "np import rtmidi NOTES = [ 60, 62, 64, 65, 67, 69, 71,", "len(NOTES) playing = numKeys * [False] midiout = rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0", "SAVE_CHECK_TIME = 1 THRESHOLD = 25 COMPARISON_VALUE = 128 numKeys = len(NOTES) playing", "for r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for r", "= rtmidi.MidiOut() assert(midiout.get_ports()) portNumber = 0 if len(midiout.get_ports()) == 1 or 'through' not", "65, 67, 69, 71, 72, 74 ] # , 76, 77, 79 ]", "scaledRects = [] frameRects = [] for i in range(numKeys): x0 = scaledWidth*i//numKeys", "scaledRects)) keysBottomRightScaled = (max(r[1][0] for r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled", "r in frameRects)) keysTopLeftScaled = (min(r[0][0] for r in scaledRects),min(r[0][1] for r in", "1 or 'through' not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth", "1) keysFrame = frame[keysTopLeftFrame[1]:keysBottomRightFrame[1], keysTopLeftFrame[0]:keysBottomRightFrame[0]] if scaledWidth != frameWidth: keysFrame = cv2.resize(keysFrame, (keysWidthScaled,keysHeightScaled))", "str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))", "SAVE_CHECK_TIME: if COMPARISON_VALUE in compare(savedFrame, blurred): print(\"saving\") save = True lastCheckTime = t", "0.25, 1.0)) if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1:", "r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for r in", "NOTES = [ 60, 62, 64, 65, 67, 69, 71, 72, 74 ]", "None savedTime = 0 lastCheckTime = 0 def compare(a,b): return cv2.threshold(cv2.absdiff(a, b), THRESHOLD,", "(min(r[0][0] for r in frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for", "else: if playing[i]: midiout.send_message([0x80, NOTES[i], 0]) playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0),", "playing[i] = False cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25,", "frameHeight scaledWidth = RECOGNIZER_WIDTH scaledHeight = int(RECOGNIZER_WIDTH / aspect) kernelSize = 2*int(KERNEL_SIZE*scaledWidth/2)+1 blankOverlay", "r in scaledRects),max(r[1][1] for r in scaledRects)) keysWidthScaled = keysBottomRightScaled[0]-keysTopLeftScaled[0] keysHeightScaled = keysBottomRightScaled[1]-keysTopLeftScaled[1]", "74 ] # , 76, 77, 79 ] NOTE_VELOCITY = 127 WINDOW_NAME =", "cv2.FILLED) if not playing[i]: midiout.send_message([0x90, NOTES[i], NOTE_VELOCITY]) playing[i] = True else: if playing[i]:", "if (cv2.waitKey(1) & 0xFF) == 27 or cv2.getWindowProperty(WINDOW_NAME, 0) == -1: break video.release()", "t if comparisonFrame is None: comparisonFrame = blurred continue delta = compare(comparisonFrame, blurred)", "frameRects),min(r[0][1] for r in frameRects)) keysBottomRightFrame = (max(r[1][0] for r in frameRects),max(r[1][1] for", "is None: save = True lastCheckTime = t else: if t >= lastCheckTime", "cv2.rectangle(overlay, r[0], r[1], (0,255,0), 2) cv2.imshow(WINDOW_NAME, cv2.addWeighted(frame, 1, overlay, 0.25, 1.0)) if (cv2.waitKey(1)", "not in str(midiout.get_ports()[0]).lower() else 1 midiout.open_port(portNumber) video = cv2.VideoCapture(0) frameWidth = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) frameHeight", "i in range(numKeys): r = scaledRects[i] cv2.rectangle(keys, adjustToKeys(r[0]), adjustToKeys(r[1]), i+1, cv2.FILLED) comparisonFrame =", "= compare(comparisonFrame, blurred) sum = keys+delta overlay = blankOverlay.copy() for i in range(numKeys):", "62, 64, 65, 67, 69, 71, 72, 74 ] # , 76, 77," ]
[ "griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \",", "stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch,", "plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\")", "# %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %%", "get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav =", "Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _,", "time import librosa.display import yaml import tensorflow as tf import numpy as np", "yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in", "output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs with both implementations.", "Saving outputs with both implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path, config,", "# Get mel spectrogram example and corresponding ground truth audio. # %% mel_spec", "time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\"", "truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\"", "between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path,", "mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len]", "tensorflow as tf import numpy as np import matplotlib.pyplot as plt from tensorflow_tts.utils", "# %% [markdown] # Get mel spectrogram example and corresponding ground truth audio.", "8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\",", "= griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %%", "# %% _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True)", "children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2,", ":, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"])", "librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3", "reconstruction (TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list:", "config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \",", "= np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config =", "stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path,", "tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x", "= time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape:", "[markdown] # Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') #", "gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch", "= griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) #", "%% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\"", "and supports batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) #", "get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav", "yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav", "{inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs with both implementations. # %%", "# Saving outputs with both implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path,", "comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec,", "25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2, ax3) = plt.subplots(3, 1,", "grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10,", "gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator(", "shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs with both implementations. #", "outputs with both implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\",", "start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output", "\"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape:", "np.min(inv_wav_lb) # %% [markdown] # Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit',", "25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2, ax3) = plt.subplots(3,", "for x in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav' # %% tempfile.gettempdir()", "%% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav", "mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s,", "as tf import numpy as np import matplotlib.pyplot as plt from tensorflow_tts.utils import", "color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\")", "file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10)", "file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch", "truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"],", "[ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav] ] labels =", "# %% import glob import tempfile import time import librosa.display import yaml import", "= plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\")", "# %% [markdown] # TF version has GPU compatibility and supports batch dimension.", "config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False,", "example and corresponding ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav =", "# %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav,", "= [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav] ] labels", "# [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown] # Time comparison", "# %% [markdown] # Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis,", "Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch", "spectrogram example and corresponding ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav", "# TF version has GPU compatibility and supports batch dimension. # %% #", "'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav =", "%% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds", "import numpy as np import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb", "file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen,", "# %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1,", "mel spectrogram example and corresponding ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\")", "in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav' # %% tempfile.gettempdir() # %%", "tempfile import time import librosa.display import yaml import tensorflow as tf import numpy", "as np import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config", "1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100,", "griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav'", "and corresponding ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\")", "[markdown] # Saving outputs with both implementations. # %% # Single file griffin_lim_lb(mel_spec,", "implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') #", "= tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items =", "librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen():", "30px\"), ) # %% _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8),", "stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:,", "\", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF version has GPU compatibility", "in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for", "both implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf,", "labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px", "librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction", "TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %% [markdown] # Get mel", "# %% np.min(inv_wav_lb) # %% [markdown] # Time comparison between both implementations. #", "[mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown] # Time comparison between", "glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None,", "# # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) #", "compatibility and supports batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32)", "plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %%", "ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def", "griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %%", "= TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape)", "'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0,", "glob import tempfile import time import librosa.display import yaml import tensorflow as tf", "Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %%", "import tempfile import time import librosa.display import yaml import tensorflow as tf import", "%config InlineBackend.figure_format = 'svg' # %% [markdown] # Get mel spectrogram example and", "_, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"],", "ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\");", "librosa.display import yaml import tensorflow as tf import numpy as np import matplotlib.pyplot", "start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs with both", "[gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items],", "np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf =", "[1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] # %%", "inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" )", "tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %% [markdown] #", "stats_path, config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown] #", "inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb =", "import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %% [markdown] # Get", "<filename>notebooks/griffin_lim.py # %% import glob import tempfile import time import librosa.display import yaml", "color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim", "tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter()", "# %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"])", "= 'svg' # %% [markdown] # Get mel spectrogram example and corresponding ground", "%% [markdown] # Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])')", "np import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format", "import librosa.display import yaml import tensorflow as tf import numpy as np import", "ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in", "loop=False) for x in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"),", "[x for x in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav' # %%", "mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch", "# %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path =", "\"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) #", "import time import librosa.display import yaml import tensorflow as tf import numpy as", "TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\",", "# Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) # %ls", "%% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %%", "import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from", "for file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]])", "ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground", ").padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration", "def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds =", "audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path", "(librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %%", "for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time:", "%% [markdown] # Saving outputs with both implementations. # %% # Single file", "config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(),", "= griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec,", "matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg'", "%% import glob import tempfile import time import librosa.display import yaml import tensorflow", "TF version has GPU compatibility and supports batch dimension. # %% # inv_wav_tf", "{time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs", "'svg' # %% [markdown] # Get mel spectrogram example and corresponding ground truth", "tempfile.gettempdir(), [x for x in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav' #", "wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for", "# %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file)", "config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config)", "= tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:,", "sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list =", "InlineBackend.figure_format = 'svg' # %% [markdown] # Get mel spectrogram example and corresponding", "supports batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1,", "tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch)", "sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim", "= yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape)", "time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving", "gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader)", "print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF version has", "# [1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len]", "-> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown] # Time comparison between both", "mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config", "ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1)", "yaml import tensorflow as tf import numpy as np import matplotlib.pyplot as plt", "from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %% [markdown]", "(ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\",", "import glob import tempfile import time import librosa.display import yaml import tensorflow as", "inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list", "output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x", ":])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :,", "np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path),", "lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items", "[markdown] # TF version has GPU compatibility and supports batch dimension. # %%", "*items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2, ax3)", "# %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) #", "GPU compatibility and supports batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :],", "color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\")", "sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 )", "x in range(10)]) # %ls {tempfile.gettempdir()} | grep '.wav' # %% tempfile.gettempdir() #", "shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF version has GPU", "for x in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")]", "print( f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown]", "f\"Iteration time: {time.perf_counter() - start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] #", "numpy as np import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb #", "tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(),", "x in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox(", "print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown]", "\", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF", ") # %% [markdown] # Saving outputs with both implementations. # %% #", "version has GPU compatibility and supports batch dimension. # %% # inv_wav_tf =", "as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format = 'svg' #", "= np.load(\"dump/train/wavs/1-wave.npy\") stats_path = \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf", "config) # %% [markdown] # TF version has GPU compatibility and supports batch", "figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"],", "= glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32),", "griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files #", "# %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis],", "ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path =", "mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF version", "import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim, griffin_lim_lb # %config InlineBackend.figure_format =", "files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) # %ls {tempfile.gettempdir()} |", "gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False)", ") # %% _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True,", "%% np.min(inv_wav_lb) # %% [markdown] # Time comparison between both implementations. # %%", "config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown] # Time", "GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1,", "Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) # %ls {tempfile.gettempdir()}", "config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_,", "# griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)]) # %ls {tempfile.gettempdir()} | grep", "ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot(", "in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter() -", "] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\",", "= \"dump/stats.npy\" dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config)", "gt_wav.shape) print(\"config\\n\", config) # %% [markdown] # TF version has GPU compatibility and", "ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100,", "file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files", "ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction", "= tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for", "config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print(", "-> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] #", "wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in range(10)])", "- start_batch:.4f}s, output shape: {inv_wav_tf_batch.shape}\" ) # %% [markdown] # Saving outputs with", "tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) #", "%% _, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(10, 8), sharey=True, sharex=True) librosa.display.waveplot(gt_wav,", "shape: \", mel_spec.shape) print(\"gt_wav shape: \", gt_wav.shape) print(\"config\\n\", config) # %% [markdown] #", "audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb)", "griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path,", "griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) # %% [markdown]", "Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit',", "sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\")", "ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2) ax2.set_title(\"Griffin-Lim reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\",", "corresponding ground truth audio. # %% mel_spec = np.load(\"dump/train/raw-feats/1-raw-feats.npy\") gt_wav = np.load(\"dump/train/wavs/1-wave.npy\") stats_path", "dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] ->", "ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for", "Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) #", "%% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"])", "# Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # #", "# %config InlineBackend.figure_format = 'svg' # %% [markdown] # Get mel spectrogram example", "tf.newaxis], config[\"sampling_rate\"]) # %% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in", "import yaml import tensorflow as tf import numpy as np import matplotlib.pyplot as", ":], n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config)", "(tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch =", "# Time comparison between both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %%", "autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"),", "[markdown] # Get mel spectrogram example and corresponding ground truth audio. # %%", "[1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] ->", "in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels,", "tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25%", "has GPU compatibility and supports batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis,", ") ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file", "Get mel spectrogram example and corresponding ground truth audio. # %% mel_spec =", "# inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb", "implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\",", "dataset_config_path = \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %%", "# %% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\")", "[audio_len] # %% np.min(inv_wav_lb) # %% [markdown] # Time comparison between both implementations.", "Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec shape: \", mel_spec.shape) print(\"gt_wav shape:", "print(\"config\\n\", config) # %% [markdown] # TF version has GPU compatibility and supports", "= \"preprocess/baker_preprocess.yaml\" config = yaml.load(open(dataset_config_path), Loader=yaml.Loader) griffin_lim_tf = TFGriffinLim(stats_path, config) # %% print(\"mel_spec", "both implementations. # %% get_ipython().run_line_magic('timeit', 'griffin_lim_tf(mel_spec[tf.newaxis, :])') # %% get_ipython().run_line_magic('timeit', 'griffin_lim_lb(mel_spec, stats_path, config)')", "%% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_", "%% [markdown] # TF version has GPU compatibility and supports batch dimension. #", "tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis],", "%% items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav]", "= [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"),", "tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ =", "reconstruction (librosa)\") ax2.set_xlabel(\"\") librosa.display.waveplot( inv_wav_tf[0].numpy()*100, sr=config[\"sampling_rate\"], color=\"r\", ax=ax3 ) ax3.set_title(\"Griffin-Lim reconstruction (TF)\"); #", "n_iter=32) # [1, mel_len] -> [1, audio_len] inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) #", "griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x", "batch dimension. # %% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len]", "config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %%", "%% # inv_wav_tf = griffin_lim_tf(mel_spec[tf.newaxis, :], n_iter=32) # [1, mel_len] -> [1, audio_len]", "# %% [markdown] # Saving outputs with both implementations. # %% # Single", "np.load(file) mel_ds = tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5):", "output_dir=\"../tmp\", wav_name=\"tf\") # # Batch files # griffin_lim_tf.save_wav(inv_wav_tf_batch, tempfile.gettempdir(), [x for x in", "tf import numpy as np import matplotlib.pyplot as plt from tensorflow_tts.utils import TFGriffinLim,", "inv_wav_lb = griffin_lim_lb(mel_spec, stats_path, config) # [mel_len] -> [audio_len] # %% np.min(inv_wav_lb) #", "layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), ) # %% _, (ax1, ax2, ax3) =", "items = [ Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav] ]", "sharey=True, sharex=True) librosa.display.waveplot(gt_wav, sr=config[\"sampling_rate\"], color=\"b\", ax=ax1) ax1.set_title(\"Ground truth\") ax1.set_xlabel(\"\") librosa.display.waveplot(inv_wav_lb*100, sr=config[\"sampling_rate\"], color=\"g\", ax=ax2)", "(TF)\"); # %% def gen(): file_list = glob.glob(\"../dump/train/norm-feats/*-norm-feats.npy\") for file in file_list: yield", "%% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\") griffin_lim_tf.save_wav(inv_wav_tf, output_dir=\"../tmp\", wav_name=\"tf\") #", "[Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25% 25% 25%\", grid_template_rows=\"30px 30px\"), )", "griffin_lim_lb # %config InlineBackend.figure_format = 'svg' # %% [markdown] # Get mel spectrogram", "mel_batch in mel_ds.take(5): start_batch = time.perf_counter() inv_wav_tf_batch = griffin_lim_tf(mel_batch) print( f\"Iteration time: {time.perf_counter()", "= tf.data.Dataset.from_generator( gen, (tf.float32), tf.TensorShape([None, config[\"num_mels\"]]) ).padded_batch(10) for mel_batch in mel_ds.take(5): start_batch =", "config)') # %% tf_wav = tf.audio.encode_wav(inv_wav_tf[0, :, tf.newaxis], config[\"sampling_rate\"]) lb_wav = tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis],", "Audio(value=x.numpy(), autoplay=False, loop=False) for x in [gt_wav_, lb_wav, tf_wav] ] labels = [Label(\"Ground", "tf.audio.encode_wav(inv_wav_lb[:, tf.newaxis], config[\"sampling_rate\"]) gt_wav_ = tf.audio.encode_wav(gt_wav[:, tf.newaxis], config[\"sampling_rate\"]) # %% items = [", "with both implementations. # %% # Single file griffin_lim_lb(mel_spec, stats_path, config, output_dir=\"../tmp\", wav_name=\"lb\")", "lb_wav, tf_wav] ] labels = [Label(\"Ground Truth\"), Label(\"Librosa\"), Label(\"TensorFlow\")] GridBox( children=[*labels, *items], layout=Layout(grid_template_columns=\"25%", "%% [markdown] # Get mel spectrogram example and corresponding ground truth audio. #" ]
[ "Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 * 0.1 * 0.22", "= (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 * 0.1 * 0.22 /", "<filename>templatedir/nice/objective.py import sys #if len(sys.argv) == 1: # print(200000) #else: Powerout = (float(sys.argv[1])", "- 298.15) * 3.14159265 * 0.1 * 0.1 * 0.22 / 0.005 #p", "0.1 * 0.1 * 0.22 / 0.005 #p = 611.21 * 2.718281828 **", "#Powerin = float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 * 8.31446261815324 * float(sys.argv[1]))", "print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 * 0.1", "# print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 *", "(float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 * 8.31446261815324 *", "float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 * 8.31446261815324 * float(sys.argv[1])) print(Powerout +", "#if len(sys.argv) == 1: # print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) *", "* 0.1 * 0.22 / 0.005 #p = 611.21 * 2.718281828 ** ((18.678", "0.22 / 0.005 #p = 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin", "len(sys.argv) == 1: # print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265", "611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 *", "- (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 * 8.31446261815324", "2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528 *", "** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000", "* 2256600 * 18.01528 * p/(1000 * 8.31446261815324 * float(sys.argv[1])) print(Powerout + float(sys.argv[2]))", "* 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528", "* 0.1 * 0.1 * 0.22 / 0.005 #p = 611.21 * 2.718281828", "sys #if len(sys.argv) == 1: # print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15)", "== 1: # print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 *", "3.14159265 * 0.1 * 0.1 * 0.22 / 0.005 #p = 611.21 *", "298.15) * 3.14159265 * 0.1 * 0.1 * 0.22 / 0.005 #p =", "/ 0.005 #p = 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin =", "= float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 * 8.31446261815324 * float(sys.argv[1])) print(Powerout", "((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600 * 18.01528 * p/(1000 *", "0.005 #p = 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2])", "#p = 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) *", "0.1 * 0.22 / 0.005 #p = 611.21 * 2.718281828 ** ((18.678 -", "= 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01))) #Powerin = float(sys.argv[2]) * 2256600", "(float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 * 0.1 * 0.22 / 0.005", "import sys #if len(sys.argv) == 1: # print(200000) #else: Powerout = (float(sys.argv[1]) -", "1: # print(200000) #else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1", "#else: Powerout = (float(sys.argv[1]) - 298.15) * 3.14159265 * 0.1 * 0.1 *", "* 3.14159265 * 0.1 * 0.1 * 0.22 / 0.005 #p = 611.21", "* 0.22 / 0.005 #p = 611.21 * 2.718281828 ** ((18.678 - (float(sys.argv[1])-273.15)/234.5)*((float(sys.argv[1])-273.15)/(float(sys.argv[1])-16.01)))" ]
[ "from PyQt5.QtWidgets import QWidget from PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore", "super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data = None self.data_index = None", "QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen and", "self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end y_length = y_end - y_start", "QWidget from PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt import", "not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size", "# TODO: what if y_start is None ? if y_start is None: if", "y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value ->", "# Draw horizontal lines ########################################### if self.hlines is not None: for hline_index, hline_value", "title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data = [data_value", "self.data_color = None self.title = None self.title_size = 32 self.title_margin = 5 self.hlines", "data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start) return math.floor(data_ordinate_position) else: return", "= None self.data_color = None self.title = None self.title_size = 32 self.title_margin =", "self.hlines_style = None self.ymin = None self.ymax = None self.x_label_height = 50 #", "= self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end y_length", "plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start", "= qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end,", "= self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start", "self.data_color)): if data_value is not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif", "Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green", "= widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end +", "max(0, widget_width - 2 * self.horizontal_margin) plot_area_height = max(0, widget_height - 2 *", "Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start =", "pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen", "Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin =", "min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width", "pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end # Draw", "bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start #", "QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal", "None self.hlines_style = None self.ymin = None self.ymax = None self.x_label_height = 50", "<= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value)", "self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) /", "size = self.size() widget_width = size.width() widget_height = size.height() if num_bar > 0:", "self.hlines = None self.hlines_style = None self.ymin = None self.ymax = None self.x_label_height", "pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen", "# See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine)", "qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start,", "title_height = self.title_size title_x_end = title_x_start + title_width title_y_end = title_y_start + title_height", "None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width =", "except: num_bar = 0 if self.data_index is not None and len(self.data_index) != len(self.data):", "def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value", "= self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end y_length = y_end -", "from PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin =", "y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if", "self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end y_length =", "PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10", "= None self.x_label_height = 50 # Set window background color self.setAutoFillBackground(True) palette =", "x_start, y_start, x_end, y_end # Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen)", "/ num_bar) x_start = self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value) #", "qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value", "plot_area_width, plot_area_height) # TODO # Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen", "= self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start) return math.floor(data_ordinate_position) else: return None", "title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) #", "QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white,", "self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else", "# self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <=", "self.data if data_value is not None] self.top_ordinate_value = max(filtered_data) if self.ymax is None", "#yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ###########################################", "palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try:", "None self.ymin = None self.ymax = None self.x_label_height = 50 # Set window", "qp = QPainter(self) try: num_bar = len(self.data) except: num_bar = 0 if self.data_index", "QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"),", "y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is", "+ title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title)", "data_value is not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color ==", "if self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width -", "title_x_end = title_x_start + title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width,", "anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font)", "self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf", "widget_width = size.width() widget_height = size.height() if num_bar > 0: plot_area_width = max(0,", "https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine)", "__init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data = None self.data_index =", "self.title_margin title_width = widget_width - 2 * self.title_margin title_height = self.title_size title_x_end =", "if y_start is None ? if y_start is None: if data_value > self.bottom_ordinate_value:", "in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style =", "See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen", "None self.ymax = None self.x_label_height = 50 # Set window background color self.setAutoFillBackground(True)", "= self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try: num_bar", "hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not None: try:", "for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not None: if", "self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end", "self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio =", "horizontal lines ########################################### if self.hlines is not None: for hline_index, hline_value in enumerate(self.hlines):", "= self.title_margin title_y_start = self.title_margin title_width = widget_width - 2 * self.title_margin title_height", "* self.horizontal_margin) plot_area_height = max(0, widget_height - 2 * self.vertical_margin) # Set antialiasing", "2 * self.horizontal_margin) plot_area_height = max(0, widget_height - 2 * self.vertical_margin) # Set", "plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end # Draw bars ####################################################### pen =", "Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try: num_bar = len(self.data) except:", "self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin", "= widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush =", "QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen)", "- 2 * self.horizontal_margin) plot_area_height = max(0, widget_height - 2 * self.vertical_margin) #", "data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0)", "qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end # Draw bars", "self.data = None self.data_index = None self.data_color = None self.title = None self.title_size", "None: try: hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine)", "if self.data_index is not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\")", "= widget_width - 2 * self.title_margin title_height = self.title_size title_x_end = title_x_start +", "Draw title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width = widget_width -", "self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin", "if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen()", "try: num_bar = len(self.data) except: num_bar = 0 if self.data_index is not None", "https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen =", "(self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start) return", "plot_area_height = max(0, widget_height - 2 * self.vertical_margin) # Set antialiasing ################################################ #", "transform ################################### filtered_data = [data_value for data_value in self.data if data_value is not", "= QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush =", "else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index", "############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) #", "= max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin", "(self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio *", "QColor from PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin", "len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size = self.size() widget_width = size.width()", "x_end, y_end # Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color", "None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end", "self.title_margin title_y_start = self.title_margin title_width = widget_width - 2 * self.title_margin title_height =", "self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen =", "widget_width - 2 * self.horizontal_margin) plot_area_height = max(0, widget_height - 2 * self.vertical_margin)", "qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position)", "widget_height = size.height() if num_bar > 0: plot_area_width = max(0, widget_width - 2", "black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen", "# x_start, y_start, x_end, y_end # Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine)", "x_start = self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value) # TODO: what", "= self.title_margin title_width = widget_width - 2 * self.title_margin title_height = self.title_size title_x_end", "data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not None: if data_color == \"green\":", "2 * self.title_margin title_height = self.title_size title_x_end = title_x_start + title_width title_y_end =", "self.vertical_margin = 10 self.data = None self.data_index = None self.data_color = None self.title", "- self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin +", "self.title = None self.title_size = 32 self.title_margin = 5 self.hlines = None self.hlines_style", "Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen", "= 0 if self.data_index is not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index)", "y_start = self.ordinateTransform(data_value) # TODO: what if y_start is None ? if y_start", "self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value:", "enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style = self.hlines_style[hline_index]", "None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size =", "import Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin", "qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end # Draw bars #######################################################", "title_width = widget_width - 2 * self.title_margin title_height = self.title_size title_x_end = title_x_start", "title_y_start = self.title_margin title_width = widget_width - 2 * self.title_margin title_height = self.title_size", "#see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine", "import math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10", "\"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length", "bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color =", "data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position", "yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush", "qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen and Brush ###############################################", "if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif", "= qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end", "+ self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height =", "import QWidget from PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt", "# Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ######################################################", "? if y_start is None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else:", "50 # Set window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette)", "window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event):", "= 32 self.title_margin = 5 self.hlines = None self.hlines_style = None self.ymin =", "QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"),", "not None] self.top_ordinate_value = max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value =", "qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin", "in enumerate(zip(self.data, self.data_color)): if data_value is not None: if data_color == \"green\": qp.setBrush(green_brush)", "Prepare coordinates transform ################################### filtered_data = [data_value for data_value in self.data if data_value", "Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ########################################################", "= self.plot_area_y_end y_length = y_end - y_start # Draw bar qp.drawRect(x_start, y_start, x_length,", "= 10 self.data = None self.data_index = None self.data_color = None self.title =", "math class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data", "what if y_start is None ? if y_start is None: if data_value >", "len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size = self.size() widget_width", "QBrush, QPen, QColor from PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def __init__(self):", "qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color = [None for data_value in", "self.title_size = 32 self.title_margin = 5 self.hlines = None self.hlines_style = None self.ymin", "= None self.ymin = None self.ymax = None self.x_label_height = 50 # Set", "Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color", "QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"),", "Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine)", "TODO: what if y_start is None ? if y_start is None: if data_value", "# Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value ->", "is not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\":", "self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) #", "\":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except:", "Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern)", "y_end # Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is", "= plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end =", "palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try: num_bar = len(self.data)", "= 5 self.hlines = None self.hlines_style = None self.ymin = None self.ymax =", "is not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO", "qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length =", "None: y_end = self.plot_area_y_end y_length = y_end - y_start # Draw bar qp.drawRect(x_start,", "self.top_ordinate_value = max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if", "Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern)", "plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end", "data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not None: if data_color", "= size.height() if num_bar > 0: plot_area_width = max(0, widget_width - 2 *", "y_length = y_end - y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def", "title_x_start + title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter,", "= QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2)", "pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end,", "event): qp = QPainter(self) try: num_bar = len(self.data) except: num_bar = 0 if", "is None: y_end = self.plot_area_y_end y_length = y_end - y_start # Draw bar", "= title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height", "= title_x_start + title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height,", "None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start", "pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen =", "pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color = [None for", "title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data", "red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush", "is None: self.data_color = [None for data_value in self.data] for data_index, (data_value, data_color)", "= (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio", "\"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\":", "and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size = self.size()", "QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"),", "= QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if", "QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black)", "QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def", "in self.data if data_value is not None] self.top_ordinate_value = max(filtered_data) if self.ymax is", "else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end", "len(data)\") # TODO size = self.size() widget_width = size.width() widget_height = size.height() if", "x_length y_start = self.ordinateTransform(data_value) # TODO: what if y_start is None ? if", "y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end", "self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start", "for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not None:", "== \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen)", "self.data_color is None: self.data_color = [None for data_value in self.data] for data_index, (data_value,", "= QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush =", "#pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine", "QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines is not None: for", "= self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height)", "self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin", "[None for data_value in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if", "data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color", "self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value) # TODO: what if y_start", "qp.setPen(pen) if self.data_color is None: self.data_color = [None for data_value in self.data] for", "data_value in self.data if data_value is not None] self.top_ordinate_value = max(filtered_data) if self.ymax", "= QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush =", "= 50 # Set window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white)", "# self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value", "pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen =", "if data_value is not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color", "= self.title_size title_x_end = title_x_start + title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start,", "None: for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not", "if self.hlines is not None: for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value)", "Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern)", "title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare", "y_end is None: y_end = self.plot_area_y_end y_length = y_end - y_start # Draw", "color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp =", "= max(0, widget_width - 2 * self.horizontal_margin) plot_area_height = max(0, widget_height - 2", "data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush)", "qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin +", "widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white,", "= None self.ymax = None self.x_label_height = 50 # Set window background color", "self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start) return math.floor(data_ordinate_position) else:", "hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style", "title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width = widget_width - 2", "is not None: for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position", "= QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush =", "pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap)", "size.height() if num_bar > 0: plot_area_width = max(0, widget_width - 2 * self.horizontal_margin)", "data_index * x_length y_start = self.ordinateTransform(data_value) # TODO: what if y_start is None", "title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height", "widget_width - 2 * self.title_margin title_height = self.title_size title_x_end = title_x_start + title_width", "and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"),", "Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines", "pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position,", "y_start, x_end, y_end # Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if", "self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value -", "plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin", "> 0: plot_area_width = max(0, widget_width - 2 * self.horizontal_margin) plot_area_height = max(0,", "self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not None:", "> self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if", "None self.data_index = None self.data_color = None self.title = None self.title_size = 32", "# Prepare coordinates transform ################################### filtered_data = [data_value for data_value in self.data if", "Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start", "self.title_margin = 5 self.hlines = None self.hlines_style = None self.ymin = None self.ymax", "None self.data_color = None self.title = None self.title_size = 32 self.title_margin = 5", "for data_value in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value", "pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) #", "https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw", "plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end", "if y_start is None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start", "data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate", "paintEvent(self, event): qp = QPainter(self) try: num_bar = len(self.data) except: num_bar = 0", "PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt import math class", "################################### filtered_data = [data_value for data_value in self.data if data_value is not None]", "max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is", "plot_area_width = max(0, widget_width - 2 * self.horizontal_margin) plot_area_height = max(0, widget_height -", "= [None for data_value in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)):", "################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font =", "is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width", "= QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw", "QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"),", "qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"),", "!= len(data)\") # TODO size = self.size() widget_width = size.width() widget_height = size.height()", "TODO # Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3,", "# Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine)", "qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen and Brush ############################################### #see", "x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index * x_length y_start", "x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end", "= [data_value for data_value in self.data if data_value is not None] self.top_ordinate_value =", "* self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) #", "= QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush =", "len(self.data) except: num_bar = 0 if self.data_index is not None and len(self.data_index) !=", "- self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start) return math.floor(data_ordinate_position)", "3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) #", "None] self.top_ordinate_value = max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data)", "- 2 * self.title_margin title_height = self.title_size title_x_end = title_x_start + title_width title_y_end", "# Draw bars ####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None:", "not None: for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if hline_position is", "- y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): #", "Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size)", "else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start,", "= QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen", "Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern)", "TODO size = self.size() widget_width = size.width() widget_height = size.height() if num_bar >", "#red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines is not", "not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush)", "widget_height - 2 * self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing See", "self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush", "is None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end", "self.size() widget_width = size.width() widget_height = size.height() if num_bar > 0: plot_area_width =", "self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start =", "== \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start", "- data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end", "ValueError(\"len(data_index) != len(data)\") # TODO size = self.size() widget_width = size.width() widget_height =", "self.data_index = None self.data_color = None self.title = None self.title_size = 32 self.title_margin", "self.data_color = [None for data_value in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data,", "class QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data =", "- self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern)", "self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style = self.hlines_style[hline_index] if hline_style ==", "brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set", "green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush", "self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try: num_bar = len(self.data) except: num_bar", "= math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index * x_length y_start =", "self.hlines is not None: for hline_index, hline_value in enumerate(self.hlines): hline_position = self.ordinateTransform(hline_value) if", "if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end =", "hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine)", "Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO # Set Pen and Brush", "= size.width() widget_height = size.height() if num_bar > 0: plot_area_width = max(0, widget_width", "raise ValueError(\"len(data_index) != len(data)\") # TODO size = self.size() widget_width = size.width() widget_height", "+ data_index * x_length y_start = self.ordinateTransform(data_value) # TODO: what if y_start is", "None self.title_size = 32 self.title_margin = 5 self.hlines = None self.hlines_style = None", "= None self.title = None self.title_size = 32 self.title_margin = 5 self.hlines =", "lines ########################################### if self.hlines is not None: for hline_index, hline_value in enumerate(self.hlines): hline_position", "def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data = None self.data_index", "title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data = [data_value for data_value", "[data_value for data_value in self.data if data_value is not None] self.top_ordinate_value = max(filtered_data)", "self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush)", "= self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style = self.hlines_style[hline_index] if hline_style", "= QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush =", "self.horizontal_margin = 10 self.vertical_margin = 10 self.data = None self.data_index = None self.data_color", "background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp", "qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width =", "y_start is None ? if y_start is None: if data_value > self.bottom_ordinate_value: y_start", "enumerate(zip(self.data, self.data_color)): if data_value is not None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen)", "data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end -", "Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern)", "None ? if y_start is None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start", "self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self)", "None self.x_label_height = 50 # Set window background color self.setAutoFillBackground(True) palette = self.palette()", "qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data =", "https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine", "self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self, event): qp = QPainter(self) try: num_bar =", "None: if data_color == \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen)", "if self.ymax is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None", "!= len(self.data): raise ValueError(\"len(data_index) != len(data)\") # TODO size = self.size() widget_width =", "# Set window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def", "if self.data_color is None: self.data_color = [None for data_value in self.data] for data_index,", "= self.size() widget_width = size.width() widget_height = size.height() if num_bar > 0: plot_area_width", "= None self.data_index = None self.data_color = None self.title = None self.title_size =", "0 if self.data_index is not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) !=", "ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <=", "data_value in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is", "self.ymax = None self.x_label_height = 50 # Set window background color self.setAutoFillBackground(True) palette", "Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data = [data_value for data_value in", "for data_value in self.data if data_value is not None] self.top_ordinate_value = max(filtered_data) if", "qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index *", "qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen)", "def paintEvent(self, event): qp = QPainter(self) try: num_bar = len(self.data) except: num_bar =", "num_bar = 0 if self.data_index is not None and len(self.data_index) != len(self.data): raise", "2 * self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing)", "filtered_data = [data_value for data_value in self.data if data_value is not None] self.top_ordinate_value", "self.horizontal_margin) plot_area_height = max(0, widget_height - 2 * self.vertical_margin) # Set antialiasing ################################################", "hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else:", "num_bar = len(self.data) except: num_bar = 0 if self.data_index is not None and", "Set window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.white) self.setPalette(palette) def paintEvent(self,", "###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width = widget_width - 2 *", "+ title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ###################################", "red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush", "= self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value) # TODO: what if", "# Draw title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width = widget_width", "Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines", "0: plot_area_width = max(0, widget_width - 2 * self.horizontal_margin) plot_area_height = max(0, widget_height", "# Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See", "hline_position = self.ordinateTransform(hline_value) if hline_position is not None: try: hline_style = self.hlines_style[hline_index] if", "plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height", "qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end #", "PyQt5.QtWidgets import QWidget from PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import", "# Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font", "self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin -", "font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin title_width", "in self.data] for data_index, (data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not", "(data_value, data_color) in enumerate(zip(self.data, self.data_color)): if data_value is not None: if data_color ==", "= y_end - y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self,", "QBarPlot(QWidget): def __init__(self): super().__init__() self.horizontal_margin = 10 self.vertical_margin = 10 self.data = None", "title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform", "size.width() widget_height = size.height() if num_bar > 0: plot_area_width = max(0, widget_width -", "elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width /", "self.x_label_height = 50 # Set window background color self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(),", "font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin title_y_start", "is not None: try: hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen =", "y_end = self.ordinateTransform(0) if y_end is None: y_end = self.plot_area_y_end y_length = y_end", "y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value", "and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen()", "= self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen", "Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black, Qt.SolidLine)", "self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end", "yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush", "Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate): # self.top_ordinate_value -> self.plot_area_y_start", "# Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font()", "= QPainter(self) try: num_bar = len(self.data) except: num_bar = 0 if self.data_index is", "if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value", "self.data_index is not None and len(self.data_index) != len(self.data): raise ValueError(\"len(data_index) != len(data)\") #", "* x_length y_start = self.ordinateTransform(data_value) # TODO: what if y_start is None ?", "# TODO size = self.size() widget_width = size.width() widget_height = size.height() if num_bar", "* self.title_margin title_height = self.title_size title_x_end = title_x_start + title_width title_y_end = title_y_start", "try: hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen)", "pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color = [None for data_value in self.data]", "\"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start =", "Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern)", "= 10 self.vertical_margin = 10 self.data = None self.data_index = None self.data_color =", "<= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position =", "from PyQt5.QtGui import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt import math", "Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen =", "QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"),", "self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO #", "= QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush =", "qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width", "None self.title = None self.title_size = 32 self.title_margin = 5 self.hlines = None", "self.ordinateTransform(data_value) # TODO: what if y_start is None ? if y_start is None:", "== \":\": pen = qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen)", "is not None] self.top_ordinate_value = max(filtered_data) if self.ymax is None else self.ymax self.bottom_ordinate_value", "qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen)", "math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value)", "= self.ordinateTransform(data_value) # TODO: what if y_start is None ? if y_start is", "= None self.hlines_style = None self.ymin = None self.ymax = None self.x_label_height =", "#green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern) #yellow_brush = QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) #", "num_bar) x_start = self.horizontal_margin + data_index * x_length y_start = self.ordinateTransform(data_value) # TODO:", "Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and", "data_value is not None] self.top_ordinate_value = max(filtered_data) if self.ymax is None else self.ymax", "= min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end =", "self.ymin = None self.ymax = None self.x_label_height = 50 # Set window background", "- self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width, plot_area_height) # TODO", "if num_bar > 0: plot_area_width = max(0, widget_width - 2 * self.horizontal_margin) plot_area_height", "= max(0, widget_height - 2 * self.vertical_margin) # Set antialiasing ################################################ # Set", "####################################################### pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color = [None", "num_bar > 0: plot_area_width = max(0, widget_width - 2 * self.horizontal_margin) plot_area_height =", "+ self.vertical_margin self.plot_area_y_end = widget_height - self.vertical_margin - self.x_label_height plot_area_height = self.plot_area_y_end -", "green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen = QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush", "import QPainter, QBrush, QPen, QColor from PyQt5.QtCore import Qt import math class QBarPlot(QWidget):", "QPainter(self) try: num_bar = len(self.data) except: num_bar = 0 if self.data_index is not", "== \"green\": qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color ==", "See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) #", "pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen", "10 self.vertical_margin = 10 self.data = None self.data_index = None self.data_color = None", "- plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin + self.vertical_margin self.plot_area_y_end = widget_height -", "self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start", "= QPen() pen.setStyle(Qt.SolidLine) # Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin)", "None: self.data_color = [None for data_value in self.data] for data_index, (data_value, data_color) in", "self.title) # Prepare coordinates transform ################################### filtered_data = [data_value for data_value in self.data", "qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin title_y_start = self.title_margin", "QPen(QColor(\"#a40000\"), Qt.SolidLine) white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"),", "= qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin title_y_start =", "-> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate)", "Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines is not None: for hline_index,", "32 self.title_margin = 5 self.hlines = None self.hlines_style = None self.ymin = None", "else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None: y_end =", "10 self.data = None self.data_index = None self.data_color = None self.title = None", "self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set", "hline_position) # x_start, y_start, x_end, y_end # Draw bars ####################################################### pen = qp.pen()", "self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value -", "self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start,", "= QPen(Qt.black, Qt.SolidLine) green_pen = QPen(QColor(\"#4e9a06\"), Qt.SolidLine) yellow_pen = QPen(QColor(\"#c4a000\"), Qt.SolidLine) red_pen =", "is None ? if y_start is None: if data_value > self.bottom_ordinate_value: y_start =", "Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black, 3, Qt.SolidLine) pen = QPen() pen.setStyle(Qt.SolidLine)", "title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates transform ################################### filtered_data = [data_value for", "y_end = self.plot_area_y_end y_length = y_end - y_start # Draw bar qp.drawRect(x_start, y_start,", "y_end - y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length) def ordinateTransform(self, data_ordinate):", "Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush = QBrush(QColor(\"#cc0000\"), Qt.SolidPattern) #green_brush = QBrush(QColor(\"#8ae234\"), Qt.SolidPattern)", "self.title_size title_x_end = title_x_start + title_width title_y_end = title_y_start + title_height qp.drawText(title_x_start, title_y_start,", "hline_position, plot_area_x_end, hline_position) # x_start, y_start, x_end, y_end # Draw bars ####################################################### pen", "self.plot_area_y_end y_length = y_end - y_start # Draw bar qp.drawRect(x_start, y_start, x_length, y_length)", "Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines is", "= QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines is not None:", "self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None: y_end", "coordinates transform ################################### filtered_data = [data_value for data_value in self.data if data_value is", "if y_end is None: y_end = self.plot_area_y_end y_length = y_end - y_start #", "plot_area_height) # TODO # Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen =", "max(0, widget_height - 2 * self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing", "else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else self.ymin plot_area_x_start =", "= None self.title_size = 32 self.title_margin = 5 self.hlines = None self.hlines_style =", "-> self.plot_area_y_start # self.bottom_ordinate_value -> self.plot_area_y_end if self.bottom_ordinate_value <= data_ordinate <= self.top_ordinate_value: data_ordinate_ratio", "if data_value is not None] self.top_ordinate_value = max(filtered_data) if self.ymax is None else", "QBrush(QColor(\"#fce94f\"), Qt.SolidPattern) #red_brush = QBrush(QColor(\"#ef2929\"), Qt.SolidPattern) # Draw horizontal lines ########################################### if self.hlines", "is None else self.ymax self.bottom_ordinate_value = min(filtered_data) if self.ymin is None else self.ymin", "antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font", "- 2 * self.vertical_margin) # Set antialiasing ################################################ # Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration", "########################################### if self.hlines is not None: for hline_index, hline_value in enumerate(self.hlines): hline_position =", "qp.setBrush(green_brush) qp.setPen(green_pen) elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush)", "self.title_margin title_height = self.title_size title_x_end = title_x_start + title_width title_y_end = title_y_start +", "y_start is None: if data_value > self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start =", "not None: try: hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen = qp.pen()", "hline_position is not None: try: hline_style = self.hlines_style[hline_index] if hline_style == \":\": pen", "# TODO # Set Pen and Brush ############################################### #see https://hci.isir.upmc.fr/wp-content/uploads/2018/03/PyQt-Dessin.pdf #pen = QPen(Qt.black,", "plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start, self.plot_area_y_start, plot_area_width,", "Draw horizontal lines ########################################### if self.hlines is not None: for hline_index, hline_value in", "widget_width - self.horizontal_margin plot_area_width = plot_area_x_end - plot_area_x_start self.plot_area_y_start = title_y_end + self.title_margin", "qp.setRenderHint(QPainter.Antialiasing) # Set Font ######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title", "Qt.DotLine Qt.DashLine Qt.DashDotLine pen.setWidth(2) pen.setBrush(Qt.black) # Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette", "qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar) x_start = self.horizontal_margin + data_index * x_length", "data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else: qp.setBrush(white_brush) qp.setPen(black_pen) x_length = math.floor(plot_area_width / num_bar)", "QPen, QColor from PyQt5.QtCore import Qt import math class QBarPlot(QWidget): def __init__(self): super().__init__()", "/ (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start + data_ordinate_ratio * (self.plot_area_y_end - self.plot_area_y_start)", "title_x_start = self.title_margin title_y_start = self.title_margin title_width = widget_width - 2 * self.title_margin", "pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) #", "= qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen =", "pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen() pen.setStyle(Qt.SolidLine)", "qp.pen() pen.setStyle(Qt.DotLine) qp.setPen(pen) else: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) except: pen = qp.pen()", "except: pen = qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) qp.drawLine(plot_area_x_start, hline_position, plot_area_x_end, hline_position) # x_start, y_start,", "= len(self.data) except: num_bar = 0 if self.data_index is not None and len(self.data_index)", "data_ordinate_ratio = (self.top_ordinate_value - data_ordinate) / (self.top_ordinate_value - self.bottom_ordinate_value) data_ordinate_position = self.plot_area_y_start +", "= title_y_start + title_height qp.drawText(title_x_start, title_y_start, title_width, title_height, Qt.AlignCenter, self.title) # Prepare coordinates", "elif data_color == \"yellow\": qp.setBrush(yellow_brush) qp.setPen(yellow_pen) elif data_color == \"red\": qp.setBrush(red_brush) qp.setPen(red_pen) else:", "self.bottom_ordinate_value: y_start = self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end", "= self.plot_area_y_start else: y_start = self.plot_area_y_end y_end = self.ordinateTransform(0) if y_end is None:", "if hline_position is not None: try: hline_style = self.hlines_style[hline_index] if hline_style == \":\":", "######################################################## font = qp.font() font.setPointSize(self.title_size) qp.setFont(font) # Draw title ###################################################### title_x_start = self.title_margin", "self.ymin plot_area_x_start = self.horizontal_margin plot_area_x_end = widget_width - self.horizontal_margin plot_area_width = plot_area_x_end -", "- self.x_label_height plot_area_height = self.plot_area_y_end - self.plot_area_y_start brush = QBrush(Qt.white, Qt.SolidPattern) qp.setBrush(brush) qp.drawRect(plot_area_x_start,", "# Qt.green pen.setCapStyle(Qt.RoundCap) pen.setJoinStyle(Qt.RoundJoin) qp.setPen(pen) # See https://en.wikipedia.org/wiki/Tango_Desktop_Project#Palette and https://web.archive.org/web/20160202102503/http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines black_pen = QPen(Qt.black,", "5 self.hlines = None self.hlines_style = None self.ymin = None self.ymax = None", "= qp.pen() pen.setStyle(Qt.SolidLine) qp.setPen(pen) if self.data_color is None: self.data_color = [None for data_value", "white_brush = QBrush(Qt.white, Qt.SolidPattern) green_brush = QBrush(QColor(\"#73d216\"), Qt.SolidPattern) yellow_brush = QBrush(QColor(\"#edd400\"), Qt.SolidPattern) red_brush" ]
[ "self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon =", "turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\")", "dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename)", "self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def", "self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text)", "quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if", "= [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button)", "debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left", "ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename", "buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for", "quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right", "QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons", "QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size)", "self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon", "buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout =", "% self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status()", "= 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug =", "turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button", "= self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R", "quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout()", "save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self)", "# right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout)", "icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self)", "self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last", "self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel()", "= \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string)", "buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides", "= ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout", "QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text =", "sys import os import signal from PyQt5.QtWidgets import * from PyQt5.QtCore import *", "turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug >", "QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path,", "def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug", "import * from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app", "self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to", "= QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path =", "= QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40)", "ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout =", "ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path))", "from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from", "import signal from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import", "= os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class", "color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self):", "%s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self):", "from PyQt5.QtCore import * from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT,", "def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show()", "def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s'", "QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon)", "= os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs =", "left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label =", "last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text)", "self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel()", "QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button)", "self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label)", "to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer =", "replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path =", "from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path", "= QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button", "right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string", "update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' %", "QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout = QVBoxLayout()", "self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons = [] turn_on_button", "= QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons:", "PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from replay_sorcery", "#!/usr/bin/python3 import sys import os import signal from PyQt5.QtWidgets import * from PyQt5.QtCore", "QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout", "self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on()", "if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug", "self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side", "in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both", "left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text =", "self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150,", "PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name", "# both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" %", "import sys import os import signal from PyQt5.QtWidgets import * from PyQt5.QtCore import", "self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit()", "self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn on\")", "def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window", "os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug):", "'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug", "refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in", "self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer", "button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout)", "= QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30", "off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action)", "self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0:", "ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug > 0: print(\"ReplaySorceryGUI started\") app.exec_()", "seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size", "QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\")", "signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png'", "turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button", "app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path", "%s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def", "= 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off()", "left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout)", "* from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app =", "text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"]", "PyQt5.QtCore import * from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL)", "92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe", "= QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons = [] turn_on_button =", "app_layout = QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path)", "buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action)", "'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def", "= QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string =", "QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text)", "left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter)", "def __init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300)", "40) buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn", "self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1)", "import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name)", "* from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0])", "self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self):", "class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI')", "> 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug > 0:", "button_size = QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action)", "import * from PyQt5.QtCore import * from PyQt5.QtGui import * from replay_sorcery import", "= QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button =", "= os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self,", "side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self):", "sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string)", "left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92)", "__init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout", "icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs", "self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons =", "QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery:", "both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"]", "turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button", "0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug > 0: print(\"ReplaySorceryGUI", "\"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status()", "def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting", "self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text", "turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button =", "side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label", "app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string", "os import signal from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui", "signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name = os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename =", "self.timer.start(1000) button_size = QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button)", "button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) #", "QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon =", "self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout()", "= QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel()", "self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color:", "os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug = debug self.rs = ReplaySorcery(self.debug)", "self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def quit_action(self): if", "import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([]) dir_name =", "app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\" % self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string =", "from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery signal.signal(signal.SIGINT, signal.SIG_DFL) app = QApplication([])", "icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def __init__(self, debug): self.debug", "= QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon", "QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text = QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\")", "= QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side", "self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self): self.rs.turn_on() def turn_off_action(self): self.rs.turn_off() def refresh_action(self): self.rs.get_status() def", "on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button)", "signal from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import *", "left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size =", "right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def update_status_text(self): text_string = \"ReplaySorcery: %s\"", "left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons = []", "full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget): def", "buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button)", "* from PyQt5.QtCore import * from PyQt5.QtGui import * from replay_sorcery import ReplaySorcery", "self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug >", "30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text() left_layout.addWidget(self.status_text) self.timer = QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000)", "for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) # right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter)", "refresh_action(self): self.rs.get_status() def quit_action(self): if self.debug > 0: print(\"Exiting ReplaySorceryGUI\") sys.exit() window =", "QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button =", "buttons = [] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\")", "= QLabel() self.instructions_text.setText(\"Ctrl+Super+R to save\\nthe last 30 seconds\\n\") left_layout.addWidget(self.instructions_text) self.status_text = QLabel() self.update_status_text()", "print(\"Exiting ReplaySorceryGUI\") sys.exit() window = ReplaySorceryGUI(1) window.show() if window.debug > 0: print(\"ReplaySorceryGUI started\")", "self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() # left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter)", "= debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout = QHBoxLayout() #", "% self.rs.current_status[\"name\"] self.status_text.setText(text_string) color_string = 'color: %s' % self.rs.current_status[\"color\"] self.status_text.setStyleSheet(color_string) self.rs.get_status() def turn_on_action(self):", "import os import signal from PyQt5.QtWidgets import * from PyQt5.QtCore import * from", "# left side left_layout = QVBoxLayout() left_layout.setAlignment(Qt.AlignCenter) self.icon = QPixmap(icon_path) self.icon = self.icon.scaled(92,", "debug): self.debug = debug self.rs = ReplaySorcery(self.debug) QWidget.__init__(self) self.setWindowTitle('ReplaySorceryGUI') self.setWindowIcon(QIcon(icon_path)) self.setMinimumWidth(300) app_layout =", "os.path.dirname(sys.argv[0]) full_path = os.path.abspath(dir_name) icon_filename = 'icon.png' icon_path = os.path.join(full_path, icon_filename) class ReplaySorceryGUI(QWidget):", "QTimer(self) self.timer.timeout.connect(self.update_status_text) self.timer.start(1000) button_size = QSize(150, 40) buttons = [] turn_on_button = QPushButton(\"Turn", "refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\") buttons.append(quit_button) quit_button.clicked.connect(self.quit_action) for button in buttons: button.setFixedSize(button_size) left_layout.addWidget(button) #", "[] turn_on_button = QPushButton(\"Turn on\") buttons.append(turn_on_button) turn_on_button.clicked.connect(self.turn_on_action) turn_off_button = QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action)", "= QPixmap(icon_path) self.icon = self.icon.scaled(92, 92) self.icon_label = QLabel() self.icon_label.setPixmap(self.icon) self.icon_label.setAlignment(Qt.AlignCenter) left_layout.addWidget(self.icon_label) self.instructions_text", "right side right_layout = QVBoxLayout() right_layout.setAlignment(Qt.AlignCenter) # both sides app_layout.addLayout(left_layout) app_layout.addLayout(right_layout) self.setLayout(app_layout) def", "= QPushButton(\"Turn off\") buttons.append(turn_off_button) turn_off_button.clicked.connect(self.turn_off_action) refresh_button = QPushButton(\"Refresh\") buttons.append(refresh_button) refresh_button.clicked.connect(self.refresh_action) quit_button = QPushButton(\"Quit\")" ]
[ "self.PGGAN.forward(code,) # Matlab version default to 0.7 return torch.clamp((imgs + 1.0) / 2.0,", "T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\"", "% np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"%", "model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%%", "H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) #", "generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def", "evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from", "= compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\")", "EPS 1.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.046 # EPS", "Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened", "0.877 #%% H_col = [] for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1,", "vs BackwardIter 1.000 # Correlation of Flattened Hessian matrix BP vs ForwardIter 0.877", "corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin,", "H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian matrix BP vs", "H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(),", "= np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"]", "[] # for triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali))", "= average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col,", "1E-1, 1, 2, 10]: T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat,", "1.0e-04 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.999 # EPS 1.0e-03", "evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() -", "= np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg,", "T0)) # 95.7 sec T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat,", "2.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.008 # EPS 1.0e+01", "print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1])", "St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col = []", "visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default to 0.7 return", "eva_col = [] # evc_col = [] # for triali in tqdm(range(400)): #", "\"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP)", "of Flattened Hessian matrix BP vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir", "% triali)) # eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) #", "T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f", "Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened", "1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 = time() eva_FI, evc_FI, H_FI =", "use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col,", "BP vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington", "fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col, evc_col, figdir=figdir, nsamp=5,", "1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%%", "Correlation of Flattened Hessian matrix BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation", "Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else", "featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg,", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.877 # Correlation of Flattened", "\"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"),", "of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation", "model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN", "vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened Hessian matrix BP vs", "vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened Hessian matrix BP vs", "without cuda 12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col,", "Hessian matrix BP vs BackwardIter 1.000 # Correlation of Flattened Hessian matrix BP", "BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP vs", "of Flattened Hessian matrix BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of", "compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\")", "np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian", "Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0,", "= np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col,", "1.0e-03 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.989 # EPS 1.0e-02", "BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened Hessian matrix BP", "of Flattened Hessian matrix BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of", "sec\" % (time() - T0)) # 61.8 sec T0 = time() eva_BP, evc_BP,", "= model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise)", "EPS 1.0e-02 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.901 # EPS", "in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"]", "Flattened Hessian matrix BP vs ForwardIter 0.877 # Correlation of Flattened Hessian matrix", "matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian", "Flattened Hessian matrix BP vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir =", "%.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter", "vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix BP", "# # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H,", "code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default to 0.7 return torch.clamp((imgs", "BP vs BackwardIter 1.000 # Correlation of Flattened Hessian matrix BP vs ForwardIter", "r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col = [] # for triali in", "triali)) # eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP)", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation", "vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened Hessian matrix BP vs", "else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise,", "ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs", "in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 = time() eva_FI,", "= r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col = [] # for triali", "pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad():", "#%% H_col = [] for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1,", "= PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default", "hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) # 95.7 sec", "plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) #", "Hessian matrix BP vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive", "def __init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs =", "#%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ):", "= r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col", "print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])", "\"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%%", "noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%% class", "# EPS 1.0e-01 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.398 #", "1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 = time() eva_FI, evc_FI, H_FI", "import join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu", "%.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix BP vs BackwardIter", "# 95.7 sec T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist,", "[1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 = time() eva_FI, evc_FI,", "H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian matrix", "BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened Hessian matrix BP", "plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col, evc_col, figdir=figdir, nsamp=5, titstr=\"PGGAN\",) fig3.show()", "= [] # evc_col = [] # for triali in tqdm(range(400)): # data", "np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix BP vs BackwardIter 1.000", "Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened", "np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", )", "data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import", "noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%% img", "eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # #", "evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with cuda 8:21 # corr_mat_log,", "# 95.4 sec #%% print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter %.3f\"", "ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) # 61.8 sec T0 =", "0.008 # EPS 1.0e+01 Correlation of Flattened Hessian matrix BP vs ForwardIter -0.003", "ForwardIter 0.877 # Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%%", "# 61.8 sec T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist,", "data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col =", "vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened Hessian matrix BP vs", "0.989 # EPS 1.0e-02 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.901", "= torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images)", "Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col = [] for EPS", "Matlab version default to 0.7 return torch.clamp((imgs + 1.0) / 2.0, 0, 1)", "1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1])", "in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col =", "evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin =", "# with torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper():", "eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig", "average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir,", "ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix", "matrix BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened Hessian matrix", "ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter", "evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian matrix BP vs ForwardIter", "scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0 =", "print(\"%.2f sec\" % (time() - T0)) # 95.4 sec #%% print(\"Correlation of Flattened", "of Flattened Hessian matrix BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of", "Flattened Hessian matrix BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened", "#%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col,", "tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] #", "matrix BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened Hessian matrix", "1.0e-01 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.398 # EPS 1.0e+00", "eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() -", "Flattened Hessian matrix BP vs BackwardIter 1.000 # Correlation of Flattened Hessian matrix", "H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian matrix BP vs ForwardIter 1.000", "matrix BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened Hessian matrix", "Visualize Spectra figdir = r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir =", "ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened Hessian matrix BP vs ForwardIter", "class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self,", "matrix BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened Hessian matrix", "eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg,", "Hessian matrix BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened Hessian", "feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) # 95.7 sec T0", "%.1e Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(),", "1.0e-05 Correlation of Flattened Hessian matrix BP vs ForwardIter 1.000 # EPS 1.0e-04", "= self.PGGAN.forward(code,) # Matlab version default to 0.7 return torch.clamp((imgs + 1.0) /", "Flattened Hessian matrix BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened", "0, 1) * scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS =", "/ 2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda()", "# Matlab version default to 0.7 return torch.clamp((imgs + 1.0) / 2.0, 0,", "eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr,", "of Flattened Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation", "(time() - T0)) # 95.7 sec T0 = time() eva_FI, evc_FI, H_FI =", "= True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu)", "evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig =", "version default to 0.7 return torch.clamp((imgs + 1.0) / 2.0, 0, 1) *", "# Correlation of Flattened Hessian matrix BP vs ForwardIter 0.877 # Correlation of", "# EPS 1.0e-05 Correlation of Flattened Hessian matrix BP vs ForwardIter 1.000 #", "EPS 1.0e+01 Correlation of Flattened Hessian matrix BP vs ForwardIter -0.003 #%% #%%", "PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self, code,", "time from os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist", "noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat,", "from os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist =", "hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) # 61.8 sec T0 = time()", "matrix BP vs ForwardIter 0.877 # Correlation of Flattened Hessian matrix ForwardIter vs", "0.901 # EPS 1.0e-01 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.398", "time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time()", "PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI, evc_BI,", "%.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter", "evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat,", "evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3", "1.0) / 2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG) #%% feat =", "Flattened Hessian matrix BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened", "to 0.7 return torch.clamp((imgs + 1.0) / 2.0, 0, 1) * scale G", "# 325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian matrix BP vs ForwardIter", "nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs", "T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\"", "Flattened Hessian matrix BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened", "ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened Hessian matrix BP vs ForwardIter", "(time() - T0)) # 61.8 sec T0 = time() eva_BP, evc_BP, H_BP =", "evc_col = [] # for triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\"", "# Correlation of Flattened Hessian matrix BP vs BackwardIter 1.000 # Correlation of", "feat = noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI, evc_BI, H_BI =", "vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened Hessian matrix BP vs", "ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0)) # 325.83 sec print(\"EPS", "sec print(\"EPS %.1e Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" %", "0.7 return torch.clamp((imgs + 1.0) / 2.0, 0, 1) * scale G =", "hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) # 95.4 sec", "ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub',", "evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0))", "# eva_col = [] # evc_col = [] # for triali in tqdm(range(400)):", "T0)) # 61.8 sec T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat,", "figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 =", "from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available()", "feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) # 95.4 sec #%%", "325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\"", "ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened Hessian matrix BP vs ForwardIter", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation", "% (time() - T0)) # 95.7 sec T0 = time() eva_FI, evc_FI, H_FI", "# EPS 1.0e+01 Correlation of Flattened Hessian matrix BP vs ForwardIter -0.003 #%%", "# EPS 1.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.046 #", "figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without", "BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened Hessian matrix BP", "__init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,)", "feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col,", "T0)) # 95.4 sec #%% print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter", "= [] for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]:", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation", "vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened Hessian matrix BP vs", "of Flattened Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation", "ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05", "figdir = r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" #", "#%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir", "hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) # 61.8 sec", "plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col", "torch.clamp((imgs + 1.0) / 2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG) #%%", "0.877 # Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col", "Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta =", "torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1", "1.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.046 # EPS 2.0e+00", "matrix BP vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive -", "Hessian matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI,", "BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix", "matrix ForwardIter vs BackwardIter 0.877 #%% H_col = [] for EPS in [1E-5,", "8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 =", "torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True)", "1, 2, 10]: T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist,", "#%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI, evc_BI, H_BI", "scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir,", "time import time from os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation", "= PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI,", "np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" %", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation", "of Flattened Hessian matrix BP vs BackwardIter 1.000 # Correlation of Flattened Hessian", "vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS", "img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN", "1E-2, 1E-1, 1, 2, 10]: T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G,", "matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian", "T0)) # 325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian matrix BP vs", "EPS = 1E-2 T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist,", "# evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example,", "use_gpu = True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True,", "BackwardIter 1.000 # Correlation of Flattened Hessian matrix BP vs ForwardIter 0.877 #", "= plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col, evc_col, figdir=figdir, nsamp=5, titstr=\"PGGAN\",)", "sec\" % (time() - T0)) # 95.7 sec T0 = time() eva_FI, evc_FI,", "fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir,", "#%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN def", "hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) # 95.7 sec T0 = time()", "np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] #", "matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian", "compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with cuda 8:21 #", "_ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise) #%% img =", "): self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab", "#%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col, evc_col,", "2, 10]: T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\",", "ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened Hessian matrix BP vs ForwardIter", "evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0))", "ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened Hessian matrix BP vs ForwardIter", "vs ForwardIter -0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington University", "imgs = self.PGGAN.forward(code,) # Matlab version default to 0.7 return torch.clamp((imgs + 1.0)", "ForwardIter -0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington University in", "1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened Hessian matrix BP", "1]) print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0,", "compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%%", "model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with", "1) * scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2", "PGGAN, ): self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) #", "os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda()", "[] # evc_col = [] # for triali in tqdm(range(400)): # data =", "time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time()", "model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ =", ") #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11", "use_cuda=True) # without cuda 12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin =", "EPS 2.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.008 # EPS", "np from time import time from os.path import join import lpips from Hessian.GAN_hessian_compute", "# EPS 2.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.008 #", "H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%%", "vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP", "1.0e-02 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.901 # EPS 1.0e-01", "savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col = [] # for", "hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) # 95.4 sec #%% print(\"Correlation of", "H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0))", "fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir, titstr=\"PGGAN\") #%% fig3 = plot_consistency_example(eva_col, evc_col, figdir=figdir,", "EPS 1.0e-03 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.989 # EPS", "1E-2 T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f", "print(\"%.2f sec\" % (time() - T0)) # 95.7 sec T0 = time() eva_FI,", "sec T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f", "Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col = []", "BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) #", "%.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation", "evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg", "= hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) # 95.7", "BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened Hessian matrix BP", "triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP =", "-0.003 #%% #%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington University in St.", "sec\" % (time() - T0)) # 325.83 sec print(\"EPS %.1e Correlation of Flattened", "matrix BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened Hessian matrix", "Hessian matrix BP vs ForwardIter 0.877 # Correlation of Flattened Hessian matrix ForwardIter", "University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col", "feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0)) # 325.83 sec", "# evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col)", "- T0)) # 95.7 sec T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G,", "Flattened Hessian matrix BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation of Flattened", "default to 0.7 return torch.clamp((imgs + 1.0) / 2.0, 0, 1) * scale", "BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened Hessian matrix BP", "Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of", "- T0)) # 325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian matrix BP", "= lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN',", "of Flattened Hessian matrix BP vs ForwardIter 0.877 # Correlation of Flattened Hessian", "= [] # for triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" %", "= 1E-2 T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\")", "meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col,", "feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg =", "# evc_col = [] # for triali in tqdm(range(400)): # data = np.load(join(savedir,", "= compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with cuda 8:21", "# eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz", "# eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra,", "- T0)) # 61.8 sec T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G,", "Hessian matrix BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened Hessian", "= model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self,", "- Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = []", "(time() - T0)) # 95.4 sec #%% print(\"Correlation of Flattened Hessian matrix BP", "1.0e+01 Correlation of Flattened Hessian matrix BP vs ForwardIter -0.003 #%% #%% Visualize", "= data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col", "0.046 # EPS 2.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.008", "feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg,", "hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0)) # 325.83 sec print(\"EPS %.1e", "= hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) # 95.4", "Correlation of Flattened Hessian matrix BP vs ForwardIter 0.999 # EPS 1.0e-03 Correlation", "data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] # evc_BP =", "Hessian matrix BP vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened Hessian", "mins, with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%%", "eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() -", "of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col = [] for", "1.000 # Correlation of Flattened Hessian matrix BP vs ForwardIter 0.877 # Correlation", "of Flattened Hessian matrix BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of", "EPS=EPS) print(\"%.2f sec\" % (time() - T0)) # 325.83 sec print(\"EPS %.1e Correlation", "import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True", "def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default to 0.7", "+ 1.0) / 2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG) #%% feat", "EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 = time()", "torch import numpy as np from time import time from os.path import join", "from time import time from os.path import join import lpips from Hessian.GAN_hessian_compute import", "matrix BP vs BackwardIter 1.000 # Correlation of Flattened Hessian matrix BP vs", "print(\"%.2f sec\" % (time() - T0)) # 61.8 sec T0 = time() eva_BP,", "# EPS 1.0e-04 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.999 #", "cuda 12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir,", "import numpy as np from time import time from os.path import join import", "= time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" %", "matrix BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened Hessian matrix", "titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda", "# Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col =", "% np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\"", "1.000 # EPS 1.0e-04 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.999", "vs ForwardIter 0.877 # Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter 0.877", "np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col)", "#%% print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0,", "BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix BP vs", "cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2", "plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col =", "BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of Flattened Hessian matrix BP", "= time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" %", "% (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of", "Flattened Hessian matrix BP vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of", "Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] # evc_col = [] #", "95.7 sec T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\")", "Hessian matrix BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of Flattened Hessian", "numpy as np from time import time from os.path import join import lpips", "r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col =", "= noise.detach().clone().cuda() EPS = 1E-2 T0 = time() eva_BI, evc_BI, H_BI = hessian_compute(G,", "eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col,", "sec #%% print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(),", "matrix BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened Hessian matrix", "print(\"EPS %.1e Correlation of Flattened Hessian matrix BP vs ForwardIter %.3f\" % (EPS,", "evc_col) np.savez(join(figdir, \"H_avg_%s.npz\"%\"PGGAN\"), H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\",", "corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with cuda", "eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() -", "of Flattened Hessian matrix BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of", "% (time() - T0)) # 61.8 sec T0 = time() eva_BP, evc_BP, H_BP", "Hessian matrix BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened Hessian", "Correlation of Flattened Hessian matrix BP vs ForwardIter -0.003 #%% #%% Visualize Spectra", "lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256',", "import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False", "feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) # 61.8 sec T0", "95.4 sec #%% print(\"Correlation of Flattened Hessian matrix BP vs BackwardIter %.3f\" %", "eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time()", "ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time() - T0)) # 95.7 sec T0 =", "# eva_BP = data[\"eva_BP\"] # evc_BP = data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) #", "False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _", "Flattened Hessian matrix BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened", "G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0 = time()", "from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta", "sec\" % (time() - T0)) # 95.4 sec #%% print(\"Correlation of Flattened Hessian", "for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0 =", "import time from os.path import join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%%", "matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI))", "self.PGGAN = PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version", "sec T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f", "% (time() - T0)) # 95.4 sec #%% print(\"Correlation of Flattened Hessian matrix", "= hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0)) #", "% (time() - T0)) # 325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian", "= time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\"", "EPS 1.0e-04 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.999 # EPS", "corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with", "T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\"", "with torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): #", "H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) #", "Flattened Hessian matrix BP vs ForwardIter 0.989 # EPS 1.0e-02 Correlation of Flattened", "vs ForwardIter 0.901 # EPS 1.0e-01 Correlation of Flattened Hessian matrix BP vs", "BackwardIter 0.877 #%% H_col = [] for EPS in [1E-5, 1E-4, 1E-3, 1E-2,", "'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) #", "# nn.Module def __init__(self, PGGAN, ): self.PGGAN = PGGAN def visualize(self, code, scale=1):", "0.398 # EPS 1.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.046", "useGPU=use_gpu) num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images", "# EPS 1.0e-03 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.989 #", "H_avg=H_avg, eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log,", "H_col = [] for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2,", "Flattened Hessian matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI,", "eva_avg=eva_avg, evc_avg=evc_avg, feats=feat_col) #%% fig = plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin", "0.999 # EPS 1.0e-03 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.989", "#%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False model =", "# EPS 1.0e-02 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.901 #", "H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) #", "Flattened Hessian matrix BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of", "# without cuda 12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col,", "num_images = 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images =", "ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened Hessian matrix BP vs ForwardIter", "[] for EPS in [1E-5, 1E-4, 1E-3, 1E-2, 1E-1, 1, 2, 10]: T0", "np.array(eva_col) from Hessian.hessian_analysis_tools import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col,", "Hessian matrix ForwardIter vs BackwardIter 0.877 #%% H_col = [] for EPS in", "(time() - T0)) # 325.83 sec print(\"EPS %.1e Correlation of Flattened Hessian matrix", "lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if", "ImDist, hessian_method=\"BP\") print(\"%.2f sec\" % (time() - T0)) # 95.4 sec #%% print(\"Correlation", "(EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1])) H_col.append((eva_FI, evc_FI, H_FI)) # EPS 1.0e-05 Correlation of Flattened", "Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\" # eva_col = [] #", "Hessian matrix BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened Hessian", "BP vs ForwardIter 0.877 # Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter", "1]) # Correlation of Flattened Hessian matrix BP vs BackwardIter 1.000 # Correlation", "H_BI.flatten())[0, 1]) # Correlation of Flattened Hessian matrix BP vs BackwardIter 1.000 #", "61.8 sec T0 = time() eva_BP, evc_BP, H_BP = hessian_compute(G, feat, ImDist, hessian_method=\"BP\")", "hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu = True if torch.cuda.is_available() else False model", "#%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True) # without cuda 12:11 mins,", "figdir=figdir, use_cuda=True) # without cuda 12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin", "join import lpips from Hessian.GAN_hessian_compute import hessian_compute #%% ImDist = lpips.LPIPS(net='squeeze').cuda() use_gpu =", "2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS", "hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" % (time() - T0)) # 325.83", "scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default to 0.7 return torch.clamp((imgs +", "import torch import numpy as np from time import time from os.path import", "# data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP = data[\"eva_BP\"] # evc_BP", "of Flattened Hessian matrix BP vs ForwardIter %.3f\" % (EPS, np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]))", "of Flattened Hessian matrix BP vs ForwardIter 1.000 # EPS 1.0e-04 Correlation of", "vs ForwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter", "Hessian matrix BP vs ForwardIter 0.008 # EPS 1.0e+01 Correlation of Flattened Hessian", "vs BackwardIter 0.877 #%% H_col = [] for EPS in [1E-5, 1E-4, 1E-3,", "= scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg, eva_avg, evc_avg = average_H(eva_col, evc_col)", "plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\",", "BP vs BackwardIter %.3f\" % np.corrcoef(H_BP.flatten(), H_BI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix", "H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0,", "EPS 1.0e-05 Correlation of Flattened Hessian matrix BP vs ForwardIter 1.000 # EPS", "average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze()", "corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log, corr_mat_lin, figdir=figdir,", "#%% #%% Visualize Spectra figdir = r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\"", "ForwardIter vs BackwardIter 0.877 #%% H_col = [] for EPS in [1E-5, 1E-4,", "BP vs ForwardIter 0.398 # EPS 1.0e+00 Correlation of Flattened Hessian matrix BP", "time() eva_BI, evc_BI, H_BI = hessian_compute(G, feat, ImDist, hessian_method=\"BackwardIter\") print(\"%.2f sec\" % (time()", "return torch.clamp((imgs + 1.0) / 2.0, 0, 1) * scale G = PGGAN_wrapper(model.avgG)", "10]: T0 = time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS)", "model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN,", "if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images =", "PGGAN def visualize(self, code, scale=1): imgs = self.PGGAN.forward(code,) # Matlab version default to", "True if torch.cuda.is_available() else False model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub', 'PGAN', model_name='celebAHQ-256', pretrained=True, useGPU=use_gpu) num_images", "* scale G = PGGAN_wrapper(model.avgG) #%% feat = noise.detach().clone().cuda() EPS = 1E-2 T0", "for triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) # eva_BP", "time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\", EPS=EPS) print(\"%.2f sec\" %", "evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0))", "= plot_spectra(eva_col, figdir=figdir, titstr=\"PGGAN\", ) #%% corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=True)", "print(\"%.2f sec\" % (time() - T0)) # 325.83 sec print(\"EPS %.1e Correlation of", "EPS 1.0e-01 Correlation of Flattened Hessian matrix BP vs ForwardIter 0.398 # EPS", "torch.no_grad(): generated_images = model.test(noise) #%% img = model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module", "Spectra figdir = r\"E:\\OneDrive - Washington University in St. Louis\\Hessian_summary\\PGGAN\" savedir = r\"E:\\Cluster_Backup\\PGGAN\"", "scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir, \"Hessian_cmp_(\\d*).npz\", featkey=\"feat\") feat_col = np.array(feat_col).squeeze() H_avg,", "of Flattened Hessian matrix BP vs ForwardIter 0.046 # EPS 2.0e+00 Correlation of", "- T0)) # 95.4 sec #%% print(\"Correlation of Flattened Hessian matrix BP vs", "= data[\"evc_BP\"] # eva_col.append(eva_BP) # evc_col.append(evc_BP) # # eva_col = np.array(eva_col) from Hessian.hessian_analysis_tools", "= 1 noise, _ = model.buildNoiseData(num_images) noise.requires_grad_(True) # with torch.no_grad(): generated_images = model.test(noise)", "= hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" % (time() - T0)) # 61.8", "print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(), H_BI.flatten())[0, 1]) #", "12:11 mins, with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False)", "np.corrcoef(H_BP.flatten(), H_FI.flatten())[0, 1]) print(\"Correlation of Flattened Hessian matrix ForwardIter vs BackwardIter %.3f\"% np.corrcoef(H_FI.flatten(),", "= time() eva_FI, evc_FI, H_FI = hessian_compute(G, feat, ImDist, hessian_method=\"ForwardIter\") print(\"%.2f sec\" %", "with cuda 8:21 # corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1,", "# corr_mat_log, corr_mat_lin = compute_hess_corr(eva_col, evc_col, figdir=figdir, use_cuda=False) #%% fig1, fig2 = plot_consistentcy_mat(corr_mat_log,", "import plot_spectra, compute_hess_corr, plot_consistency_example, plot_consistentcy_mat, average_H, scan_hess_npz eva_col, evc_col, feat_col, meta = scan_hess_npz(savedir,", "Correlation of Flattened Hessian matrix BP vs BackwardIter 1.000 # Correlation of Flattened", "as np from time import time from os.path import join import lpips from", "# for triali in tqdm(range(400)): # data = np.load(join(savedir, \"Hessian_cmp_%d.npz\" % triali)) #", "= model.avgG.forward(noise) #%% class PGGAN_wrapper(): # nn.Module def __init__(self, PGGAN, ): self.PGGAN =" ]
[ "from ..core import Field, SystemObject, MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import", "from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True,", "is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True,", "Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True,", "type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType),", "is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\",", "MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS =", "default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\",", "optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str,", "is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True,", "type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True)", "optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod def is_supported(cls, system):", "mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ]", "optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True,", "creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\",", "is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool,", "creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\",", "type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True),", "type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True),", "default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType,", "Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\",", "Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True,", "is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True,", "..core import Field, SystemObject, MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType", "is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod", "mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType),", "type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod def is_supported(cls, system): return system.compat.has_tenants()", "type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True,", "is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True,", "Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True,", "creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod def is_supported(cls,", "from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [", "cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True),", "Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True,", "type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int,", "..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True),", "type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True,", "import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\",", "Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\",", "type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")),", "optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str,", "..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\",", "cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True),", "Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\",", "type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True,", "mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True,", "Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int,", "Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True,", "creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\", type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType,", "is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True,", "Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod def is_supported(cls, system): return", "Field, SystemObject, MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject):", "= [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True,", "mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True,", "import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int,", "class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True),", "Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True,", "import Field, SystemObject, MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class", "FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str,", "[ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True,", "Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True,", "is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\",", "is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True, creation_parameter=True, optional=True, cached=True), Field(\"capacity\", type=MunchType), Field(\"entity_counts\",", "is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True) ] @classmethod def", "type=MunchType), Field(\"created_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True,", "Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True,", "Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True,", "SystemObject, MillisecondsDatetimeType from ..core.api.special_values import Autogenerate from ..core.translators_and_types import MunchType class Tenant(SystemObject): FIELDS", "creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\",", "is_sortable=True, is_filterable=True), Field(\"updated_at\", type=MillisecondsDatetimeType, is_sortable=True, is_filterable=True), Field(\"anonymous_gid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True),", "is_sortable=True), Field(\"nfs_allow_unmapped_users\", type=str, mutable=True, is_filterable=True, is_sortable=True, creation_parameter=True, optional=True), Field(\"nfs_group_policy\", type=str, mutable=True, is_filterable=True, is_sortable=True,", "MunchType class Tenant(SystemObject): FIELDS = [ Field(\"id\", type=int, is_identity=True, is_filterable=True, is_sortable=True), Field(\"short_tenant_key\", type=int,", "is_sortable=True), Field(\"short_tenant_key\", type=int, cached=True), Field(\"name\", type=str, is_filterable=True, mutable=True, creation_parameter=True, default=Autogenerate(\"tenant_{uuid}\")), Field(\"visible_to_sysadmin\", type=bool, default=True,", "type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True), Field(\"anonymous_uid\", type=int, creation_parameter=True, optional=True, mutable=True, is_filterable=True, is_sortable=True)," ]
[ "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "writing, software # distributed under the License is distributed on an \"AS IS\"", "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# See the License for the specific language governing permissions and # limitations", "License. # You may obtain a copy of the License at # #", "# Copyright 2021 <NAME>. All Rights Reserved. # # Licensed under the Apache", "2021 <NAME>. All Rights Reserved. # # Licensed under the Apache License, Version", "from absl import flags from absl import logging from glob import glob from", "def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is", "TFRecord index files necessary when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx", "glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\")", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "compliance with the License. # You may obtain a copy of the License", "\"Absolute path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern", "from glob import glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob", ") for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script,", "absl import app from absl import flags from absl import logging from glob", "import logging from glob import glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\",", "tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx]) if __name__ == \"__main__\":", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "governing permissions and # limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord index", "usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl", "this file except in compliance with the License. # You may obtain a", "\"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" )", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl import", "you may not use this file except in compliance with the License. #", "None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\"", "tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx", "raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\" ) for tfrecord,", "Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "absl import flags from absl import logging from glob import glob from subprocess", "in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx]) if __name__", "is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify", "for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" ) FLAGS", "necessary when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\"", "ANY KIND, either express or implied. # See the License for the specific", "tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" ) FLAGS =", "index files necessary when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\", "absl import logging from glob import glob from subprocess import call import os.path", "specific language governing permissions and # limitations under the License. # ============================================================================== r\"\"\"Generate", "Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must", "in compliance with the License. # You may obtain a copy of the", "\"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "# limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary when", "use this file except in compliance with the License. # You may obtain", "import app from absl import flags from absl import logging from glob import", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "logging from glob import glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None,", "not use this file except in compliance with the License. # You may", "from absl import app from absl import flags from absl import logging from", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", ") FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify", "--tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl import flags from", "import glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord", "does not lead to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files,", "See the License for the specific language governing permissions and # limitations under", "not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\" )", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "--tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl import flags from absl import", "for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord,", "License, Version 2.0 (the \"License\"); # you may not use this file except", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "[filename + \"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script}", "valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "tfrecord_idxs = [filename + \"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise", "main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "script.\" ) FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from", "flags from absl import logging from glob import glob from subprocess import call", "OF ANY KIND, either express or implied. # See the License for the", "tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise", "= glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename in tfrecord_files] if not", "flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def", "2.0 (the \"License\"); # you may not use this file except in compliance", "--tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs", "= [filename + \"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError(", "raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for", "from absl import logging from glob import glob from subprocess import call import", "# you may not use this file except in compliance with the License.", "\"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_):", "for the specific language governing permissions and # limitations under the License. #", "agreed to in writing, software # distributed under the License is distributed on", "the License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary when using DALI preprocessing.", "limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary when using", "language governing permissions and # limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord", "is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename +", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx]) if __name__ == \"__main__\": app.run(main)", "filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to", "(the \"License\"); # you may not use this file except in compliance with", "and # limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary", "using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl", "# # Unless required by applicable law or agreed to in writing, software", "permissions and # limitations under the License. # ============================================================================== r\"\"\"Generate TFRecord index files", "express or implied. # See the License for the specific language governing permissions", "if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise", "Version 2.0 (the \"License\"); # you may not use this file except in", "# Unless required by applicable law or agreed to in writing, software #", "except in compliance with the License. # You may obtain a copy of", "the specific language governing permissions and # limitations under the License. # ==============================================================================", "by applicable law or agreed to in writing, software # distributed under the", "All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the", "flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx", "from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string(", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead", "tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx]) if", "files necessary when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord", "either express or implied. # See the License for the specific language governing", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "glob import glob from subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for", "import flags from absl import logging from glob import glob from subprocess import", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl import flags", "--tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename in tfrecord_files]", "FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename", "file except in compliance with the License. # You may obtain a copy", "os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\" ) for", "import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path", "raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx", "tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx])", "<NAME>. All Rights Reserved. # # Licensed under the Apache License, Version 2.0", "License for the specific language governing permissions and # limitations under the License.", "\"\"\" from absl import app from absl import flags from absl import logging", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\")", "the License. # You may obtain a copy of the License at #", "preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app", "to in writing, software # distributed under the License is distributed on an", "<gh_stars>1000+ # Copyright 2021 <NAME>. All Rights Reserved. # # Licensed under the", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary when using DALI preprocessing. Example", "files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS", "specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename in", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "r\"\"\"Generate TFRecord index files necessary when using DALI preprocessing. Example usage: python create_tfrecord_indexes.py", "implied. # See the License for the specific language governing permissions and #", "lead to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating", "\"License\"); # you may not use this file except in compliance with the", "under the License. # ============================================================================== r\"\"\"Generate TFRecord index files necessary when using DALI", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None,", "Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "required by applicable law or agreed to in writing, software # distributed under", "# ============================================================================== r\"\"\"Generate TFRecord index files necessary when using DALI preprocessing. Example usage:", "to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None:", "FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\")", "Copyright 2021 <NAME>. All Rights Reserved. # # Licensed under the Apache License,", "+ \"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does", "applicable law or agreed to in writing, software # distributed under the License", "None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to tfrecord2idx script.\"", "============================================================================== r\"\"\"Generate TFRecord index files necessary when using DALI preprocessing. Example usage: python", "DALI preprocessing. Example usage: python create_tfrecord_indexes.py --tfrecord2idx_script=~/DALI/tools/tfrecord2idx \\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import", "\\ --tfrecord_file_pattern=tfrecord/pascal*.tfrecord \"\"\" from absl import app from absl import flags from absl", "tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for", "in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid", "zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index file for {tfrecord}\") call([FLAGS.tfrecord2idx_script, tfrecord, tfrecord_idx]) if __name__ ==", "os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute path to", "flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script", "tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename in tfrecord_files] if", "not lead to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs):", "or agreed to in writing, software # distributed under the License is distributed", "subprocess import call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\",", "or implied. # See the License for the specific language governing permissions and", "app from absl import flags from absl import logging from glob import glob", "specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern)", "RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files =", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "None, \"Absolute path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_): if", "glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs = [filename + \"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script):", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not lead to valid tfrecord2idx script.\"", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\") tfrecord_files = glob(FLAGS.tfrecord_file_pattern) tfrecord_idxs =", "to valid tfrecord2idx script.\" ) for tfrecord, tfrecord_idx in zip(tfrecord_files, tfrecord_idxs): logging.info(f\"Generating index", "None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if FLAGS.tfrecord2idx_script is None: raise RuntimeError(\"Must specify --tfrecord2idx_script\")", "with the License. # You may obtain a copy of the License at", "\"_idx\" for filename in tfrecord_files] if not os.path.isfile(FLAGS.tfrecord2idx_script): raise ValueError( \"{FLAGS.tfrecord2idx_script} does not", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "call import os.path flags.DEFINE_string(\"tfrecord_file_pattern\", None, \"Glob for tfrecord files.\") flags.DEFINE_string( \"tfrecord2idx_script\", None, \"Absolute", "= flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is None: raise RuntimeError(\"Must specify --tfrecord_file_pattern.\") if", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "path to tfrecord2idx script.\" ) FLAGS = flags.FLAGS def main(_): if FLAGS.tfrecord_file_pattern is" ]
[ "\"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item]) if __name__ == '__main__':", "\"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t", "} self.t = Transform() def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item,", "None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\":", ".transform import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\":", "\"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\"", "\"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def test_transform(self) -> None: for strict_item", "None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item", "strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys():", "{ \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\",", "def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"),", "self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform()", "{ \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def test_transform(self)", "self.t = Transform() def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"),", "setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\":", "\"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\",", "\"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict =", "\"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\":", "self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item])", "in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item,", "<gh_stars>1-10 import unittest from .transform import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None:", "TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\":", "\"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" }", "for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in", "\"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\":", "\"大陆\": \"大陆\" } self.t = Transform() def test_transform(self) -> None: for strict_item in", "\"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\",", "\"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def test_transform(self) -> None: for", "strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item]) if __name__ == '__main__': unittest.main()", "\"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def test_transform(self) -> None:", "\"大陆\" } self.t = Transform() def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys():", "self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item]) if __name__", "\"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\"", "from .transform import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = {", "\"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\",", "import unittest from .transform import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict", "\"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = {", "self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\",", "import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\",", "class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\",", "= Transform() def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item])", "= { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def", "\"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\":", "Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\":", "\"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\",", "\"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t = Transform() def test_transform(self) ->", "\"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" }", "} self.smart_data_dict = { \"约2.5亿年~6500万年\": \"约250000000年~65000000年\", \"廿二日,日出东方\": \"22日,日出东方\", \"大陆\": \"大陆\" } self.t =", "Transform() def test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item],", "\"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\":", "test_transform(self) -> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item)", "self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"),", "-> None: for strict_item in self.strict_data_dict.keys(): self.assertEqual(self.t.transform(strict_item, \"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for", "unittest from .transform import Transform class TransformTest(unittest.TestCase): def setUp(self) -> None: self.strict_data_dict =", "def setUp(self) -> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\",", "= { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\":", "-> None: self.strict_data_dict = { \"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\",", "\"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\":", "\"an2cn\"), self.strict_data_dict[strict_item]) self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item]) if", "self.assertEqual(self.t.transform(self.strict_data_dict[strict_item], \"cn2an\"), strict_item) for smart_item in self.smart_data_dict.keys(): self.assertEqual(self.t.transform(smart_item, \"cn2an\"), self.smart_data_dict[smart_item]) if __name__ ==", "\"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\": \"抛出去的硬币为正面的概率是二分之一\", \"现在室内温度为39℃,很热啊!\": \"现在室内温度为三十九摄氏度,很热啊!\", \"创业板指9月9日早盘低开1.57%\": \"创业板指九月九日早盘低开百分之一点五七\" } self.smart_data_dict", "\"小王捡了100块钱\": \"小王捡了一百块钱\", \"用户增长最快的3个城市\": \"用户增长最快的三个城市\", \"小王的生日是2001年3月4日\": \"小王的生日是二零零一年三月四日\", \"小王的生日是2012年12月12日\": \"小王的生日是二零一二年十二月十二日\", \"今天股价上涨了8%\": \"今天股价上涨了百分之八\", \"第2天股价下降了-3.8%\": \"第二天股价下降了百分之负三点八\", \"抛出去的硬币为正面的概率是1/2\":" ]
[ "import handler404, handler500 from . import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\"", "import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls),", "\"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")),", "path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new", "include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if", "django.conf import settings from django.conf.urls import handler404, handler500 from . import views handler404", "path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+", "include, path from django.conf.urls.static import static from django.conf import settings from django.conf.urls import", "django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from", "from django.conf import settings from django.conf.urls import handler404, handler500 from . import views", "admin from django.urls import include, path from django.conf.urls.static import static from django.conf import", "include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns += static(", "handler500 from . import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns =", "from django.conf.urls import handler404, handler500 from . import views handler404 = \"foodgram.views.page_not_found\" handler500", "django.conf.urls import handler404, handler500 from . import views handler404 = \"foodgram.views.page_not_found\" handler500 =", "django.conf.urls.static import static from django.conf import settings from django.conf.urls import handler404, handler500 from", "from django.urls import include, path from django.conf.urls.static import static from django.conf import settings", "path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG:", "= [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\",", "handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")),", "include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: #", "[ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")),", "from . import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [", "handler404, handler500 from . import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns", "include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT", "urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")),", "path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)", "include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns", "path from django.conf.urls.static import static from django.conf import settings from django.conf.urls import handler404,", "import include, path from django.conf.urls.static import static from django.conf import settings from django.conf.urls", "from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static", "handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\",", "settings from django.conf.urls import handler404, handler500 from . import views handler404 = \"foodgram.views.page_not_found\"", "from django.conf.urls.static import static from django.conf import settings from django.conf.urls import handler404, handler500", "path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns +=", "import static from django.conf import settings from django.conf.urls import handler404, handler500 from .", "admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")),", "include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL,", "\"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\",", "static from django.conf import settings from django.conf.urls import handler404, handler500 from . import", "path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")), path(\"followings/\", include(\"follows.urls\")), path(\"shopping-list/\", include(\"shopping_list.urls\")), path(\"\",", "= \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\", include(\"django.contrib.auth.urls\")), path(\"favorites/\", include(\"favorites.urls\")),", ". import views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/',", "views handler404 = \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\",", "path(\"\", include(\"recipes.urls\")), ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns += static( settings.MEDIA_URL,", "= \"foodgram.views.page_not_found\" handler500 = \"foodgram.views.server_error\" urlpatterns = [ path('admin/', admin.site.urls), path(\"auth/\", include(\"users.urls\")), path(\"auth/\",", "]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: # new urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT )", "import admin from django.urls import include, path from django.conf.urls.static import static from django.conf", "import settings from django.conf.urls import handler404, handler500 from . import views handler404 =", "django.urls import include, path from django.conf.urls.static import static from django.conf import settings from" ]
[ "_configure_interior(event): # update the scrollbars to match the size of the inner frame", "self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None", "= Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT,", "def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self,", "return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar:", "to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() !=", "an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\",", "the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(),", "the canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event):", "self.canvas.winfo_width(): # update the canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>',", "= interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track", "vertical scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) # create", "**kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/", "yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event:", "\"\"\"A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute", "*args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame", "scrollbar def _configure_interior(event): # update the scrollbars to match the size of the", "self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar", "def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'):", "= self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel", "orient, factor = 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if", "frame inside the canvas which will be scrolled with it self.interior = interior", "scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event,", "and sync them, # also updating the scrollbar def _configure_interior(event): # update the", "for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self,", "tkinter import * import sys class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master,", "1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4:", "side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) #", "This frame only allows vertical scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master,", "or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def", "self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the", "fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width():", "scrollable frame that actually works! * Use the 'interior' attribute to place widgets", "show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor = 2):", "self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def", "= factor else: raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>',", "if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+')", "# create a frame inside the canvas which will be scrolled with it", "_configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width to fill", "self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self,", "if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and", "allows vertical scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) #", "Construct and pack/place/grid normally * This frame only allows vertical scrolling \"\"\" def", "create a frame inside the canvas which will be scrolled with it self.interior", "for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) )", "yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind())", "# create a canvas object and a vertical scrollbar for scrolling it self.vscrollbar", "interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width to fill the canvas", "None if type(factor) == int: self.factor = factor else: raise Exception(\"Factor must be", "and pack/place/grid normally * This frame only allows vertical scrolling \"\"\" def __init__(self,", "# update the scrollbars to match the size of the inner frame size", "yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or", "scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) # create a", "Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0)", "!= self.canvas.winfo_width(): # update the inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id,", "_on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" )", "highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) #", "scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas =", ") return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if", "def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return", "4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32'", "hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel", "canvas and frame width and sync them, # also updating the scrollbar def", "== 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform ==", "the scrollable frame * Construct and pack/place/grid normally * This frame only allows", "'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" )", "== 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None):", "scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x',", "super().__init__(master, *args, **kw) # create a canvas object and a vertical scrollbar for", "frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth()", "'_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel", "self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea !=", "bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas", "= self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor)", "a canvas object and a vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self,", ") elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform", "view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or", "= Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to", "_on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel", "Use the 'interior' attribute to place widgets inside the scrollable frame * Construct", "Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel,", "else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event)", "and frame width and sync them, # also updating the scrollbar def _configure_interior(event):", "lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually works!", "Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH,", "scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event:", "interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and", "inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas, yscrollbar=self.vscrollbar)", "= yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar,", "scrollable frame * Construct and pack/place/grid normally * This frame only allows vertical", "lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure", "works! * Use the 'interior' attribute to place widgets inside the scrollable frame", "main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in", "will be scrolled with it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id =", "canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if", "self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a", "and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar,", "view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\"", "def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\"", "hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar:", "class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget()", "anchor=NW) # track changes to the canvas and frame width and sync them,", "scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight())", "create a canvas object and a vertical scrollbar for scrolling it self.vscrollbar =", "track changes to the canvas and frame width and sync them, # also", "xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar,", "hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root,", "_on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set)", "= None if type(factor) == int: self.factor = factor else: raise Exception(\"Factor must", "* Construct and pack/place/grid normally * This frame only allows vertical scrolling \"\"\"", "the scrollbar def _configure_interior(event): # update the scrollbars to match the size of", "view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which will be", "main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda", "xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar:", "= self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame", "update the scrollbars to match the size of the inner frame size =", "to the canvas and frame width and sync them, # also updating the", "frame width and sync them, # also updating the scrollbar def _configure_interior(event): #", "super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class", "0 %s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's", "self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command = getattr(widget,", "frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the", "self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar", "* This frame only allows vertical scrolling \"\"\" def __init__(self, master, *args, **kw):", "yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>',", "self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea", "lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor)", "self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) #", "to place widgets inside the scrollable frame * Construct and pack/place/grid normally *", "width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth()", "scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind())", "_mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command =", "view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def", "self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame", "the 'interior' attribute to place widgets inside the scrollable frame * Construct and", "frame only allows vertical scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args,", "inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if", "**kw) # create a canvas object and a vertical scrollbar for scrolling it", "interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes", "normally * This frame only allows vertical scrolling \"\"\" def __init__(self, master, *args,", "(xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event:", "scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel):", "self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner", "def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor =", "inside the canvas which will be scrolled with it self.interior = interior =", "main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar)", "self.activeArea = None if type(factor) == int: self.factor = factor else: raise Exception(\"Factor", "only allows vertical scrolling \"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw)", "if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar", "ScrollingArea: def __init__(self, root, factor = 2): self.activeArea = None if type(factor) ==", "def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) # create a canvas object", "xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not", "widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor = 1):", "scrolled with it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0,", "if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif", "changes to the canvas and frame width and sync them, # also updating", "# track changes to the canvas and frame width and sync them, #", "in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda", "event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform", "or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if", "and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar", "self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for", "*args, **kw): super().__init__(master, *args, **kw) # create a canvas object and a vertical", "root, factor = 2): self.activeArea = None if type(factor) == int: self.factor =", "scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable", "attribute to place widgets inside the scrollable frame * Construct and pack/place/grid normally", "self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None def", "%s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width", "'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin':", "__init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self): self.grid()", "'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if", "event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform == 'cygwin':", "self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor", "to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas, yscrollbar=self.vscrollbar) def reset(self): self.canvas.xview_moveto(0)", "raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>',", "# reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas", "= main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar:", "expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside", ") scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that", "# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor = 2): self.activeArea =", "= widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor =", "!= self.canvas.winfo_width(): # update the canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth())", "from tkinter import * import sys class Panel(Frame): def __init__(self, master, *args, **kw):", "def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview", "also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the", "interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width to fit the inner frame", "_mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget,", "interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update", "xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and", "yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel =", "self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor", "Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the", "else: raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+')", "int: self.factor = factor else: raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux')", "pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to", "add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and", "update the inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas)", "import sys class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def", "#https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor = 2): self.activeArea = None if", "to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0", "width and sync them, # also updating the scrollbar def _configure_interior(event): # update", "self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview)", "# also updating the scrollbar def _configure_interior(event): # update the scrollbars to match", "widgets inside the scrollable frame * Construct and pack/place/grid normally * This frame", "interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's", "factor = 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num", "== 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform ==", "import * import sys class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args,", "master, *args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self): self.grid() #", "def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command", "yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if", "% size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width to fit", "self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually works! * Use", "**kw): super().__init__(master, *args, **kw) # create a canvas object and a vertical scrollbar", "must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+')", "if type(factor) == int: self.factor = factor else: raise Exception(\"Factor must be an", "class ScrollingArea: def __init__(self, root, factor = 2): self.activeArea = None if type(factor)", "* import sys class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw)", "that actually works! * Use the 'interior' attribute to place widgets inside the", "getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif", "view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\"", "the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size)", "== 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\"", "expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset", "def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width to", "= 2): self.activeArea = None if type(factor) == int: self.factor = factor else:", "the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which will", "def __init__(self, root, factor = 2): self.activeArea = None if type(factor) == int:", "fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas, yscrollbar=self.vscrollbar) def reset(self): self.canvas.xview_moveto(0) self.canvas.yview_moveto(0)", "event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually works! *", "*args, **kw) def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea:", "sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def", "scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'):", "self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea", "add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget):", "window=interior, anchor=NW) # track changes to the canvas and frame width and sync", "root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def", "def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar:", "self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set)", ": root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event):", "be scrolled with it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0,", "yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create", "fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame", "orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)", "\"\"\" def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) # create a canvas", "!= self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea =", "== 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform == 'cygwin': def", "factor = 2): self.activeArea = None if type(factor) == int: self.factor = factor", "place widgets inside the scrollable frame * Construct and pack/place/grid normally * This", "if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num ==", "self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor = 2): self.activeArea", "not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'):", "the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s", "_configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width", "a vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)", "def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def show(self):", "http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def __init__(self, root, factor = 2): self.activeArea = None", "master, *args, **kw): super().__init__(master, *args, **kw) # create a canvas object and a", "if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class", "self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the", "if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>',", "2): self.activeArea = None if type(factor) == int: self.factor = factor else: raise", "root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if", "event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter", "pack/place/grid normally * This frame only allows vertical scrolling \"\"\" def __init__(self, master,", "sys.platform == 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform", "sys class Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def hide(self):", "actually works! * Use the 'interior' attribute to place widgets inside the scrollable", "xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y',", "and a vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT,", "= (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width():", "if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the inner frame's width to fill the", "# update the inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>',", "size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth() !=", "frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas, yscrollbar=self.vscrollbar) def", "__init__(self, root, factor = 2): self.activeArea = None if type(factor) == int: self.factor", "the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): #", "VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually works! * Use the 'interior'", "self.canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the", "def _configure_interior(event): # update the scrollbars to match the size of the inner", "== int: self.factor = factor else: raise Exception(\"Factor must be an integer.\") if", "sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num == 5:", "'_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel =", "sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars", "scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A", "event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel", "updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size", "sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None,", "self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel =", "yscrollbar or xscrollbar if main_scrollbar: scrollingArea._on_mouse_wheel = main_scrollbar._on_mouse_wheel for scrollbar in (xscrollbar, yscrollbar):", "class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually works! * Use the", "%s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width to", "= 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num ==", "it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0, highlightthickness=0,", "reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which", "None def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command = getattr(widget, orient+'view') if", "self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if yscrollbar", "frame that actually works! * Use the 'interior' attribute to place widgets inside", "if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width to fit the inner", "self.canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with", "bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view self.canvas.xview_moveto(0) self.canvas.yview_moveto(0)", "factor else: raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel,", "self.canvas.xview_moveto(0) self.canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled", "self.canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width", "object and a vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y,", "# update the canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior)", "= Canvas(self, bd=0, highlightthickness=0, yscrollcommand=self.vscrollbar.set) self.canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) self.vscrollbar.config(command=self.canvas.yview) # reset the view", "widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self, widget, orient,", "5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event):", "inside the scrollable frame * Construct and pack/place/grid normally * This frame only", "view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview", "size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\"", "'interior' attribute to place widgets inside the scrollable frame * Construct and pack/place/grid", "(interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" % size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): #", "* Use the 'interior' attribute to place widgets inside the scrollable frame *", "orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" ) elif event.num", "inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update", "self.factor = factor else: raise Exception(\"Factor must be an integer.\") if sys.platform.startswith('linux') :", ") elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self,", "elif sys.platform == 'darwin': def _on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea,", "= getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event): if event.num == 4: view_command(\"scroll\",(-1)*factor,\"units\" )", "and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self):", "add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self:", "them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to", "which will be scrolled with it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id", "Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place", "add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda", "def _mouse_wheel_bind(self, widget): self.activeArea = widget def _mouse_wheel_unbind(self): self.activeArea = None def build_function__on_mouse_wheel(self,", "if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda", "a frame inside the canvas which will be scrolled with it self.interior =", "def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea", "event: self._mouse_wheel_unbind()) if xscrollbar and not hasattr(xscrollbar, '_on_mouse_wheel'): xscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'x', self.factor) if", "of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0 %s %s\" %", "type(factor) == int: self.factor = factor else: raise Exception(\"Factor must be an integer.\")", "scrollbar.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) class VScrolledPanel(Panel): \"\"\"A pure Tkinter scrollable frame that actually", "the canvas and frame width and sync them, # also updating the scrollbar", "_on_mouse_wheel(event): view_command(\"scroll\",event.delta,\"units\" ) return _on_mouse_wheel def add_scrolling(self, scrollingArea, xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set)", "self.canvas.winfo_width(): # update the inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width())", "build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def", "Panel(Frame): def __init__(self, master, *args, **kw): super().__init__(master, *args, **kw) def hide(self): self.grid_forget() def", "self.factor) if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar =", "width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas, yscrollbar=self.vscrollbar) def reset(self):", "**kw) def hide(self): self.grid_forget() def show(self): self.grid() # http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame #https://code.activestate.com/recipes/578894-mousewheel-binding-to-scrolling-area-tkinter-multi/ class ScrollingArea: def", "it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior, anchor=NW)", "canvas which will be scrolled with it self.interior = interior = Frame(self.canvas, bg=\"white\",)", "scrollbar in (xscrollbar, yscrollbar): if scrollbar: scrollbar.bind('<Enter>', lambda event, scrollbar=scrollbar: self._mouse_wheel_bind(scrollbar) ) scrollbar.bind('<Leave>',", "scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea)) scrollingArea.bind('<Leave>', lambda event: self._mouse_wheel_unbind()) if xscrollbar and not", "size) if interior.winfo_reqwidth() != self.canvas.winfo_width(): # update the canvas's width to fit the", "canvas object and a vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL)", "scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas = Canvas(self, bd=0,", "not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar or xscrollbar if", ") elif sys.platform == 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" )", "if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea = widget", "frame * Construct and pack/place/grid normally * This frame only allows vertical scrolling", "update the canvas's width to fit the inner frame self.canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def", "if yscrollbar and not hasattr(yscrollbar, '_on_mouse_wheel'): yscrollbar._on_mouse_wheel = self.build_function__on_mouse_wheel(scrollingArea,'y', self.factor) main_scrollbar = yscrollbar", "sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif sys.platform == 'darwin': def _on_mouse_wheel(event):", "_on_mouse_wheel(self,event): if self.activeArea and self.activeArea != self: self.activeArea._on_mouse_wheel(event) def _mouse_wheel_bind(self, widget): self.activeArea =", "match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) self.canvas.config(scrollregion=\"0 0", "xscrollbar=None, yscrollbar=None): if yscrollbar: scrollingArea.configure(xscrollcommand=yscrollbar.set) yscrollbar['command']=scrollingArea.yview if xscrollbar: scrollingArea.configure(yscrollcommand=xscrollbar.set) xscrollbar['command']=scrollingArea.xview scrollingArea.bind('<Enter>',lambda event: self._mouse_wheel_bind(scrollingArea))", "__init__(self, master, *args, **kw): super().__init__(master, *args, **kw) # create a canvas object and", "root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel, add='+') def _on_mouse_wheel(self,event): if self.activeArea and self.activeArea", "vertical scrollbar for scrolling it self.vscrollbar = Scrollbar(self, orient=VERTICAL) self.vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) self.canvas", "the inner frame's width to fill the canvas self.canvas.itemconfigure(interior_id, width=self.canvas.winfo_width()) self.canvas.bind('<Configure>', _configure_canvas) ScrollingArea(self).add_scrolling(self.canvas,", "elif event.num == 5: view_command(\"scroll\",factor,\"units\" ) elif sys.platform == 'win32' or sys.platform ==", "elif sys.platform == 'win32' or sys.platform == 'cygwin': def _on_mouse_wheel(event): view_command(\"scroll\",(-1)*int((event.delta/120)*factor),\"units\" ) elif", "0, window=interior, anchor=NW) # track changes to the canvas and frame width and", "widget, orient, factor = 1): view_command = getattr(widget, orient+'view') if sys.platform.startswith('linux'): def _on_mouse_wheel(event):", "= None def build_function__on_mouse_wheel(self, widget, orient, factor = 1): view_command = getattr(widget, orient+'view')", "*args, **kw) # create a canvas object and a vertical scrollbar for scrolling", "be an integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else:", "with it self.interior = interior = Frame(self.canvas, bg=\"white\",) interior_id = self.canvas.create_window(0, 0, window=interior,", "the canvas which will be scrolled with it self.interior = interior = Frame(self.canvas,", "integer.\") if sys.platform.startswith('linux') : root.bind_all('<4>', self._on_mouse_wheel, add='+') root.bind_all('<5>', self._on_mouse_wheel, add='+') else: root.bind_all(\"<MouseWheel>\", self._on_mouse_wheel," ]
[ "cxxflit = shutil.which('c++filt') tested = False stat = 0 for soname in ['harfbuzz',", "exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname + '.def') if not", "encoding='utf-8') as f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb'", "cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-',", "in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not", "expose internal symbols' % so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS if", "re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit", "os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else: print('Checking that %s has the", "+ os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose internal symbols' %", "x in EXPORTED_SYMBOLS] + # cheat: copy the last line from the def", "def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] +", "'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found;", "'|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*',", "re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in wrong order builddir", "in EXPORTED_SYMBOLS] + # cheat: copy the last line from the def file!", "nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found; skipping test')", "'_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list',", "= '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__',", "same symbol list as %s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8') as", "+ # cheat: copy the last line from the def file! [def_file.splitlines()[-1]] ))", "in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal symbols", "does not expose internal symbols' % so) suspicious_symbols = [x for x in", "x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal", "= 1 def_path = os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not", "'_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s in", "#!/usr/bin/env python3 import sys, os, shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' #", "nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested =", "suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname + '.def') if not os.path.exists(def_path):", "'_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list',", "as %s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file =", "= f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x)", "s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b'", "print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname +", "% symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] + # cheat: copy the", "not nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested", "stat = 1 def_path = os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\'", "soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else:", "if suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+", "False stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix", "not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat =", "[s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not", "1 tested = True if not tested: print('check-symbols.sh: no shared libraries found; skipping", "so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix,", "= True if not tested: print('check-symbols.sh: no shared libraries found; skipping test') sys.exit(77)", "shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in wrong", "are prefixed with _ symprefix = '_' if suffix == 'dylib' else ''", "re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix,", "'__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm:", "On macOS, C symbols are prefixed with _ symprefix = '_' if suffix", ").decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not", "found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat = 0", "for x in EXPORTED_SYMBOLS] + # cheat: copy the last line from the", "if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also", "EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0]", "print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False", "input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does", "not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat", "symbol list as %s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8') as f:", "% (so, def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file = f.read() diff_result", "(symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also if is available if cxxflit:", "+ [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run", "prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose", "+ [re.sub('^%shb' % symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] + # cheat:", "diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True if not tested: print('check-symbols.sh: no", "else: print('Checking that %s has the same symbol list as %s' % (so,", "True if not tested: print('check-symbols.sh: no shared libraries found; skipping test') sys.exit(77) sys.exit(stat)", "open(def_path, 'r', encoding='utf-8') as f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS']", "def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file = f.read() diff_result = list(difflib.context_diff(", "builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata',", "re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat =", "IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__',", "with open(def_path, 'r', encoding='utf-8') as f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(),", "'_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not", "available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix +", "subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] #", "(so, def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file = f.read() diff_result =", "% (soname, suffix)) if not os.path.exists(so): continue # On macOS, C symbols are", "'_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*',", "\\'nm\\' not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat", "so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue #", "not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else: print('Checking that %s has", "if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz',", "(symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose internal symbols'", "def_path = os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping'", "suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname", "for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so", "python3 import sys, os, shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise", "as f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' %", "'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' %", "print('Checking that %s does not expose internal symbols' % so) suspicious_symbols = [x", "tested = False stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']:", "'_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if", "not found; skipping' % def_path) else: print('Checking that %s has the same symbol", "'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname,", "if not nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit = shutil.which('c++filt')", "IGNORED_SYMBOLS), s)] # run again c++flit also if is available if cxxflit: EXPORTED_SYMBOLS", "suffix in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if", "also if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix", "% (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also if is available if", "% def_path) else: print('Checking that %s has the same symbol list as %s'", "not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also if", "= False stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for", "libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue # On macOS, C", "= 'C' # otherwise 'nm' prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__))", "macOS, C symbols are prefixed with _ symprefix = '_' if suffix ==", "if diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True if not tested: print('check-symbols.sh:", "% prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1", "print('\\n'.join(diff_result)) stat = 1 tested = True if not tested: print('check-symbols.sh: no shared", "if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir,", "['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so):", "'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split()", "with _ symprefix = '_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS =", "for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch,", "the last line from the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat", "'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue # On macOS, C symbols", "EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE)", "= os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue # On", "has the same symbol list as %s' % (so, def_path)) with open(def_path, 'r',", "# run again c++flit also if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output(", "= (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose internal", "shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit =", "the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested =", "# otherwise 'nm' prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs =", "found; skipping' % def_path) else: print('Checking that %s has the same symbol list", "tested = True if not tested: print('check-symbols.sh: no shared libraries found; skipping test')", "'__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm", "c++flit also if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines()", "f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for", "'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue", "[def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True if not", "x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1 def_path =", "os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start',", "= shutil.which('c++filt') tested = False stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset',", "suffix)) if not os.path.exists(so): continue # On macOS, C symbols are prefixed with", "wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini',", "test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat = 0 for soname", "symbols are prefixed with _ symprefix = '_' if suffix == 'dylib' else", "_ symprefix = '_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2]", "(soname, suffix)) if not os.path.exists(so): continue # On macOS, C symbols are prefixed", "if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix =", "not expose internal symbols' % so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS", "if not os.path.exists(so): continue # On macOS, C symbols are prefixed with _", "that %s does not expose internal symbols' % so) suspicious_symbols = [x for", "prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols) stat = 1 def_path", "os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose internal symbols' % so)", "'r', encoding='utf-8') as f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] +", "'C' # otherwise 'nm' prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs", "in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS =", "1 def_path = os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not found;", "diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for x", "symbols exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname + '.def') if", "'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found; skipping", "= subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking", "%s does not expose internal symbols' % so) suspicious_symbols = [x for x", "cheat: copy the last line from the def file! [def_file.splitlines()[-1]] )) if diff_result:", "= os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77)", "%s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also if is available", "list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for x in EXPORTED_SYMBOLS]", "'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s'", "stat = 1 tested = True if not tested: print('check-symbols.sh: no shared libraries", "otherwise 'nm' prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs',", "EXPORTED_SYMBOLS] + # cheat: copy the last line from the def file! [def_file.splitlines()[-1]]", "# On macOS, C symbols are prefixed with _ symprefix = '_' if", "from the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested", "not os.path.exists(so): continue # On macOS, C symbols are prefixed with _ symprefix", "C symbols are prefixed with _ symprefix = '_' if suffix == 'dylib'", "prefixed with _ symprefix = '_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS", "= 1 tested = True if not tested: print('check-symbols.sh: no shared libraries found;", "'nm' prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs')", "os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata',", "is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix", "'.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else: print('Checking that", "run again c++flit also if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit],", "'__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm =", "'_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path'])", "if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else: print('Checking that %s", "libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__',", "os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not found; skipping test') sys.exit(77) cxxflit", "the same symbol list as %s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8')", "os, shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in", "def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True", "skipping' % def_path) else: print('Checking that %s has the same symbol list as", "'_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm'))", "again c++flit also if is available if cxxflit: EXPORTED_SYMBOLS = subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode()", "suspicious_symbols = [x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)]", "f: def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix,", "os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss',", "re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again c++flit also if is", "'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\' not", "'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py: \\'nm\\'", "in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' %", "list as %s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file", ".+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)]", "= list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for x in", "['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so = os.path.join(builddir, libs,", "= os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__',", "suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST]", "subprocess.check_output( [cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that", "symprefix = '_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for", "for suffix in ['so', 'dylib']: so = os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix))", "os.path.exists(so): continue # On macOS, C symbols are prefixed with _ symprefix =", "line from the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1", "continue # On macOS, C symbols are prefixed with _ symprefix = '_'", "os.path.join(builddir, libs, 'lib%s.%s' % (soname, suffix)) if not os.path.exists(so): continue # On macOS,", "[cxxflit], input='\\n'.join(EXPORTED_SYMBOLS).encode() ).decode('utf-8').splitlines() prefix = (symprefix + os.path.basename(so)).replace('libharfbuzz', 'hb').replace('-', '_').split('.')[0] print('Checking that %s", "os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in wrong order builddir = os.getenv('builddir',", "0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']:", "%s' % (so, def_path)) with open(def_path, 'r', encoding='utf-8') as f: def_file = f.read()", "skipping test') sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat = 0 for", "print('\\'%s\\' not found; skipping' % def_path) else: print('Checking that %s has the same", "'__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM', shutil.which('nm')) if not nm: print('check-symbols.py:", "[BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS),", "['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] + #", "in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so = os.path.join(builddir,", "'' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'),", "prints in wrong order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS", "stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in", "= [x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if", "[x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols:", "[re.sub('^%shb' % symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] + # cheat: copy", "'.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext', '_fbss', '__bss_start', '__bss_start__', '__bss_end__', '_edata', '_end',", "EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:',", "order builddir = os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init',", "copy the last line from the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result))", "def_path) else: print('Checking that %s has the same symbol list as %s' %", "+ '.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path) else: print('Checking", "symprefix, 'hb', x) for x in EXPORTED_SYMBOLS] + # cheat: copy the last", "% so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)' %", "= '_' if suffix == 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s", "file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True if", "for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.*", "subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in wrong order", "soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so', 'dylib']: so =", "'_').split('.')[0] print('Checking that %s does not expose internal symbols' % so) suspicious_symbols =", "print('Checking that %s has the same symbol list as %s' % (so, def_path))", "x) for x in EXPORTED_SYMBOLS] + # cheat: copy the last line from", "symbols' % so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS if not re.match(r'^%s(_|$)'", "internal symbols exposed:', suspicious_symbols) stat = 1 def_path = os.path.join(builddir, soname + '.def')", "'hb').replace('-', '_').split('.')[0] print('Checking that %s does not expose internal symbols' % so) suspicious_symbols", "that %s has the same symbol list as %s' % (so, def_path)) with", "sys, os, shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints", "else '' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() +", "import sys, os, shutil, subprocess, re, difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm'", "shutil.which('c++filt') tested = False stat = 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu',", "sys.exit(77) cxxflit = shutil.which('c++filt') tested = False stat = 0 for soname in", "'hb', x) for x in EXPORTED_SYMBOLS] + # cheat: copy the last line", "= 0 for soname in ['harfbuzz', 'harfbuzz-subset', 'harfbuzz-icu', 'harfbuzz-gobject']: for suffix in ['so',", "'__bss_end__', '_edata', '_end', '_bss_end__', '__end__', '__gcov_.*', 'llvm_.*', 'flush_fn_list', 'writeout_fn_list', 'mangle_path']) nm = os.getenv('NM',", "[so]).decode('utf-8'), re.MULTILINE) if not re.match(r'.* %s(%s)\\b' % (symprefix, IGNORED_SYMBOLS), s)] # run again", "# cheat: copy the last line from the def file! [def_file.splitlines()[-1]] )) if", "difflib os.environ['LC_ALL'] = 'C' # otherwise 'nm' prints in wrong order builddir =", "def_file = f.read() diff_result = list(difflib.context_diff( def_file.splitlines(), ['EXPORTS'] + [re.sub('^%shb' % symprefix, 'hb',", "if not re.match(r'^%s(_|$)' % prefix, x)] if suspicious_symbols: print('Ouch, internal symbols exposed:', suspicious_symbols)", ")) if diff_result: print('\\n'.join(diff_result)) stat = 1 tested = True if not tested:", "= [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$', subprocess.check_output(nm.split() + [so]).decode('utf-8'), re.MULTILINE) if", "== 'dylib' else '' EXPORTED_SYMBOLS = [s.split()[2] for s in re.findall(r'^.+ [BCDGIRST] .+$',", "s)] # run again c++flit also if is available if cxxflit: EXPORTED_SYMBOLS =", "%s has the same symbol list as %s' % (so, def_path)) with open(def_path,", "= os.getenv('builddir', os.path.dirname(__file__)) libs = os.getenv('libs', '.libs') IGNORED_SYMBOLS = '|'.join(['_fini', '_init', '_fdata', '_ftext',", "last line from the def file! [def_file.splitlines()[-1]] )) if diff_result: print('\\n'.join(diff_result)) stat =", "internal symbols' % so) suspicious_symbols = [x for x in EXPORTED_SYMBOLS if not", "os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' % def_path)", "= os.path.join(builddir, soname + '.def') if not os.path.exists(def_path): print('\\'%s\\' not found; skipping' %" ]
[ "iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and", "gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # #", "# # Get a string, which encodes const, volatile, and reference qualifiers of", "def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type)", "itertools import gdb import gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval __all__", "qualifiers of a gdb.Type: const, volatile, reference. The result is a string where", "following fileld: # # - printer_name: A subprinter name used by gdb (required).", "typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q),", "provide the following fileld: # # - printer_name: A subprinter name used by", "So e.g. 'const &foo' will return 'c&', 'const foo' will return 'c', etc.", "gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get a string, which encodes const,", "v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = (", "# v.qualifiers # v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class", "= typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not", "= str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and template names handling", "parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the", "encodes const, volatile, and reference qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get", "list of strings. ############################################################################### import sys import collections import operator import itertools import", "gdb.Type # def template_name(t): \"\"\"Get the template name of gdb.Type. Only for struct/union/enum.\"\"\"", "v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type',", "qualifiers, references, and pointers of a type\"\"\" qps = [] while True: typename", "fileld: # # - printer_name: A subprinter name used by gdb (required). #", "name of gdb.Type # def template_name(t): \"\"\"Get the template name of gdb.Type. Only", "= t.target() if t != t.unqualified(): qualifiers += ('c' if t == t.unqualified().const()", "else 'v' if t == t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else", "'*', 'const', 'volatile', ''))) if not qual: break typename = typename[:-len(qual)] qps.append(qual) while", "extra members: # v.qualifiers # v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value):", "== gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t = t.target() if t", "result is a string where 'c' designates const, 'v' volatile, '&' reference. So", "'const', 'volatile', ''))) if not qual: break typename = typename[:-len(qual)] qps.append(qual) while True:", "== t.unqualified().const() else 'v' if t == t.unqualified().volatile() else 'cv' if t ==", "Get the template name of gdb.Type # def template_name(t): \"\"\"Get the template name", "############################################################################### # A printer object must provide the following fileld: # # -", "# Type qualifiers and template names handling ############################################################################### # # Get the template", "of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code", "############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name',", "of gdb.Type # def template_name(t): \"\"\"Get the template name of gdb.Type. Only for", "template name of gdb.Type # def template_name(t): \"\"\"Get the template name of gdb.Type.", "Type qualifiers and template names handling ############################################################################### # # Get the template name", "v.qualifiers # v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for", "else 'cv' if t == t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove", "if not qual: break typename = typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip()", "name used by gdb (required). # - template_name: A string or a list", "qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t =", "object must provide the following fileld: # # - printer_name: A subprinter name", "(required). # - template_name: A string or a list of strings. ############################################################################### import", "'') # # Get a string, which encodes const, volatile, and reference qualifiers", "# # - printer_name: A subprinter name used by gdb (required). # -", "string encoding the qualifiers of a gdb.Type: const, volatile, reference. The result is", "# - printer_name: A subprinter name used by gdb (required). # - template_name:", "volatile, '&' reference. So e.g. 'const &foo' will return 'c&', 'const foo' will", "or a list of strings. ############################################################################### import sys import collections import operator import", "t == t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references,", "self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and template names handling ############################################################################### #", "template_name(self.basic_type) ############################################################################### # Type qualifiers and template names handling ############################################################################### # # Get", "if t == t.unqualified().const() else 'v' if t == t.unqualified().volatile() else 'cv' if", "def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of a type\"\"\" qps =", "lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume", "\"\"\"Remove const/volatile qualifiers, references, and pointers of a type\"\"\" qps = [] while", "value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name =", "a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a gdb.Type:", "template names handling ############################################################################### # # Get the template name of gdb.Type #", "by gdb (required). # - template_name: A string or a list of strings.", "= template_name(self.basic_type) ############################################################################### # Type qualifiers and template names handling ############################################################################### # #", "class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self,", "or '') # # Get a string, which encodes const, volatile, and reference", "collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and provides the following extra", "# Get a string, which encodes const, volatile, and reference qualifiers of a", "typename.startswith(q), ('const', 'volatile', ''))) if not qual: break typename = typename[len(qual):] qps.append(qual) return", "for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value):", "[ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely, return", "handling ############################################################################### # # Get the template name of gdb.Type # def template_name(t):", "############################################################################### # GDBValue derives from gdb.Value and provides the following extra members: #", "q: not typename.startswith(q), ('const', 'volatile', ''))) if not qual: break typename = typename[len(qual):]", "typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile',", "collections import operator import itertools import gdb import gdb.types import gdb.printing from gdb", "following extra members: # v.qualifiers # v.basic_type # v.type_name # v.template_name ############################################################################### class", "next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if not qual: break typename =", "== t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and", "(basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get a", "for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION,", "\"\"\"Get string encoding the qualifiers of a gdb.Type: const, volatile, reference. The result", "gdb.Type: const, volatile, reference. The result is a string where 'c' designates const,", "entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and provides", "= [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely,", "qps.append(qual) while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const',", "# def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a gdb.Type: const, volatile,", "t == t.unqualified().const() else 'v' if t == t.unqualified().volatile() else 'cv' if t", "############################################################################### import sys import collections import operator import itertools import gdb import gdb.types", "Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT,", "'const &foo' will return 'c&', 'const foo' will return 'c', etc. \"\"\" assert", "reference qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the qualifiers", "gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def", "a gdb.Type: const, volatile, reference. The result is a string where 'c' designates", "and provides the following extra members: # v.qualifiers # v.basic_type # v.type_name #", "not qual: break typename = typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual", "typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if not qual:", "typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not qual: break typename = typename[:-len(qual)]", "# - template_name: A string or a list of strings. ############################################################################### import sys", "!= t.unqualified(): qualifiers += ('c' if t == t.unqualified().const() else 'v' if t", "\"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from", "template name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t)", "names handling ############################################################################### # # Get the template name of gdb.Type # def", "foo' will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers", "('&', '*', 'const', 'volatile', ''))) if not qual: break typename = typename[:-len(qual)] qps.append(qual)", "will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers =", "def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a gdb.Type: const, volatile, reference.", "'' if qualifiers: t = t.target() if t != t.unqualified(): qualifiers += ('c'", "the following extra members: # v.qualifiers # v.basic_type # v.type_name # v.template_name ###############################################################################", "'v' volatile, '&' reference. So e.g. 'const &foo' will return 'c&', 'const foo'", "return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and provides the", "and pointers of a type\"\"\" qps = [] while True: typename = typename.rstrip()", "and '&' or '' if qualifiers: t = t.target() if t != t.unqualified():", "else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of", "qualifiers += ('c' if t == t.unqualified().const() else 'v' if t == t.unqualified().volatile()", "of a gdb.Type: const, volatile, reference. The result is a string where 'c'", "self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ###############################################################################", "t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or '' if", "t.code == gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t = t.target() if", "printer_name: A subprinter name used by gdb (required). # - template_name: A string", "assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&'", "qual: break typename = typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual =", "const, volatile, reference. The result is a string where 'c' designates const, 'v'", "and str(basic_type).split('<')[0] or '') # # Get a string, which encodes const, volatile,", "and template names handling ############################################################################### # # Get the template name of gdb.Type", "v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__", "'&' reference. So e.g. 'const &foo' will return 'c&', 'const foo' will return", "gdb.printing from gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name'", "'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\"", "# GDBValue derives from gdb.Value and provides the following extra members: # v.qualifiers", "typename = typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q:", "t.target() if t != t.unqualified(): qualifiers += ('c' if t == t.unqualified().const() else", "= gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and", "of a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a", "# v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ =", "maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and provides the following extra members:", "t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t", "True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', '')))", "string where 'c' designates const, 'v' volatile, '&' reference. So e.g. 'const &foo'", "strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of a type\"\"\" qps = []", "t == t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else '') return qualifiers", "import gdb import gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval __all__ =", "gdb (required). # - template_name: A string or a list of strings. ###############################################################################", "\"\"\"Get the template name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type", "return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of a type\"\"\"", "qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of a type\"\"\" qps", "__slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers", "qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of", "pointers of a type\"\"\" qps = [] while True: typename = typename.rstrip() qual", "qps = [] while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not", "provides the following extra members: # v.qualifiers # v.basic_type # v.type_name # v.template_name", "string, which encodes const, volatile, and reference qualifiers of a gdb.Type # def", "from gdb.Value and provides the following extra members: # v.qualifiers # v.basic_type #", "return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get", "import sys import collections import operator import itertools import gdb import gdb.types import", "gdb import gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval __all__ = [", "# v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers',", "and reference qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the", "is a string where 'c' designates const, 'v' volatile, '&' reference. So e.g.", "<filename>pcommon/gdb/pprint/utils.py ############################################################################### # A printer object must provide the following fileld: # #", "type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a gdb.Type: const, volatile, reference. The", "assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and", "a string, which encodes const, volatile, and reference qualifiers of a gdb.Type #", "qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not", "'') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers of a", "# def template_name(t): \"\"\"Get the template name of gdb.Type. Only for struct/union/enum.\"\"\" assert", "gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type)", "\"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and", "template_name: A string or a list of strings. ############################################################################### import sys import collections", "== t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else '') return qualifiers def", "import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator):", "GDBValue derives from gdb.Value and provides the following extra members: # v.qualifiers #", "class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name'", "&foo' will return 'c&', 'const foo' will return 'c', etc. \"\"\" assert isinstance(t,", "# Get the template name of gdb.Type # def template_name(t): \"\"\"Get the template", "+= ('c' if t == t.unqualified().const() else 'v' if t == t.unqualified().volatile() else", "'c&', 'const foo' will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t =", "a list of strings. ############################################################################### import sys import collections import operator import itertools", "'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ###############################################################################", "= [] while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q),", "qualifiers and template names handling ############################################################################### # # Get the template name of", "the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value", "A string or a list of strings. ############################################################################### import sys import collections import", "const/volatile qualifiers, references, and pointers of a type\"\"\" qps = [] while True:", "encoding the qualifiers of a gdb.Type: const, volatile, reference. The result is a", "not typename.startswith(q), ('const', 'volatile', ''))) if not qual: break typename = typename[len(qual):] qps.append(qual)", "derives from gdb.Value and provides the following extra members: # v.qualifiers # v.basic_type", "gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or", "self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers", "= t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or '' if qualifiers:", "basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '')", "template_name(t): \"\"\"Get the template name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type)", "('c' if t == t.unqualified().const() else 'v' if t == t.unqualified().volatile() else 'cv'", "in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get a string,", "gdb.Value and provides the following extra members: # v.qualifiers # v.basic_type # v.type_name", "############################################################################### # # Get the template name of gdb.Type # def template_name(t): \"\"\"Get", "a string where 'c' designates const, 'v' volatile, '&' reference. So e.g. 'const", "'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type =", "not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not qual: break typename =", "from gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ]", "gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume',", "typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if", "used by gdb (required). # - template_name: A string or a list of", "'volatile', ''))) if not qual: break typename = typename[:-len(qual)] qps.append(qual) while True: typename", "where 'c' designates const, 'v' volatile, '&' reference. So e.g. 'const &foo' will", "gdb.Type) t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or ''", "etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF", "A printer object must provide the following fileld: # # - printer_name: A", "'c', etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code ==", "def template_name(t): \"\"\"Get the template name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t,", "= type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### #", "type\"\"\" qps = [] while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q:", "return 'c&', 'const foo' will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t", "( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type)", "t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers, references, and pointers", "operator import itertools import gdb import gdb.types import gdb.printing from gdb import lookup_type,", "''))) if not qual: break typename = typename[:-len(qual)] qps.append(qual) while True: typename =", "('const', 'volatile', ''))) if not qual: break typename = typename[len(qual):] qps.append(qual) return typename,", "import collections import operator import itertools import gdb import gdb.types import gdb.printing from", "subprinter name used by gdb (required). # - template_name: A string or a", "the template name of gdb.Type # def template_name(t): \"\"\"Get the template name of", "'&' or '' if qualifiers: t = t.target() if t != t.unqualified(): qualifiers", "the qualifiers of a gdb.Type: const, volatile, reference. The result is a string", "t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename):", "gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in", "gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding the qualifiers of a gdb.Type: const,", "designates const, 'v' volatile, '&' reference. So e.g. 'const &foo' will return 'c&',", "qualifiers: t = t.target() if t != t.unqualified(): qualifiers += ('c' if t", "next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not qual: break", "sys import collections import operator import itertools import gdb import gdb.types import gdb.printing", "t != t.unqualified(): qualifiers += ('c' if t == t.unqualified().const() else 'v' if", "= typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile', '')))", "if t == t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else '') return", "const, 'v' volatile, '&' reference. So e.g. 'const &foo' will return 'c&', 'const", "strings. ############################################################################### import sys import collections import operator import itertools import gdb import", "if qualifiers: t = t.target() if t != t.unqualified(): qualifiers += ('c' if", "e.g. 'const &foo' will return 'c&', 'const foo' will return 'c', etc. \"\"\"", "= gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') #", "\"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def", "- template_name: A string or a list of strings. ############################################################################### import sys import", "must provide the following fileld: # # - printer_name: A subprinter name used", "gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get a string, which encodes", "t.unqualified(): qualifiers += ('c' if t == t.unqualified().const() else 'v' if t ==", "'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type", "True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const',", "name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return", "str(basic_type).split('<')[0] or '') # # Get a string, which encodes const, volatile, and", "const, volatile, and reference qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get string", "the following fileld: # # - printer_name: A subprinter name used by gdb", "str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and template names handling ###############################################################################", "reference. So e.g. 'const &foo' will return 'c&', 'const foo' will return 'c',", "= typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if not", "= next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if not qual: break typename", "members: # v.qualifiers # v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper", "[] while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&',", "qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile', ''))) if not qual: break", "if t == t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile qualifiers,", "__all__ = [ 'GDBValue', 'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator", "- printer_name: A subprinter name used by gdb (required). # - template_name: A", "'c' designates const, 'v' volatile, '&' reference. So e.g. 'const &foo' will return", "break typename = typename[:-len(qual)] qps.append(qual) while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda", "import itertools import gdb import gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval", "# v.basic_type # v.type_name # v.template_name ############################################################################### class GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\"", "which encodes const, volatile, and reference qualifiers of a gdb.Type # def type_qualifiers(t):", "] def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### #", "the template name of gdb.Type. Only for struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type =", "def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue", "struct/union/enum.\"\"\" assert isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM]", "a type\"\"\" qps = [] while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda", "gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t = t.target() if t !=", "isinstance(t, gdb.Type) basic_type = gdb.types.get_basic_type(t) return (basic_type.code in [gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0]", "of strings. ############################################################################### import sys import collections import operator import itertools import gdb", "'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type)", "gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value)", "or '' if qualifiers: t = t.target() if t != t.unqualified(): qualifiers +=", "type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type", "Get a string, which encodes const, volatile, and reference qualifiers of a gdb.Type", "None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives from gdb.Value and provides the following", "# # Get the template name of gdb.Type # def template_name(t): \"\"\"Get the", "import gdb.types import gdb.printing from gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue',", "The result is a string where 'c' designates const, 'v' volatile, '&' reference.", "= next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not qual:", "gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and template", "'volatile', ''))) if not qual: break typename = typename[len(qual):] qps.append(qual) return typename, qps[::-1]", "while True: typename = typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*',", "references, and pointers of a type\"\"\" qps = [] while True: typename =", "[gdb.TYPE_CODE_STRUCT, gdb.TYPE_CODE_UNION, gdb.TYPE_CODE_ENUM] and str(basic_type).split('<')[0] or '') # # Get a string, which", "self.type_name = str(self.basic_type) self.template_name = template_name(self.basic_type) ############################################################################### # Type qualifiers and template names", "return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code", "'consume', 'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator,", "# A printer object must provide the following fileld: # # - printer_name:", "t.unqualified().const() else 'v' if t == t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile()", "= ( 'qualifiers', 'basic_type', 'type_name', 'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers =", "'cv' if t == t.unqualified().const().volatile() else '') return qualifiers def strip_qualifiers(typename): \"\"\"Remove const/volatile", "if t != t.unqualified(): qualifiers += ('c' if t == t.unqualified().const() else 'v'", "'v' if t == t.unqualified().volatile() else 'cv' if t == t.unqualified().const().volatile() else '')", "############################################################################### # Type qualifiers and template names handling ############################################################################### # # Get the", "import operator import itertools import gdb import gdb.types import gdb.printing from gdb import", "typename.rstrip() qual = next(itertools.dropwhile(lambda q: not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if", "volatile, reference. The result is a string where 'c' designates const, 'v' volatile,", "import gdb.printing from gdb import lookup_type, parse_and_eval __all__ = [ 'GDBValue', 'consume', 'strip_qualifiers',", "of a type\"\"\" qps = [] while True: typename = typename.rstrip() qual =", "volatile, and reference qualifiers of a gdb.Type # def type_qualifiers(t): \"\"\"Get string encoding", "'const foo' will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type) t = t.strip_typedefs()", "printer object must provide the following fileld: # # - printer_name: A subprinter", "q: not typename.endswith(q), ('&', '*', 'const', 'volatile', ''))) if not qual: break typename", "reference. The result is a string where 'c' designates const, 'v' volatile, '&'", "isinstance(t, gdb.Type) t = t.strip_typedefs() qualifiers = t.code == gdb.TYPE_CODE_REF and '&' or", "= t.code == gdb.TYPE_CODE_REF and '&' or '' if qualifiers: t = t.target()", "while True: typename = typename.lstrip() qual = next(itertools.dropwhile(lambda q: not typename.startswith(q), ('const', 'volatile',", "GDBValue(gdb.Value): \"\"\"Wrapper class for gdb.Value\"\"\" __slots__ = ( 'qualifiers', 'basic_type', 'type_name', 'template_name' )", ") def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name =", "string or a list of strings. ############################################################################### import sys import collections import operator", "'strip_qualifiers', 'template_name' ] def consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0)", "t = t.target() if t != t.unqualified(): qualifiers += ('c' if t ==", "consume(iterator): \"\"\"Consume the iterator entirely, return None.\"\"\" collections.deque(iterator, maxlen=0) ############################################################################### # GDBValue derives", "__init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name = str(self.basic_type) self.template_name", "'template_name' ) def __init__(self, value): gdb.Value.__init__(value) self.qualifiers = type_qualifiers(value.type) self.basic_type = gdb.types.get_basic_type(value.type) self.type_name", "A subprinter name used by gdb (required). # - template_name: A string or", "will return 'c&', 'const foo' will return 'c', etc. \"\"\" assert isinstance(t, gdb.Type)" ]
[ "author = \"pretix team\" description = gettext_lazy(\"Allows to add arbitrary regex validation to", "django.utils.translation import gettext_lazy try: from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use", "pretix 2.7 or above to run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig):", "verbose_name = \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix", "to fields\") visible = True version = __version__ category = \"CUSTOMIZATION\" compatibility =", "PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex", "__version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class", "fields\") visible = True version = __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\"", "this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex", "run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name =", "gettext_lazy(\"Regex Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows to add arbitrary regex", "True version = __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from", "\"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author =", "version = __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from .", "class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name =", "except ImportError: raise RuntimeError(\"Please use pretix 2.7 or above to run this plugin!\")", "regex validation to fields\") visible = True version = __version__ category = \"CUSTOMIZATION\"", "to run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name", "add arbitrary regex validation to fields\") visible = True version = __version__ category", "PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7 or above to run this", "from django.utils.translation import gettext_lazy try: from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please", "= __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import", "ImportError: raise RuntimeError(\"Please use pretix 2.7 or above to run this plugin!\") __version__", "import gettext_lazy try: from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix", "visible = True version = __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def", "<reponame>pretix-unofficial/pretix-regex-validation<filename>pretix_regex_validation/__init__.py from django.utils.translation import gettext_lazy try: from pretix.base.plugins import PluginConfig except ImportError: raise", "\"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import signals # NOQA default_app_config", "RuntimeError(\"Please use pretix 2.7 or above to run this plugin!\") __version__ = \"1.0.1\"", "PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows to", "\"pretix team\" description = gettext_lazy(\"Allows to add arbitrary regex validation to fields\") visible", "team\" description = gettext_lazy(\"Allows to add arbitrary regex validation to fields\") visible =", "try: from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7 or", "= \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta:", "from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7 or above", "= gettext_lazy(\"Allows to add arbitrary regex validation to fields\") visible = True version", "to add arbitrary regex validation to fields\") visible = True version = __version__", "arbitrary regex validation to fields\") visible = True version = __version__ category =", "category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import signals #", "Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows to add arbitrary regex validation", "= True version = __version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self):", "compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import signals # NOQA default_app_config =", "use pretix 2.7 or above to run this plugin!\") __version__ = \"1.0.1\" class", "validation to fields\") visible = True version = __version__ category = \"CUSTOMIZATION\" compatibility", "plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\"", "\"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name", "import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7 or above to run", "2.7 or above to run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name", "above to run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name = \"pretix_regex_validation\"", "= \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author", "= \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix team\"", "= gettext_lazy(\"Regex Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows to add arbitrary", "= \"pretix team\" description = gettext_lazy(\"Allows to add arbitrary regex validation to fields\")", "gettext_lazy try: from pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7", "= \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import signals # NOQA", "description = gettext_lazy(\"Allows to add arbitrary regex validation to fields\") visible = True", "= \"pretix>=3.18.0.dev0\" def ready(self): from . import signals # NOQA default_app_config = \"pretix_regex_validation.PluginApp\"", "\"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix team\" description", "pretix.base.plugins import PluginConfig except ImportError: raise RuntimeError(\"Please use pretix 2.7 or above to", "__version__ category = \"CUSTOMIZATION\" compatibility = \"pretix>=3.18.0.dev0\" def ready(self): from . import signals", "name = \"pretix_regex_validation\" verbose_name = \"Regex Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\")", "name = gettext_lazy(\"Regex Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows to add", "raise RuntimeError(\"Please use pretix 2.7 or above to run this plugin!\") __version__ =", "gettext_lazy(\"Allows to add arbitrary regex validation to fields\") visible = True version =", "or above to run this plugin!\") __version__ = \"1.0.1\" class PluginApp(PluginConfig): name =", "Validation\" class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix team\" description =", "class PretixPluginMeta: name = gettext_lazy(\"Regex Validation\") author = \"pretix team\" description = gettext_lazy(\"Allows" ]
[ "time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL response", "open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of ' +", "payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL response =", "Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1", "= (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file in append mode file1", "to file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0)", "{'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload)", "= time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL", "= round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch}", "= json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file in", "in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + '", "# Writing to file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: '", "' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of ' + str(date) + '\\n')", "<gh_stars>0 #!/usr/bin/env python3 import datetime import time import json import requests epoch =", "json import requests epoch = round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}',", "dictData[0] # Writing to file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage:", "+ str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of ' + str(date) + '\\n') file1.close()", "dictData1 = dictData[0] # Writing to file in append mode file1 = open(\"TBUsed.txt\",\"a\")", "params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to", "#!/usr/bin/env python3 import datetime import time import json import requests epoch = round(time.time())", "json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file in append", "datetime import time import json import requests epoch = round(time.time()) date = time.ctime()", "'%s' % epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json()))", "= requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] #", "import datetime import time import json import requests epoch = round(time.time()) date =", "response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0]", "# Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result'])", "URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 =", "= open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of '", "epoch = round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' %", "% epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData", "requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing", "'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data", "'time': '%s' % epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data =", "python3 import datetime import time import json import requests epoch = round(time.time()) date", "round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} #", "data = json.loads(json.dumps(response.json())) dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file", "append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB", "file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) +", "= {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query',", "requests epoch = round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s'", "Writing to file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' +", "file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of ' + str(date)", "time import json import requests epoch = round(time.time()) date = time.ctime() payload =", "import time import json import requests epoch = round(time.time()) date = time.ctime() payload", "usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of ' + str(date) +", "import json import requests epoch = round(time.time()) date = time.ctime() payload = {'query':", "(data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file in append mode file1 =", "mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as", "epoch} # Prometheus URL response = requests.get('http://10.2.180.52:9090/api/v1/query', params=payload) data = json.loads(json.dumps(response.json())) dictData =", "= dictData[0] # Writing to file in append mode file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total", "date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time': '%s' % epoch} # Prometheus", "dictData = (data[u'data'][u'result']) dictData1 = dictData[0] # Writing to file in append mode", "file1 = open(\"TBUsed.txt\",\"a\") file1.write('Total usage: ' + str(int(dictData1[u'value'][1])/1000000000000.0) + ' TB as of", "import requests epoch = round(time.time()) date = time.ctime() payload = {'query': 'bucket_usage_size{bucket=\"airtindibucket\",instance=\"at001-s3.managed-dr.com:443\",job=\"minio-job\"}', 'time':" ]
[ "None: idx = S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\",", "as np import matplotlib.pyplot as plt import pandas as pd import collections from", "self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return", "linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if filename is", "evaluate_predictions(pred, Y, X=None): # Extract lower and upper prediction bands pred_l = np.min(pred,1)", "X is None: wsc_coverage = None else: # Estimated conditional coverage (worse-case slab)", "coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None: wsc_coverage =", "marg_coverage = np.mean(cover) if X is None: wsc_coverage = None else: # Estimated", "alpha=0.4, color='gray') if limits is not None: for q_idx in range(len(limits[i])): q =", "fig is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is", "colors is None: if limits is not None: colors = ['tab:blue'] * len(limits)", "limits is not None: colors = ['tab:blue'] * len(limits) if linestyles is None:", "idx = S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4,", "= None else: # Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y,", "matplotlib.pyplot as plt import pandas as pd import collections from chr import coverage", "prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover =", "xlim=None, filename=None): if colors is None: if limits is not None: colors =", "if linestyles is None: if limits is not None: linestyles = ['-'] *", "is not None: for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1,", "is not None: colors = ['tab:blue'] * len(limits) if linestyles is None: if", "plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim)", "0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if", "'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None,", "lower and upper prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal", "as pd import collections from chr import coverage import pdb class RegressionDataset(Dataset): def", "np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is", "color='gray') if limits is not None: for q_idx in range(len(limits[i])): q = limits[i][q_idx]", "= limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not", "pred_h-pred_l length = np.mean(lengths) # Length conditional on coverage idx_cover = np.where(cover)[0] length_cover", "is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is not", "if limits is not None: linestyles = ['-'] * len(limits) if fig is", "if limits is not None: for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q,", "torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def", "np.mean(lengths) # Length conditional on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for", "def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred,", "np.mean(cover) if X is None: wsc_coverage = None else: # Estimated conditional coverage", "length lengths = pred_h-pred_l length = np.mean(lengths) # Length conditional on coverage idx_cover", "Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover':", "color='black') if S is not None: idx = S[i] z = np.zeros(len(breaks),) z[idx]", "S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if", "(worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths =", "z, step=\"pre\", alpha=0.4, color='gray') if limits is not None: for q_idx in range(len(limits[i])):", "len(limits) if fig is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if", "= np.mean([lengths for i in idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage],", "Extract lower and upper prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) #", "Marginal length lengths = pred_h-pred_l length = np.mean(lengths) # Length conditional on coverage", "i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is None: if limits is not", "len(limits) if linestyles is None: if limits is not None: linestyles = ['-']", "xlim is not None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5, 3) plt.savefig(filename,", "coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths = pred_h-pred_l length = np.mean(lengths)", "= pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out", "# Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) #", "torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self):", "= pred_h-pred_l length = np.mean(lengths) # Length conditional on coverage idx_cover = np.where(cover)[0]", "lengths = pred_h-pred_l length = np.mean(lengths) # Length conditional on coverage idx_cover =", "= weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is not None: for", "None: wsc_coverage = None else: # Estimated conditional coverage (worse-case slab) wsc_coverage =", "import matplotlib.pyplot as plt import pandas as pd import collections from chr import", "self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower", "is not None: linestyles = ['-'] * len(limits) if fig is None: fig", "None: colors = ['tab:blue'] * len(limits) if linestyles is None: if limits is", "from chr import coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data", "q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is", "chr import coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data =", "[marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks,", "colors=None, linestyles=None, xlim=None, filename=None): if colors is None: if limits is not None:", "X=None): # Extract lower and upper prediction bands pred_l = np.min(pred,1) pred_h =", "out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if", "= ['tab:blue'] * len(limits) if linestyles is None: if limits is not None:", "is None: if limits is not None: linestyles = ['-'] * len(limits) if", "idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length],", "RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self,", "if X is None: wsc_coverage = None else: # Estimated conditional coverage (worse-case", "step=\"pre\", alpha=0.4, color='gray') if limits is not None: for q_idx in range(len(limits[i])): q", "plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5,", "q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density')", "S is not None: idx = S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx]", "weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is not None: for q_idx", "cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None: wsc_coverage = None", "and upper prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage", "coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths", "if S is not None: idx = S[i] z = np.zeros(len(breaks),) z[idx] =", "wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths = pred_h-pred_l length", "torch from torch.utils.data import Dataset import numpy as np import matplotlib.pyplot as plt", "S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is None: if", "Y, X=None): # Extract lower and upper prediction bands pred_l = np.min(pred,1) pred_h", "np.mean([lengths for i in idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional", "in idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length':", "= coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths = pred_h-pred_l length =", "['-'] * len(limits) if fig is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre',", "None else: # Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred,", "def evaluate_predictions(pred, Y, X=None): # Extract lower and upper prediction bands pred_l =", "class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def", "import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data =", "coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data", "None: if limits is not None: colors = ['tab:blue'] * len(limits) if linestyles", "def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index):", "conditional on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover])", "limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None:", "plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if filename is not None:", "weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is None:", "np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is not", "is None: wsc_coverage = None else: # Estimated conditional coverage (worse-case slab) wsc_coverage", "linestyles is None: if limits is not None: linestyles = ['-'] * len(limits)", "# Marginal length lengths = pred_h-pred_l length = np.mean(lengths) # Length conditional on", "from torch.utils.data import Dataset import numpy as np import matplotlib.pyplot as plt import", "= np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover]) # Combine results out", "= np.mean(lengths) # Length conditional on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths", "wsc_coverage = None else: # Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X,", "(self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower and upper prediction", "range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim", "pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float()", "# Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None:", "= torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data)", "M=100) # Marginal length lengths = pred_h-pred_l length = np.mean(lengths) # Length conditional", "import pandas as pd import collections from chr import coverage import pdb class", "for i in idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage':", "bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h)", "* len(limits) if fig is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black')", "if xlim is not None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5, 3)", "import numpy as np import matplotlib.pyplot as plt import pandas as pd import", "out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return", "index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None):", "len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower and upper prediction bands pred_l", "def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors", "if colors is None: if limits is not None: colors = ['tab:blue'] *", "= S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray')", "filename=None): if colors is None: if limits is not None: colors = ['tab:blue']", "import coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float()", "* len(limits) if linestyles is None: if limits is not None: linestyles =", "z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits", "return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None):", "cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None,", "return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower and upper prediction bands", "[length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None,", "import Dataset import numpy as np import matplotlib.pyplot as plt import pandas as", "torch.utils.data import Dataset import numpy as np import matplotlib.pyplot as plt import pandas", "None: for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx])", "return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): #", "__init__(self, X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return", "i in idx_cover]) # Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage],", "not None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5, 3) plt.savefig(filename, bbox_inches='tight', dpi=300)", "conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length", "coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None,", "pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage", "length_cover = np.mean([lengths for i in idx_cover]) # Combine results out = pd.DataFrame({'Coverage':", "for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$')", "not None: colors = ['tab:blue'] * len(limits) if linestyles is None: if limits", "z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is not None:", "plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is not None: for q_idx in", "Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal", "[wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None,", "linestyles = ['-'] * len(limits) if fig is None: fig = plt.figure() plt.step(breaks,", "slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100) # Marginal length lengths = pred_h-pred_l", "not None: linestyles = ['-'] * len(limits) if fig is None: fig =", "if limits is not None: colors = ['tab:blue'] * len(limits) if linestyles is", "fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is not None: idx", "not None: for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx],", "None: linestyles = ['-'] * len(limits) if fig is None: fig = plt.figure()", "'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights,", "color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if filename is not", "is not None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5, 3) plt.savefig(filename, bbox_inches='tight',", "__len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower and upper", "pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]}) return out def", "as plt import pandas as pd import collections from chr import coverage import", "None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is not None:", "plt.step(breaks, weights[i], where='pre', color='black') if S is not None: idx = S[i] z", "not None: idx = S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z,", "results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length cover': [length_cover]})", "None: if limits is not None: linestyles = ['-'] * len(limits) if fig", "Y, pred, M=100) # Marginal length lengths = pred_h-pred_l length = np.mean(lengths) #", "else: # Estimated conditional coverage (worse-case slab) wsc_coverage = coverage.wsc_unbiased(X, Y, pred, M=100)", "is None: if limits is not None: colors = ['tab:blue'] * len(limits) if", "is not None: idx = S[i] z = np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks,", "pred, M=100) # Marginal length lengths = pred_h-pred_l length = np.mean(lengths) # Length", "= np.zeros(len(breaks),) z[idx] = weights[i,idx] plt.fill_between(breaks, z, step=\"pre\", alpha=0.4, color='gray') if limits is", "def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract lower and", "X_data, y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index],", "colors = ['tab:blue'] * len(limits) if linestyles is None: if limits is not", "[length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0,", "where='pre', color='black') if S is not None: idx = S[i] z = np.zeros(len(breaks),)", "np import matplotlib.pyplot as plt import pandas as pd import collections from chr", "if fig is None: fig = plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S", "idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover]) # Combine results", "1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if xlim is not None: plt.xlim(xlim) if filename", "= plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is not None: idx =", "'Length': [length], 'Length cover': [length_cover]}) return out def plot_histogram(breaks, weights, S=None, fig=None, limits=None,", "= np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X", "limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is None: if limits is", "numpy as np import matplotlib.pyplot as plt import pandas as pd import collections", "['tab:blue'] * len(limits) if linestyles is None: if limits is not None: linestyles", "# Length conditional on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i", "import torch from torch.utils.data import Dataset import numpy as np import matplotlib.pyplot as", "length = np.mean(lengths) # Length conditional on coverage idx_cover = np.where(cover)[0] length_cover =", "pd import collections from chr import coverage import pdb class RegressionDataset(Dataset): def __init__(self,", "fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is None: if limits", "Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None: wsc_coverage", "import collections from chr import coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data,", "plt import pandas as pd import collections from chr import coverage import pdb", "(Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None: wsc_coverage = None else: #", "np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover)", "= (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if X is None: wsc_coverage = None else:", "plt.figure() plt.step(breaks, weights[i], where='pre', color='black') if S is not None: idx = S[i]", "in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0, 1, linestyle=linestyles[q_idx], color=colors[q_idx]) plt.xlabel('$Y$') plt.ylabel('Density') if", "self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y, X=None): # Extract", "y_data): self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index]", "self.X_data = torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def", "on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover]) #", "= np.mean(cover) if X is None: wsc_coverage = None else: # Estimated conditional", "# Combine results out = pd.DataFrame({'Coverage': [marg_coverage], 'Conditional coverage': [wsc_coverage], 'Length': [length], 'Length", "pandas as pd import collections from chr import coverage import pdb class RegressionDataset(Dataset):", "= torch.from_numpy(X_data).float() self.y_data = torch.from_numpy(y_data).float() def __getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__", "__getitem__(self, index): return self.X_data[index], self.y_data[index] def __len__ (self): return len(self.X_data) def evaluate_predictions(pred, Y,", "Length conditional on coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i in", "weights[i], where='pre', color='black') if S is not None: idx = S[i] z =", "coverage idx_cover = np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover]) # Combine", "collections from chr import coverage import pdb class RegressionDataset(Dataset): def __init__(self, X_data, y_data):", "plot_histogram(breaks, weights, S=None, fig=None, limits=None, i=0, colors=None, linestyles=None, xlim=None, filename=None): if colors is", "limits is not None: linestyles = ['-'] * len(limits) if fig is None:", "= np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage =", "= ['-'] * len(limits) if fig is None: fig = plt.figure() plt.step(breaks, weights[i],", "upper prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1) # Marginal coverage cover", "Dataset import numpy as np import matplotlib.pyplot as plt import pandas as pd", "np.where(cover)[0] length_cover = np.mean([lengths for i in idx_cover]) # Combine results out =", "# Extract lower and upper prediction bands pred_l = np.min(pred,1) pred_h = np.max(pred,1)", "limits is not None: for q_idx in range(len(limits[i])): q = limits[i][q_idx] plt.axvline(q, 0,", "pred_h = np.max(pred,1) # Marginal coverage cover = (Y>=pred_l)*(Y<=pred_h) marg_coverage = np.mean(cover) if", "None: plt.xlim(xlim) if filename is not None: fig.set_size_inches(4.5, 3) plt.savefig(filename, bbox_inches='tight', dpi=300) plt.show()", "linestyles=None, xlim=None, filename=None): if colors is None: if limits is not None: colors" ]
[ "of string length 1) or a tag (array of string length 2) or", "instead of the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if", "v): ok = False break elif op == \"approx\": # check each numerical", "else: v = dataset[tag[0]] else: v = data[tag[0]] elif len(tag) == 2: if", "here def isnegate(x): return x if ('negate' in r) and (r['negate'] == \"yes\"):", "the negate flag to this rule for i in cr: i['negate'] = \"yes\"", "except InvalidDicomError: print(\"Not a DICOM file: \", response) continue indir = '/data/scratch/archive/' if", "if there is no value in v, fail in this case ok =", "the file exists already # lets store some data in a series specific", "or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json'", "'OSERROR on creating the named pipe %s' % self.pipename pass try: rp =", "file: \", response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does", "% pid) def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except:", "(ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid > 0: #", "data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 )", "running?\\n\" sys.stderr.write(message % self.pidfile) return # not an error in a restart #", "# lets store some data in a series specific file fn3 = os.path.join(outdir,", "classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules == 0: print \"Warning: no", "stat, tempfile, copy import dicom, json, re from signal import SIGTERM from dicom.filereader", "if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False", "fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue #", "currentSliceLocation; except: pass if not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] =", "be 1, 2, or 3 entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes):", "False break except ValueError: pass elif op == \"exist\": if isnegate(not tagthere): ok", "== \"regexp\": pattern = re.compile(v2) vstring = v if isinstance(v, (int, float)): #print", "isinstance(v, (int, float)): #print \"v is : \", v, \" and v2 is:", "\"Advanced Programming in the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try:", "- set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files", "/data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules ): # add recursively rules", "read the classify rules if self.classify_rules == 0: print \"Warning: no classify rules", "\"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule in r: # find the", "print(\"Error: tag with unknown structure, should be 1, 2, or 3 entries in", "done' self.run() def send(self,arg): \"\"\" Send a message to the daemon via pipe", "= v if isinstance(v, (int, float)): #print \"v is : \", v, \"", "for relative comparisons in the classification v2 = r['value'] taghere2 = True try:", "dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path \",", "the id this rule refers to # copy the rules and append instead", "continue # don't do anything because the file exists already # lets store", "i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit here\"", "for y in classifyTypes if y != t] return classifyTypes def run(self): try:", "else: print \"Warning: no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules ):", "the 'value' could in some cases be a tag, that would allow for", "killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err:", "location (use the maximum values for all slice locations) currentSliceLocation = None try:", "> 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2", "not \"operator\" in r: r[\"operator\"] = \"regexp\" # default value op = r[\"operator\"]", "this rule for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True", "%s, ClassifyType tag will be empty\" % self.rulesFile return classifyTypes for rule in", "override the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin =", "'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles'])", "InvalidDicomError: print(\"Not a DICOM file: \", response) continue indir = '/data/scratch/archive/' if not", "except OSError: print 'Error: could not open named pipe for reading commands' sys.exit(1)", "'r') as f: data = json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation'])", "self.classify_rules[rule]['type'] # if we check on the series level all rules have to", "rules back until no more changes can be done for attempt in range(100):", "has been daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules", "self.daemonize() print ' done' self.run() def send(self,arg): \"\"\" Send a message to the", "#2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors", "runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid =", "ok # we need to be able to reference a specific rule (id", "that map to any of the images in the series) data['ClassifyType'] = self.classify(dataset,", "= {} try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except:", "this method when you subclass Daemon. It will be called after the process", "== \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename =", "v2 is: \", v2 vstring = str(v) if isnegate(not pattern.search(vstring)): # this pattern", "failed, this is it if ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes))", "'/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir = '/data/scratch/views/raw'", "os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) ==", "except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except:", "in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in", "except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB']", "pid = None os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start the daemon')", "tag with unknown structure, should be 1, 2, or 3 entries in array')", "in array') print(\"Error: tag with unknown structure, should be 1, 2, or 3", "2: if 'start' == sys.argv[1]: try: daemon.start() except: print \"Error: could not create", "'/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we should", "file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer']", "ok = False break if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) >", "(crashed). try: os.kill(pid, 0) except OSError: # The process does not exist, forget", "for reading commands' sys.exit(1) while True: response = rp.readline()[:-1] if not response: time.sleep(0.1)", "copy the rules and append instead of the reference rule findID = True", "file names for processing using 'send'.\" print \"Test the rules by running test:\"", "for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit", "= dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] =", "resolve dependencies between rules, this could introduce a problem with termination, # Todo:", "# Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except", "y != t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print", "except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except:", "generic daemon class. Usage: subclass the Daemon class and override the run() method", "int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)]", "series level all rules have to be true for every image in the", "its close to a specific value approxLevel = 1e-4 if 'approxLevel' in r:", ")): # we get this if there is no value in v, fail", "delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start the daemon \"\"\" #", "whole type and continue with the next ok = False break elif op", "back until no more changes can be done for attempt in range(100): didChange", "== r[ruleornotrule]: # found the id this rule refers to # copy the", "There are two files that make this thing work, one is the .pid", "double-fork magic, see Stevens' \"Advanced Programming in the UNIX Environment\" for details (ISBN", "list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are", "for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not", "more changes can be done for attempt in range(100): didChange = False for", "rules if self.classify_rules == 0: print \"Warning: no classify rules found in %s,", "str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value)", "(array of string length 3) v = '' taghere = True if len(tag)", "== \"<\": try: if isnegate(not float(v2) > float(v)): ok = False break except", "try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print", "one is the .pid file for the daemon # the second is the", "float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance( v, (int, float) )): #", "not an error in a restart # Try killing the daemon process try:", "data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two", "p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon =", "data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the slice location (use the maximum", "a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data =", "in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have a negated rule here", "isnegate(x): return x if ('negate' in r) and (r['negate'] == \"yes\"): def isnegate(x):", "== float(v)): ok = False break except ValueError: pass elif op == \"!=\":", "a specific value approxLevel = 1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel'])", "in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the", "== \"contains\": if isnegate(v2 not in v): ok = False break elif op", "restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start the", "file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno())", "pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass", "the daemon via pipe \"\"\" # open a named pipe and write to", "Stevens' \"Advanced Programming in the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\"", "allow for relative comparisons in the classification v2 = r['value'] taghere2 = True", "try: if isnegate(not float(v2) == float(v)): ok = False break except ValueError: pass", "a named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename,", "with the next ok = False break elif op == \"==\": try: if", "= ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start' == sys.argv[1]: try: daemon.start()", "in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print", "message = \"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) #", "creates study/series directories with symbolic links.\" print \"Use 'start' to start the daemon", "\"operator\" in r: r[\"operator\"] = \"regexp\" # default value op = r[\"operator\"] if", "list ) and isinstance(v2, list) and len(v) == len(v2): for i in range(len(v)):", "pid) def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except: pass", "and continue with the next ok = False break elif op == \"==\":", "dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer except: pass try:", "will create all type that map to any of the images in the", "pattern = re.compile(v2) vstring = v if isinstance(v, (int, float)): #print \"v is", "each numerical entry if its close to a specific value approxLevel = 1e-4", "continue else: try: dataset = dicom.read_file(response) except IOError: print(\"Could not find file:\", response)", "add recursively rules back until no more changes can be done for attempt", "pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork magic, see", "wd.close() except IOError: print 'Error: could not open the pipe %s' % self.pipename", "== 0: print \"Warning: no classify rules found in %s, ClassifyType tag will", "os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating", "and (not isinstance( v, (int, float) )): # we get this if there", "def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the named", "rp = open(self.pipename, 'r') except OSError: print 'Error: could not open named pipe", "try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try:", "path \", fn, \" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not", "the daemon \"\"\" # Get the pid from the pidfile try: pf =", "with unknown structure, should be 1, 2, or 3 entries in array') print(\"Error:", "except OSError: print 'OSERROR on creating the named pipe %s' % self.pipename pass", "changes can be done for attempt in range(100): didChange = False for rule", "pipe %s' % self.pipename pass try: rp = open(self.pipename, 'r') except OSError: print", "it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close()", "daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0", "err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1)", "fail the whole type and continue with the next ok = False break", "if self.classify_rules == 0: print \"Warning: no classify rules found in %s, ClassifyType", "if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except", "str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the slice", "== \"==\": try: if isnegate(not float(v2) == float(v)): ok = False break except", "= str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] =", "continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not exist\") continue", "v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure, should be", "elif op == \"exist\": if isnegate(not tagthere): ok = False break elif op", "= True if not findID: print \"Error: could not find a rule with", "pattern.search(vstring)): # this pattern failed, fail the whole type and continue with the", "try: rp = open(self.pipename, 'r') except OSError: print 'Error: could not open named", "not tag[0] in data: if not tag[0] in dataset: taghere = False else:", "\"\"\" # Check for a pidfile to see if the daemon already runs", "July 2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if", "the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid", "self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) #", "op == \"approx\": # check each numerical entry if its close to a", "isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit here\" ok = False break", "slice location (use the maximum values for all slice locations) currentSliceLocation = None", "isnegate(not pattern.search(vstring)): # this pattern failed, fail the whole type and continue with", "\"!=\": try: if isnegate(not float(v2) != float(v)): ok = False break except ValueError:", "== sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print", "except ValueError: pass elif op == \"exist\": if isnegate(not tagthere): ok = False", "(use the maximum values for all slice locations) currentSliceLocation = None try: currentSliceLocation", "dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName", "sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1)", "negate: ruleornotrule = \"notrule\" if ruleornotrule in r: # find the rule with", "type and continue with the next ok = False break elif op ==", "infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if", "op = r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok = False break", "not tag[0] in dataset: taghere = False else: v = dataset[tag[0]] else: v", "pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2:", "> 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\"", "except IOError: print(\"Could not find file:\", response) continue except InvalidDicomError: print(\"Not a DICOM", "== 3: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False", "try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try:", "data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName']", "a daemon process that creates study/series directories with symbolic links.\" print \"Use 'start'", "True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag to", "from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" %", "not x # check if this regular expression matches the current type t", "parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror))", "after the process has been daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon):", "except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except:", "op == \"notexist\": if isnegate(tagthere): ok = False break elif op == \"regexp\":", "= self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with", "\"\\n\") wd.flush() wd.close() except IOError: print 'Error: could not open the pipe %s'", "isinstance(v, list)) and (not isinstance( v, (int, float) )): # we get this", "# we get this if there is no value in v, fail in", "%s test\" % sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print", "except IOError: pid = None if not pid: message = \"pidfile %s does", "% self.pidfile) # Maybe the pid file exits - but the process is", "rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found", "False break elif op == \"==\": try: if isnegate(not float(v2) == float(v)): ok", "sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else:", "http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid > 0: # exit first", "0: print \"Warning: no classify rules found in %s, ClassifyType tag will be", "'' taghere = True if len(tag) == 1: if not tag[0] in data:", "self.run() def send(self,arg): \"\"\" Send a message to the daemon via pipe \"\"\"", "= False for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] ==", "data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID']", "len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM", "isnegate(v2 not in v): ok = False break elif op == \"approx\": #", "are two files that make this thing work, one is the .pid file", "== \"notexist\": if isnegate(tagthere): ok = False break elif op == \"regexp\": pattern", "= None if pid: message = \"pidfile %s already exist. Daemon already running?\\n\"", "= int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = \"pidfile", "re from signal import SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A", "we get this if there is no value in v, fail in this", "specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try:", "r['value'] taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 =", "# read the classify rules if self.classify_rules == 0: print \"Warning: no classify", "case ok = False break if isinstance( v, list ) and isinstance(v2, list)", "if not tag[0] in dataset: taghere = False else: v = dataset[tag[0]] else:", "failed, fail the whole type and continue with the next ok = False", "dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0) ) in", "2) or a specific index into a tag (array of string length 3)", "python2.7 %s test\" % sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0]", "Daemon. It will be called after the process has been daemonized by start()", "pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass", "(\"notrule\" in r) ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule", "ValueError: pass elif op == \"<\": try: if isnegate(not float(v2) > float(v)): ok", "make sure that the rules are ok # we need to be able", "#data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True)", "not open named pipe for reading commands' sys.exit(1) while True: response = rp.readline()[:-1]", "'/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon", "the process is not running (crashed). try: os.kill(pid, 0) except OSError: # The", "to the program to make sure that the rules are ok # we", "= False break elif op == \"==\": try: if isnegate(not float(v2) == float(v)):", "False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure,", "r['value'] if not \"operator\" in r: r[\"operator\"] = \"regexp\" # default value op", "Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid file exits -", "tag with unknown structure, should be 1, 2, or 3 entries in array\")", "elif len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere", "v if isinstance(v, (int, float)): #print \"v is : \", v, \" and", "data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType']", "found in %s, ClassifyType tag will be empty\" % self.rulesFile return classifyTypes for", "Maybe the pid file exits - but the process is not running (crashed).", "pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() +", "%s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does not", "classify_rules def resolveValue(self,tag,dataset,data): # a value can be a tag (array of string", "if len(tag) == 1: if not tag[0] in data: if not tag[0] in", "None if not pid: message = \"pidfile %s does not exist. Daemon not", "and creates a Study/Series symbolic link structure. \"\"\" import sys, os, time, atexit,", "that ID findID = False for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2]", "check if this regular expression matches the current type t taghere = True", "data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 ) # add new", "classifyTypes): classifyTypes = [y for y in classifyTypes if y != t] return", "atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the named pipe %s' % self.pipename", "ValueError('Error: tag with unknown structure, should be 1, 2, or 3 entries in", "the classify rules if self.classify_rules == 0: print \"Warning: no classify rules found", "the rules are ok # we need to be able to reference a", "\", response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not", "in r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance( v,", "the end) seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"):", "could not open named pipe for reading commands' sys.exit(1) while True: response =", "except IOError: print 'Error: could not open the pipe %s' % self.pipename else:", "print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send' == sys.argv[1]:", "in a restart # Try killing the daemon process try: while 1: os.kill(pid,", "specific value approxLevel = 1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if", "exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid file exits", "sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self):", "= '' taghere = True if len(tag) == 1: if not tag[0] in", "\" and v2 is: \", v2 vstring = str(v) if isnegate(not pattern.search(vstring)): #", "> approxLevel): #print \"approx does not fit here\" ok = False break if", "process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err)", "Start the daemon print(' start the daemon') self.daemonize() print ' done' self.run() def", "dataset[0x0043,0x1039].value except: pass # keep the slice location (use the maximum values for", "os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid", "break return classify_rules def resolveValue(self,tag,dataset,data): # a value can be a tag (array", "error in a restart # Try killing the daemon process try: while 1:", "to a specific value approxLevel = 1e-4 if 'approxLevel' in r: approxLevel =", "the daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You should override this method", "e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r')", "= [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 ) #", "break except ValueError: pass elif op == \"<\": try: if isnegate(not float(v2) >", "json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation;", "op == \"!=\": try: if isnegate(not float(v2) != float(v)): ok = False break", "os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn):", "\", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart()", "at the end) seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] ==", "if isnegate(not tagthere): ok = False break elif op == \"contains\": if isnegate(v2", "send messages and reads a DICOM file, extracts the header information and creates", "if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a value can be", "string length 3) v = '' taghere = True if len(tag) == 1:", "seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck =", "if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else: v", "program to make sure that the rules are ok # we need to", "atexit, stat, tempfile, copy import dicom, json, re from signal import SIGTERM from", "= dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 ) # add new types", "str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try:", "via pipe \"\"\" # open a named pipe and write to it if", "\"Error: could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]:", "except ValueError: pass elif op == \"<\": try: if isnegate(not float(v2) > float(v)):", "= int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message =", "not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path \", fn, \"", "open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print 'Error: could not", "int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = \"pidfile %s", "try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try:", "not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv)", "failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\")", "if this regular expression matches the current type t taghere = True try:", "empty\" % self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] #", "in r) ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule in", "ok = False break elif op == \"contains\": if isnegate(v2 not in v):", "= str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] =", "if ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not", "os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\"", "rules are ok # we need to be able to reference a specific", "daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\" #", "not ok and (t in classifyTypes): classifyTypes = [y for y in classifyTypes", "daemon \"\"\" # Get the pid from the pidfile try: pf = file(self.pidfile,'r')", "approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance( v, (int, float)", "\"notexist\": if isnegate(tagthere): ok = False break elif op == \"regexp\": pattern =", "the header information and creates a Study/Series symbolic link structure. \"\"\" import sys,", "= True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have", "if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if", "decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try: pid", "isnegate(not tagthere): ok = False break elif op == \"contains\": if isnegate(v2 not", "data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] =", "+ list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok and (t in classifyTypes):", "False else: v = dataset[tag[0]] else: v = data[tag[0]] elif len(tag) == 2:", "op == \">\": try: if isnegate(not float(v2) < float(v)): ok = False break", "data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence']", "( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else: v = dataset[int(tag[0],0),", "cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print \"Error:", "try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except: pass try:", "os.path.exists(fn3): with open(fn3, 'r') as f: data = json.load(f) if currentSliceLocation != None:", "in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset,", "\"\"\" # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid", "classify rules if self.classify_rules == 0: print \"Warning: no classify rules found in", "'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules )", "in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit here\" ok", "__init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr =", "tag (array of string length 2) or a specific index into a tag", "dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID", "already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid", "not open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to", "be a tag (array of string length 1) or a tag (array of", "except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except:", "pass def delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start the daemon", "v, (int, float) )): # we get this if there is no value", "v, list ) and isinstance(v2, list) and len(v) == len(v2): for i in", "process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self):", "pass if not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles']", "try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start the daemon \"\"\" # Check", "process that listens to send messages and reads a DICOM file, extracts the", "with termination, # Todo: add a check to the program to make sure", "daemon via pipe \"\"\" # open a named pipe and write to it", "isnegate(not float(v2) > float(v)): ok = False break except ValueError: pass elif op", "be empty\" % self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type']", "== 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files", "create all type that map to any of the images in the series)", "= False for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry]", "= False break elif op == \"regexp\": pattern = re.compile(v2) vstring = v", "dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime)", "else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does not exist\\n\") sys.exit(1) def", "= str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] =", "'Error: could not open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the", "\"Error: creating path \", fn, \" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID)", "or 3 entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read the", "t taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue #", "!= None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if", "= r['value'] if not \"operator\" in r: r[\"operator\"] = \"regexp\" # default value", "to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush()", "taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2 == False:", "as f: data = json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation']) >", "= float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance( v, (int, float) )):", "except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except:", "r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance( v, (int,", "data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID']", "#print \"approx does not fit here\" ok = False break if isinstance( v,", "ok nobody failed, this is it if ok: classifyTypes = classifyTypes + list(set([t])", "ok and (t in classifyTypes): classifyTypes = [y for y in classifyTypes if", "dataset = dicom.read_file(response) except IOError: print(\"Could not find file:\", response) continue except InvalidDicomError:", "== \">\": try: if isnegate(not float(v2) < float(v)): ok = False break except", "return classify_rules def resolveValue(self,tag,dataset,data): # a value can be a tag (array of", "print \"Error: could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' ==", "time.sleep(0.1) except OSError, err: err = str(err) if err.find(\"No such process\") > 0:", "currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass", "running (crashed). try: os.kill(pid, 0) except OSError: # The process does not exist,", "\" find <dicomdir> -type f -print | grep -v .json | xargs -i", "start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile =", "if not os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir = '/data/scratch/views/raw' if", "by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile", "in data: if not tag[0] in dataset: taghere = False else: v =", "the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close()", "if currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except:", "float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType' in data:", "(e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do", "connection to the daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the", "break elif op == \"==\": try: if isnegate(not float(v2) == float(v)): ok =", "not os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir = '/data/scratch/views/raw' if not", "self.classify_rules == 0: print \"Warning: no classify rules found in %s, ClassifyType tag", "running test:\" print \" python2.7 %s test\" % sys.argv[0] print \"\" print \"Usage:", "+ '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start' ==", "file exists already # lets store some data in a series specific file", "-type f -print | grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\" >>", "if negate: ruleornotrule = \"notrule\" if ruleornotrule in r: # find the rule", "= False break if isinstance( v, list ) and isinstance(v2, list) and len(v)", "pf.close() except IOError: pid = None if not pid: message = \"pidfile %s", "the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork()", "all rules have to be true for every image in the series (remove", "dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID", "process has been daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self):", "every image in the series (remove at the end) seriesLevelCheck = False if", "= True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag", "dicom, json, re from signal import SIGTERM from dicom.filereader import InvalidDicomError class Daemon:", "to be true for every image in the series (remove at the end)", "data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f:", "= str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] =", "sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid)", "def classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules == 0: print \"Warning:", "else: try: dataset = dicom.read_file(response) except IOError: print(\"Could not find file:\", response) continue", "class Daemon: \"\"\" A generic daemon class. Usage: subclass the Daemon class and", "self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile self.pipename", "we need to be able to reference a specific rule (id tag?) self.classify_rules", "pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except:", "(%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0)", "a tag, that would allow for relative comparisons in the classification v2 =", "not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return # not an error", "1, 2, or 3 entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes): #", "if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast using", "if not response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except IOError: print(\"Could", "indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send'", "except: pass if not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID", "stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile", "\"\"\" Create a daemon process that listens to send messages and reads a", "): # add recursively rules back until no more changes can be done", "not exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response)", "'send'.\" print \"Test the rules by running test:\" print \" python2.7 %s test\"", "'start' == sys.argv[1]: try: daemon.start() except: print \"Error: could not create processing daemon:", "# write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try:", "parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try: pid = os.fork()", "str(v) if isnegate(not pattern.search(vstring)): # this pattern failed, fail the whole type and", "in the background. Send file names for processing using 'send'.\" print \"Test the", "os.umask(0) # do second fork try: pid = os.fork() if pid > 0:", "e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from", "for attempt in range(100): didChange = False for rule in range(len(classify_rules)): for entry", "' done' self.run() def send(self,arg): \"\"\" Send a message to the daemon via", "r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule = \"rule\" if negate:", "ClassifyType tag will be empty\" % self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)):", "pipe for reading commands' sys.exit(1) while True: response = rp.readline()[:-1] if not response:", "except: pass try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except:", "already # lets store some data in a series specific file fn3 =", "creating path \", fn, \" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if", "by:\" print \" find <dicomdir> -type f -print | grep -v .json |", "3 entries in array') print(\"Error: tag with unknown structure, should be 1, 2,", "expression matches the current type t taghere = True try: taghere, v =", "in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) ==", "class and override the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):", "v2 vstring = str(v) if isnegate(not pattern.search(vstring)): # this pattern failed, fail the", "isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break", "OSError, err: err = str(err) if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile):", "except: pass def delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start the", "try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try:", "for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate =", "SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find(\"No such process\") >", "message = \"pidfile %s does not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile)", "str(err) if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print", "type that map to any of the images in the series) data['ClassifyType'] =", "'start' to start the daemon in the background. Send file names for processing", "does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\" # Get", "a rule with ID %s\" % r[ruleornotrule] continue if not didChange: break return", "between rules, this could introduce a problem with termination, # Todo: add a", "self.pidfile) # Maybe the pid file exits - but the process is not", "== \"SeriesLevel\"): seriesLevelCheck = True ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r", "negate flag to this rule for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr)", "file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid)", "sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork", "that the rules are ok # we need to be able to reference", "second is the named pipe in /tmp/.processSingleFile # Hauke, July 2015 if __name__", "f: self.classify_rules = json.load(f) # we should resolve dependencies between rules, this could", "a tag (array of string length 3) v = '' taghere = True", "try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try:", "if ('negate' in r) and (r['negate'] == \"yes\"): def isnegate(x): return not x", ") # add new types as they are found (this will create all", "Hauke, July 2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename)", "the program to make sure that the rules are ok # we need", "will be called after the process has been daemonized by start() or restart().", "DICOM files fast using a daemon process that creates study/series directories with symbolic", "seriesLevelCheck and not ok and (t in classifyTypes): classifyTypes = [y for y", "= dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure, should be 1,", "class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with", "= [y for y in classifyTypes if y != t] return classifyTypes def", "rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\"", "try: if isnegate(not float(v2) > float(v)): ok = False break except ValueError: pass", "failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush()", "'r') except OSError: print 'Error: could not open named pipe for reading commands'", "dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription", "structure, should be 1, 2, or 3 entries in array\") return taghere, v", "print ' done' self.run() def send(self,arg): \"\"\" Send a message to the daemon", "daemon') self.daemonize() print ' done' self.run() def send(self,arg): \"\"\" Send a message to", "rules found in %s, ClassifyType tag will be empty\" % self.rulesFile return classifyTypes", "DICOM file: \", response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir", "pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass", "'/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork magic, see Stevens' \"Advanced Programming", "return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating", "processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' ==", "isnegate(not float(v2) != float(v)): ok = False break except ValueError: pass elif op", "else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send' ==", "with unknown structure, should be 1, 2, or 3 entries in array\") return", "rp.close() # There are two files that make this thing work, one is", "i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print \"Error: could", "that make this thing work, one is the .pid file for the daemon", "int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure, should be 1, 2, or", "file exits - but the process is not running (crashed). try: os.kill(pid, 0)", "and (r['negate'] == \"yes\"): def isnegate(x): return not x # check if this", "pass elif op == \">\": try: if isnegate(not float(v2) < float(v)): ok =", "able to reference a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print", "elif op == \"!=\": try: if isnegate(not float(v2) != float(v)): ok = False", "ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r')", "try: os.kill(pid, 0) except OSError: # The process does not exist, forget the", "the series (remove at the end) seriesLevelCheck = False if ('check' in self.classify_rules[rule])", "True: response = rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try: dataset =", "pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass", "is the named pipe in /tmp/.processSingleFile # Hauke, July 2015 if __name__ ==", "= False else: v = dataset[tag[0]] else: v = data[tag[0]] elif len(tag) ==", "response) continue except InvalidDicomError: print(\"Not a DICOM file: \", response) continue indir =", "is not running (crashed). try: os.kill(pid, 0) except OSError: # The process does", "'/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID)", "os.path.exists(fn): print \"Error: creating path \", fn, \" did not work\" fn2 =", "data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1", "+ \".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality']", "files fast using a daemon process that creates study/series directories with symbolic links.\"", "== sys.argv[1]: try: daemon.start() except: print \"Error: could not create processing daemon: \",", "findID = False for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id']", "self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork magic, see Stevens'", "print(' start the daemon') self.daemonize() print ' done' self.run() def send(self,arg): \"\"\" Send", "of the images in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] =", "#1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment", "3) v = '' taghere = True if len(tag) == 1: if not", "names for processing using 'send'.\" print \"Test the rules by running test:\" print", "append instead of the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules'])", "ValueError: v2 = r['value'] if taghere2 == False: v2 = r['value'] if not", "# default value op = r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok", "print(\"Error: indir does not exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir)", "%s does not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return # not", "str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber)", "that creates study/series directories with symbolic links.\" print \"Use 'start' to start the", "of string length 2) or a specific index into a tag (array of", "str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value)", "!= float(v)): ok = False break except ValueError: pass elif op == \"<\":", "tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start'", "pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except", "float) )): # we get this if there is no value in v,", "pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] =", "self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could be found\" def", "True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have a", "images in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] +", "\".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] =", "pid and wait to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start", "refers to # copy the rules and append instead of the reference rule", "def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr", "== \"approx\": # check each numerical entry if its close to a specific", "be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start", "try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value)", "os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't do", "data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription']", "work, one is the .pid file for the daemon # the second is", "= str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0)", "(e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin,", "v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else:", "cases be a tag, that would allow for relative comparisons in the classification", "to any of the images in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType'])", "set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that", "to the daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon", "op == \"==\": try: if isnegate(not float(v2) == float(v)): ok = False break", "study/series directories with symbolic links.\" print \"Use 'start' to start the daemon in", "print \"For a simple test send a DICOM directory by:\" print \" find", "taghere = False else: v = dataset[tag[0]] else: v = data[tag[0]] elif len(tag)", "str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value)", "print 'Error: could not open named pipe for reading commands' sys.exit(1) while True:", "delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except: pass def start(self):", "does not exist, forget the pid and wait to be restarted.. pid =", "using 'send'.\" print \"Test the rules by running test:\" print \" python2.7 %s", "Check for a pidfile to see if the daemon already runs try: pf", "if isnegate(tagthere): ok = False break elif op == \"regexp\": pattern = re.compile(v2)", "\"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print \"Error: could not find", "0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart", "try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try:", "already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid file exits - but", "from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try: pid =", "pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass", "do second fork try: pid = os.fork() if pid > 0: # exit", "the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except", "dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime)", "(r['negate'] == \"yes\"): def isnegate(x): return not x # check if this regular", "continue if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a value can", "data = json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation']", "IOError: pid = None if not pid: message = \"pidfile %s does not", "dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 ) # add new types as", "stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile =", "else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure, should", "except ValueError: continue # the 'value' could in some cases be a tag,", "response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not exist\")", "if isnegate(not pattern.search(vstring)): # this pattern failed, fail the whole type and continue", "the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data))", "try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\"", "len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere =", "# this pattern failed, fail the whole type and continue with the next", "elif op == \"approx\": # check each numerical entry if its close to", "stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe'", "os.remove(self.pipename) except: pass def start(self): \"\"\" Start the daemon \"\"\" # Check for", "= os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename)", "sys.argv[1]: try: daemon.start() except: print \"Error: could not create processing daemon: \", sys.exc_info()[0]", "classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the", "SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic daemon class. Usage:", "because the file exists already # lets store some data in a series", "rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could", "try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try:", "wait to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start the daemon", "== len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does", "findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate", "False break if isinstance( v, list ) and isinstance(v2, list) and len(v) ==", ") in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag)", "daemon process that listens to send messages and reads a DICOM file, extracts", "pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg", "0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid =", "= False break else: ok = False break # ok nobody failed, this", "ruleornotrule in r: # find the rule with that ID findID = False", "ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start' == sys.argv[1]: try: daemon.start() except:", "except IOError: pid = None if pid: message = \"pidfile %s already exist.", "break if isinstance( v, list ) and isinstance(v2, list) and len(v) == len(v2):", "3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast", "# exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\"", "not running?\\n\" sys.stderr.write(message % self.pidfile) return # not an error in a restart", "self.pipename pass try: rp = open(self.pipename, 'r') except OSError: print 'Error: could not", "such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def", "= '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork magic, see Stevens' \"Advanced", "\">\": try: if isnegate(not float(v2) < float(v)): ok = False break except ValueError:", "1 ) # add new types as they are found (this will create", "array') print(\"Error: tag with unknown structure, should be 1, 2, or 3 entries", "v2 = r['value'] taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError:", "called after the process has been daemonized by start() or restart(). \"\"\" class", "= \"notrule\" if ruleornotrule in r: # find the rule with that ID", "% (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) #", "string length 1) or a tag (array of string length 2) or a", "type t taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue", "current type t taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError:", "it if ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and", "= file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not", "> approxLevel): ok = False break else: ok = False break # ok", "== sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast using a daemon", "\" python2.7 %s test\" % sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" %", "except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except:", "False break elif op == \"approx\": # check each numerical entry if its", "run(self): \"\"\" You should override this method when you subclass Daemon. It will", "list)) and (not isinstance( v, (int, float) )): # we get this if", "def isnegate(x): return not x # check if this regular expression matches the", "v2 = r['value'] if taghere2 == False: v2 = r['value'] if not \"operator\"", "classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok and", "exists already # lets store some data in a series specific file fn3", "this case ok = False break if isinstance( v, list ) and isinstance(v2,", "continue except InvalidDicomError: print(\"Not a DICOM file: \", response) continue indir = '/data/scratch/archive/'", "None if pid: message = \"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message", "): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else: ok = False", "entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have a negated rule", "err = str(err) if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename)", "creates a Study/Series symbolic link structure. \"\"\" import sys, os, time, atexit, stat,", "classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok and (t in", "copy import dicom, json, re from signal import SIGTERM from dicom.filereader import InvalidDicomError", "for every image in the series (remove at the end) seriesLevelCheck = False", "for all slice locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except: pass", "from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic daemon class. Usage: subclass", "if y != t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError:", "try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except: pass try:", "\"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the", "links.\" print \"Use 'start' to start the daemon in the background. Send file", "in range(100): didChange = False for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])):", "\"approx does not fit here\" ok = False break if isinstance( v, (int,", "= re.compile(v2) vstring = v if isinstance(v, (int, float)): #print \"v is :", "get this if there is no value in v, fail in this case", "float(v2) < float(v)): ok = False break except ValueError: pass elif op ==", "\"\" print \"For a simple test send a DICOM directory by:\" print \"", "if pid: message = \"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message %", "\"==\": try: if isnegate(not float(v2) == float(v)): ok = False break except ValueError:", "stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError:", "%s already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid", "signal import SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic daemon", "try: if isnegate(not float(v2) < float(v)): ok = False break except ValueError: pass", "introduce a problem with termination, # Todo: add a check to the program", "will be empty\" % self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t =", "r: r[\"operator\"] = \"regexp\" # default value op = r[\"operator\"] if op ==", "the connection to the daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop", "pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message", "= False break elif op == \"approx\": # check each numerical entry if", "== sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print", "end) seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck", "in /tmp/.processSingleFile # Hauke, July 2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid'", "this rule refers to # copy the rules and append instead of the", "named pipe for reading commands' sys.exit(1) while True: response = rp.readline()[:-1] if not", "range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check on the series level all", "= os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error:", "f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that make this thing work,", "= data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r') as f: data =", "approxLevel): ok = False break else: ok = False break # ok nobody", "and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok = True for entry in", "as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that make this thing", "pass try: rp = open(self.pipename, 'r') except OSError: print 'Error: could not open", "data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value", "= self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self,", "a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json", "data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation']", "this thing work, one is the .pid file for the daemon # the", "if we check on the series level all rules have to be true", "elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' ==", "'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print 'Error: could not open", "break # ok nobody failed, this is it if ok: classifyTypes = classifyTypes", "IOError: print(\"Could not find file:\", response) continue except InvalidDicomError: print(\"Not a DICOM file:", "with symbolic links.\" print \"Use 'start' to start the daemon in the background.", "+ 1 ) # add new types as they are found (this will", "pid: message = \"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile)", "dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription", "% self.pidfile) return # not an error in a restart # Try killing", "daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules(", "for processing using 'send'.\" print \"Test the rules by running test:\" print \"", "sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent", "response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except IOError: print(\"Could not find", "if not findID: print \"Error: could not find a rule with ID %s\"", "== 2: if 'start' == sys.argv[1]: try: daemon.start() except: print \"Error: could not", "test\" % sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\"", "\", v2 vstring = str(v) if isnegate(not pattern.search(vstring)): # this pattern failed, fail", "self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules", "('negate' in r) and (r['negate'] == \"yes\"): def isnegate(x): return not x #", "open(fn3, 'r') as f: data = json.load(f) if currentSliceLocation != None: try: if", "= dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] =", "file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno())", "in classifyTypes): classifyTypes = [y for y in classifyTypes if y != t]", "= dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] =", "background. Send file names for processing using 'send'.\" print \"Test the rules by", "'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and (not isinstance(", "reference rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add", "the second is the named pipe in /tmp/.processSingleFile # Hauke, July 2015 if", "return x if ('negate' in r) and (r['negate'] == \"yes\"): def isnegate(x): return", "maximum values for all slice locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation']", "\"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile):", "op == \"<\": try: if isnegate(not float(v2) > float(v)): ok = False break", "(this will create all type that map to any of the images in", "break else: ok = False break # ok nobody failed, this is it", "%s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a simple test send a", "self.classify_rules = json.load(f) # we should resolve dependencies between rules, this could introduce", "else: raise ValueError('Error: tag with unknown structure, should be 1, 2, or 3", "= str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] =", "if not tag[0] in data: if not tag[0] in dataset: taghere = False", "open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the", "or 3 entries in array') print(\"Error: tag with unknown structure, should be 1,", "of string length 3) v = '' taghere = True if len(tag) ==", "ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could", "Create a daemon process that listens to send messages and reads a DICOM", "and reads a DICOM file, extracts the header information and creates a Study/Series", "and isinstance(v2, list) and len(v) == len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i]))", "nobody failed, this is it if ok: classifyTypes = classifyTypes + list(set([t]) -", "= 1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list))", "value op = r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok = False", "\"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2])", "in r: # find the rule with that ID findID = False for", "self.stop() self.start() def run(self): \"\"\" You should override this method when you subclass", "= False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True", "a specific index into a tag (array of string length 3) v =", "open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that make this", "'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) #", "f: data = json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation):", "a negated rule here def isnegate(x): return x if ('negate' in r) and", "# Check for a pidfile to see if the daemon already runs try:", "list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok and (t in classifyTypes): classifyTypes", "send(self,arg): \"\"\" Send a message to the daemon via pipe \"\"\" # open", "# decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try:", "try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the named pipe %s'", "str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value)", "= False break # ok nobody failed, this is it if ok: classifyTypes", "UNIX double-fork magic, see Stevens' \"Advanced Programming in the UNIX Environment\" for details", "pid = None if not pid: message = \"pidfile %s does not exist.", "running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid file exits - but the", "if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if", "try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try:", "f -print | grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\" >> /tmp/.processSingleFilePipe\"", "you subclass Daemon. It will be called after the process has been daemonized", "os, time, atexit, stat, tempfile, copy import dicom, json, re from signal import", "OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect", "in dataset: taghere = False else: v = dataset[tag[0]] else: v = data[tag[0]]", "this regular expression matches the current type t taghere = True try: taghere,", "-print | grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\" >> /tmp/.processSingleFilePipe\" print", "using a daemon process that creates study/series directories with symbolic links.\" print \"Use", "try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2 ==", "no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules ): # add recursively", "self.stderr = stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do", "messages and reads a DICOM file, extracts the header information and creates a", "try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None", "sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast using a daemon process", "else: print \"Process DICOM files fast using a daemon process that creates study/series", "\"regexp\" # default value op = r[\"operator\"] if op == \"notexist\": if isnegate(tagthere):", "data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription']", "work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue", "a problem with termination, # Todo: add a check to the program to", "if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else: ok = False break", "data: if not tag[0] in dataset: taghere = False else: v = dataset[tag[0]]", "ok = False break elif op == \"approx\": # check each numerical entry", "while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find(\"No", "% self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if", "#se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write", "# add the negate flag to this rule for i in cr: i['negate']", "self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does not exist\\n\") sys.exit(1)", "int(tag[1],0) ) in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif", "v def classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules == 0: print", "isnegate(not float(v2) < float(v)): ok = False break except ValueError: pass elif op", "the daemon print(' start the daemon') self.daemonize() print ' done' self.run() def send(self,arg):", "if (not isinstance(v, list)) and (not isinstance( v, (int, float) )): # we", "\"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a simple test send", "False for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate", "= str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the", "self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork", "except OSError, err: err = str(err) if err.find(\"No such process\") > 0: if", "when you subclass Daemon. It will be called after the process has been", "file:\", response) continue except InvalidDicomError: print(\"Not a DICOM file: \", response) continue indir", "data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber']", "= self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2 == False: v2 =", "# we could have a negated rule here def isnegate(x): return x if", "done for attempt in range(100): didChange = False for rule in range(len(classify_rules)): for", "time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except IOError: print(\"Could not find file:\",", "if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p):", "dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer except: pass", "# we need to be able to reference a specific rule (id tag?)", "#so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno())", "wd = open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print 'Error:", "try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try:", "parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror))", "tag, that would allow for relative comparisons in the classification v2 = r['value']", "UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if", "op == \"contains\": if isnegate(v2 not in v): ok = False break elif", "close to a specific value approxLevel = 1e-4 if 'approxLevel' in r: approxLevel", "= dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] =", "listens to send messages and reads a DICOM file, extracts the header information", "except ValueError: pass elif op == \">\": try: if isnegate(not float(v2) < float(v)):", "check each numerical entry if its close to a specific value approxLevel =", "\"regexp\": pattern = re.compile(v2) vstring = v if isinstance(v, (int, float)): #print \"v", "r) ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule in r:", "[y for y in classifyTypes if y != t] return classifyTypes def run(self):", "import sys, os, time, atexit, stat, tempfile, copy import dicom, json, re from", "os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we should resolve dependencies", "ValueError: pass elif op == \"!=\": try: if isnegate(not float(v2) != float(v)): ok", "== False: v2 = r['value'] if not \"operator\" in r: r[\"operator\"] = \"regexp\"", "return not x # check if this regular expression matches the current type", "named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w')", "self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could in some cases be a", "/tmp/.processSingleFile # Hauke, July 2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p", "2, or 3 entries in array') print(\"Error: tag with unknown structure, should be", "# Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid =", "level all rules have to be true for every image in the series", "pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass", "self.classify_rules[rule]['rules'][entry] # we could have a negated rule here def isnegate(x): return x", "try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try:", "specific index into a tag (array of string length 3) v = ''", "the Daemon class and override the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null',", "= dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] =", "1, 2, or 3 entries in array') print(\"Error: tag with unknown structure, should", "fn, \" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response,", "re.compile(v2) vstring = v if isinstance(v, (int, float)): #print \"v is : \",", "raise ValueError('Error: tag with unknown structure, should be 1, 2, or 3 entries", "(int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else: ok", "negate = (\"notrule\" in r) ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\"", "# Maybe the pid file exits - but the process is not running", "rule refers to # copy the rules and append instead of the reference", "DICOM file, extracts the header information and creates a Study/Series symbolic link structure.", "on the series level all rules have to be true for every image", "print \"Warning: no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules ): #", "series (remove at the end) seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and", "= self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could in some cases be", "process that creates study/series directories with symbolic links.\" print \"Use 'start' to start", "negate: # add the negate flag to this rule for i in cr:", "False break except ValueError: pass elif op == \"<\": try: if isnegate(not float(v2)", "structure. \"\"\" import sys, os, time, atexit, stat, tempfile, copy import dicom, json,", "= os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not", "\"\"\" You should override this method when you subclass Daemon. It will be", "int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value", "= dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0) )", "os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find(\"No such process\")", "(not isinstance(v, list)) and (not isinstance( v, (int, float) )): # we get", "else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not ( int(tag[0],0),", "entries in array') print(\"Error: tag with unknown structure, should be 1, 2, or", "DICOM directory by:\" print \" find <dicomdir> -type f -print | grep -v", "see if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip())", "next ok = False break elif op == \"==\": try: if isnegate(not float(v2)", "this is it if ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if", "= False break except ValueError: pass elif op == \"<\": try: if isnegate(not", "1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and", "= currentSliceLocation; except: pass if not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID']", "ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok", "dataset: taghere = False else: v = dataset[tag[0]] else: v = data[tag[0]] elif", "exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn", "'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else:", "entry if its close to a specific value approxLevel = 1e-4 if 'approxLevel'", "except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) #", "'r') #so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(),", "= False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not", "pid = None if pid: message = \"pidfile %s already exist. Daemon already", "in the classification v2 = r['value'] taghere2 = True try: taghere2, v2 =", "two files that make this thing work, one is the .pid file for", "are ok # we need to be able to reference a specific rule", "not os.path.exists(fn): print \"Error: creating path \", fn, \" did not work\" fn2", "= str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] =", "taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the", "r['value'] if taghere2 == False: v2 = r['value'] if not \"operator\" in r:", "<reponame>sigmadg/sigmadg.github.io<filename>Cuadro_Magico/code/bin/processSingleFile.py<gh_stars>0 #!/Usr/bin/env python \"\"\" Create a daemon process that listens to send messages", "magic, see Stevens' \"Advanced Programming in the UNIX Environment\" for details (ISBN 0201563177)", "OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple", "print \"Warning: no classify rules found in %s, ClassifyType tag will be empty\"", "the named pipe %s' % self.pipename pass try: rp = open(self.pipename, 'r') except", "= dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] =", "# we should resolve dependencies between rules, this could introduce a problem with", "except: pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except:", "matches the current type t taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data)", "there is no value in v, fail in this case ok = False", "# a value can be a tag (array of string length 1) or", "daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start' == sys.argv[1]: try:", "except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) #", "if not pid: message = \"pidfile %s does not exist. Daemon not running?\\n\"", "length 3) v = '' taghere = True if len(tag) == 1: if", "= daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2)", "# ok nobody failed, this is it if ok: classifyTypes = classifyTypes +", "a daemon process that listens to send messages and reads a DICOM file,", "str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber)", "if isnegate(not float(v2) > float(v)): ok = False break except ValueError: pass elif", "except: print \"Error: could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop'", "\", v, \" and v2 is: \", v2 vstring = str(v) if isnegate(not", "second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno,", "in a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data", "in r) and (r['negate'] == \"yes\"): def isnegate(x): return not x # check", "print \"Test the rules by running test:\" print \" python2.7 %s test\" %", "try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0)", "pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass", "sys.exit(1) # Start the daemon print(' start the daemon') self.daemonize() print ' done'", "the daemon') self.daemonize() print ' done' self.run() def send(self,arg): \"\"\" Send a message", "# the 'value' could in some cases be a tag, that would allow", "for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: #", "could introduce a problem with termination, # Todo: add a check to the", "been daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules =", "Stop the daemon \"\"\" # Get the pid from the pidfile try: pf", "be 1, 2, or 3 entries in array') print(\"Error: tag with unknown structure,", "for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid >", "regular expression matches the current type t taghere = True try: taghere, v", "sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+',", "\"\"\" A generic daemon class. Usage: subclass the Daemon class and override the", "# There are two files that make this thing work, one is the", "resolveValue(self,tag,dataset,data): # a value can be a tag (array of string length 1)", "if isnegate(v2 not in v): ok = False break elif op == \"approx\":", "continue # the 'value' could in some cases be a tag, that would", "fit here\" ok = False break if isinstance( v, (int, float) ): if", "ID findID = False for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and", "# add new types as they are found (this will create all type", "atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except: pass", "wd.flush() wd.close() except IOError: print 'Error: could not open the pipe %s' %", "float(v)): ok = False break except ValueError: pass elif op == \"<\": try:", "#os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def", "= True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value'", "exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\" # Get the pid", "with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we should resolve dependencies between", "method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout =", "to reference a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning:", "findID: print \"Error: could not find a rule with ID %s\" % r[ruleornotrule]", "from signal import SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic", "dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't do anything", "fork try: pid = os.fork() if pid > 0: # exit from second", "% r[ruleornotrule] continue if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a", "if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not isinstance(v, list)) and (not", "os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError,", "= str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except:", "unknown structure, should be 1, 2, or 3 entries in array\") return taghere,", "tempfile, copy import dicom, json, re from signal import SIGTERM from dicom.filereader import", "Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip())", "keep the slice location (use the maximum values for all slice locations) currentSliceLocation", "self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w')", "(remove at the end) seriesLevelCheck = False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check']", "currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r') as f: data", "run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout", "Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError,", "a check to the program to make sure that the rules are ok", "and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this rule refers to #", "not fit here\" ok = False break if isinstance( v, (int, float) ):", "#os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid())", "to make sure that the rules are ok # we need to be", "dicom.read_file(response) except IOError: print(\"Could not find file:\", response) continue except InvalidDicomError: print(\"Not a", "except: pass if os.path.exists(fn3): with open(fn3, 'r') as f: data = json.load(f) if", "float)): #print \"v is : \", v, \" and v2 is: \", v2", "print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a simple test", "self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok = True for entry", "try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles']", "not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not", "if ruleornotrule in r: # find the rule with that ID findID =", "> 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed:", "the pid file exits - but the process is not running (crashed). try:", "if isinstance(v, (int, float)): #print \"v is : \", v, \" and v2", "as f: self.classify_rules = json.load(f) # we should resolve dependencies between rules, this", "should override this method when you subclass Daemon. It will be called after", "= pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX double-fork magic,", "== 1: if not tag[0] in data: if not tag[0] in dataset: taghere", "= False break if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel):", "any of the images in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType']", "this pattern failed, fail the whole type and continue with the next ok", "new types as they are found (this will create all type that map", "in classifyTypes if y != t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe)", "\"\"\" import sys, os, time, atexit, stat, tempfile, copy import dicom, json, re", "for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule", "data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime']", "daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast using a daemon process that", "if pid > 0: # exit from second parent sys.exit(0) except OSError, e:", "a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM)", "simple test send a DICOM directory by:\" print \" find <dicomdir> -type f", "rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the", "os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path \", fn, \" did", "exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return # not an error in", "# find the rule with that ID findID = False for rule2 in", "= False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown", "print str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start() def", "image in the series (remove at the end) seriesLevelCheck = False if ('check'", "add the negate flag to this rule for i in cr: i['negate'] =", "(t in classifyTypes): classifyTypes = [y for y in classifyTypes if y !=", "pipe in /tmp/.processSingleFile # Hauke, July 2015 if __name__ == \"__main__\": pidfilename =", "if 'start' == sys.argv[1]: try: daemon.start() except: print \"Error: could not create processing", "test:\" print \" python2.7 %s test\" % sys.argv[0] print \"\" print \"Usage: %s", "rule with ID %s\" % r[ruleornotrule] continue if not didChange: break return classify_rules", "e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard", "data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate']", "= r['value'] taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2", "print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a", "ValueError: pass elif op == \">\": try: if isnegate(not float(v2) < float(v)): ok", "resolveClassifyRules(self, classify_rules ): # add recursively rules back until no more changes can", "set(classifyTypes)) if seriesLevelCheck and not ok and (t in classifyTypes): classifyTypes = [y", "= None try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r')", "the series level all rules have to be true for every image in", "r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\"", "sys.stderr.write(\"fork #2 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file", "def start(self): \"\"\" Start the daemon \"\"\" # Check for a pidfile to", "self.stdout = stdout self.stderr = stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def", "taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with", "if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err)", "= str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass", "Daemon: \"\"\" A generic daemon class. Usage: subclass the Daemon class and override", "ok = False break elif op == \"==\": try: if isnegate(not float(v2) ==", "v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2 == False: v2", "try: daemon.start() except: print \"Error: could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1)", "sys.argv[0] print \"\" print \"For a simple test send a DICOM directory by:\"", "'Error: could not open named pipe for reading commands' sys.exit(1) while True: response", "# open a named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd", "subclass the Daemon class and override the run() method \"\"\" def __init__(self, pidfile,", "range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit here\" ok =", "= stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the", "os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't do anything because the file", "float(v)): ok = False break except ValueError: pass elif op == \"!=\": try:", "series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {}", "daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif", "in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) +", "be able to reference a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else:", "sys.exit(0) else: print \"Process DICOM files fast using a daemon process that creates", "dataset[tag[0]] else: v = data[tag[0]] elif len(tag) == 2: if not ( int(tag[0],0),", "= file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid:", "rule here def isnegate(x): return x if ('negate' in r) and (r['negate'] ==", "The process does not exist, forget the pid and wait to be restarted..", "and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg +", "else: ok = False break # ok nobody failed, this is it if", "the named pipe in /tmp/.processSingleFile # Hauke, July 2015 if __name__ == \"__main__\":", "os.symlink(response, fn2) #else: # continue # don't do anything because the file exists", "%s' % self.pipename pass try: rp = open(self.pipename, 'r') except OSError: print 'Error:", "\"v is : \", v, \" and v2 is: \", v2 vstring =", "a DICOM file, extracts the header information and creates a Study/Series symbolic link", "command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0)", "if taghere2 == False: v2 = r['value'] if not \"operator\" in r: r[\"operator\"]", "or a tag (array of string length 2) or a specific index into", "and override the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin", "exist, forget the pid and wait to be restarted.. pid = None os.remove(self.pidfile)", "except: pass try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except:", "descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se =", "dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag with unknown structure, should be 1, 2,", "is: \", v2 vstring = str(v) if isnegate(not pattern.search(vstring)): # this pattern failed,", "to this rule for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange =", "should be 1, 2, or 3 entries in array\") return taghere, v def", "rule for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if", "symbolic links.\" print \"Use 'start' to start the daemon in the background. Send", "# check each numerical entry if its close to a specific value approxLevel", "except ValueError: v2 = r['value'] if taghere2 == False: v2 = r['value'] if", "sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test'", "# do second fork try: pid = os.fork() if pid > 0: #", "try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try:", "json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3:", "string length 2) or a specific index into a tag (array of string", "from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError:", "pass # keep the slice location (use the maximum values for all slice", "as they are found (this will create all type that map to any", "for a pidfile to see if the daemon already runs try: pf =", "for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have a negated", "# don't do anything because the file exists already # lets store some", "until no more changes can be done for attempt in range(100): didChange =", "pass try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except: pass", "== sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r", "os.kill(pid, 0) except OSError: # The process does not exist, forget the pid", "(int, float) )): # we get this if there is no value in", "= dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] =", "isnegate(x): return not x # check if this regular expression matches the current", "if op == \"notexist\": if isnegate(tagthere): ok = False break elif op ==", "don't do anything because the file exists already # lets store some data", "\"Error: could not find a rule with ID %s\" % r[ruleornotrule] continue if", "would allow for relative comparisons in the classification v2 = r['value'] taghere2 =", "if isinstance( v, list ) and isinstance(v2, list) and len(v) == len(v2): for", "t = self.classify_rules[rule]['type'] # if we check on the series level all rules", "response = rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response)", "pf.close() except IOError: pid = None if pid: message = \"pidfile %s already", "return # not an error in a restart # Try killing the daemon", "range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule = \"rule\" if", "dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3:", "= None if not pid: message = \"pidfile %s does not exist. Daemon", "== \"!=\": try: if isnegate(not float(v2) != float(v)): ok = False break except", "print \"\" print \"For a simple test send a DICOM directory by:\" print", "= os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer", "process is not running (crashed). try: os.kill(pid, 0) except OSError: # The process", "= \"pidfile %s does not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return", "store some data in a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID)", "locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with", "except OSError: # The process does not exist, forget the pid and wait", "creating the named pipe %s' % self.pipename pass try: rp = open(self.pipename, 'r')", "in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error:", "add new types as they are found (this will create all type that", "elif op == \"regexp\": pattern = re.compile(v2) vstring = v if isinstance(v, (int,", "# check if this regular expression matches the current type t taghere =", "should resolve dependencies between rules, this could introduce a problem with termination, #", "seriesLevelCheck = True ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry]", "sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For", "os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer'] = dataset.Manufacturer except:", "You should override this method when you subclass Daemon. It will be called", "sure that the rules are ok # we need to be able to", "break elif op == \"regexp\": pattern = re.compile(v2) vstring = v if isinstance(v,", "not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: #", "map to any of the images in the series) data['ClassifyType'] = self.classify(dataset, data,", "= dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] =", "commands' sys.exit(1) while True: response = rp.readline()[:-1] if not response: time.sleep(0.1) continue else:", "be called after the process has been daemonized by start() or restart(). \"\"\"", "r[ruleornotrule]: # found the id this rule refers to # copy the rules", "if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this", "try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try:", "\"notrule\" if ruleornotrule in r: # find the rule with that ID findID", "= dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] =", "start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a simple test send a DICOM", "some data in a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) +", "if isnegate(not float(v2) == float(v)): ok = False break except ValueError: pass elif", "fail in this case ok = False break if isinstance( v, list )", "#os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" %", "except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except:", "def daemonize(self): \"\"\" do the UNIX double-fork magic, see Stevens' \"Advanced Programming in", "data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing']", "pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass", "value in v, fail in this case ok = False break if isinstance(", "\"\"\" Stop the daemon \"\"\" # Get the pid from the pidfile try:", "the .pid file for the daemon # the second is the named pipe", "r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok = False break elif op", "daemon in the background. Send file names for processing using 'send'.\" print \"Test", "= json.load(f) if currentSliceLocation != None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] =", "in %s, ClassifyType tag will be empty\" % self.rulesFile return classifyTypes for rule", "see Stevens' \"Advanced Programming in the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16", "= file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(),", "range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r)", "= str(v) if isnegate(not pattern.search(vstring)): # this pattern failed, fail the whole type", "except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except:", "sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does not exist\\n\") sys.exit(1) def stop(self):", "this could introduce a problem with termination, # Todo: add a check to", "time, atexit, stat, tempfile, copy import dicom, json, re from signal import SIGTERM", "ok = False break elif op == \"regexp\": pattern = re.compile(v2) vstring =", "# continue # don't do anything because the file exists already # lets", "str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value)", "(%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si", "def isnegate(x): return x if ('negate' in r) and (r['negate'] == \"yes\"): def", "'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process DICOM files fast using a", "= self.classify_rules[rule]['rules'][entry] # we could have a negated rule here def isnegate(x): return", "approxLevel): #print \"approx does not fit here\" ok = False break if isinstance(", "float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType' in data: data['ClassifyType'] =", "data['NumFiles'] = str( int(data['NumFiles']) + 1 ) # add new types as they", "= dataset[tag[0]] else: v = data[tag[0]] elif len(tag) == 2: if not (", "recursively rules back until no more changes can be done for attempt in", "elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules", "# The process does not exist, forget the pid and wait to be", "not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif", "not findID: print \"Error: could not find a rule with ID %s\" %", "a pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r')", ") and isinstance(v2, list) and len(v) == len(v2): for i in range(len(v)): if", "\"\"\" # open a named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try:", "approxLevel = 1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not isinstance(v,", "False for rule2 in range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]:", "2: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else:", "\"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this rule", "# the second is the named pipe in /tmp/.processSingleFile # Hauke, July 2015", "- set(classifyTypes)) if seriesLevelCheck and not ok and (t in classifyTypes): classifyTypes =", "v2 = r['value'] if not \"operator\" in r: r[\"operator\"] = \"regexp\" # default", "%d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush()", "classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check on", "False break elif op == \"regexp\": pattern = re.compile(v2) vstring = v if", "did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else:", "(self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok = True for entry in range(len(self.classify_rules[rule]['rules'])):", "os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir):", "restart(). \"\"\" class ProcessSingleFile(Daemon): def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if", "all type that map to any of the images in the series) data['ClassifyType']", "v = '' taghere = True if len(tag) == 1: if not tag[0]", "err: err = str(err) if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile)", "os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path \", fn, \" did not", "entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read the classify rules", "data in a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\"", "pass try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass", "id this rule refers to # copy the rules and append instead of", "standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout, 'a+')", "is the .pid file for the daemon # the second is the named", "sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif", "reading commands' sys.exit(1) while True: response = rp.readline()[:-1] if not response: time.sleep(0.1) continue", "y in classifyTypes if y != t] return classifyTypes def run(self): try: os.mkfifo(self.pipename)", "except ValueError: pass elif op == \"!=\": try: if isnegate(not float(v2) != float(v)):", "\"yes\"): def isnegate(x): return not x # check if this regular expression matches", "= True if len(tag) == 1: if not tag[0] in data: if not", "the maximum values for all slice locations) currentSliceLocation = None try: currentSliceLocation =", "if isnegate(not float(v2) < float(v)): ok = False break except ValueError: pass elif", "1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find(\"No such", "return classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check", "pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid =", "float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else: ok =", "to see if the daemon already runs try: pf = file(self.pidfile,'r') pid =", "value can be a tag (array of string length 1) or a tag", "= os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't", "0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid > 0: # exit", "data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness']", "cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag to this rule", "the current type t taghere = True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except", "r = self.classify_rules[rule]['rules'][entry] # we could have a negated rule here def isnegate(x):", "= str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] =", "found the id this rule refers to # copy the rules and append", "v = dataset[tag[0]] else: v = data[tag[0]] elif len(tag) == 2: if not", "taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could in some", "ok = False break # ok nobody failed, this is it if ok:", "len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere =", "\"\"\" Send a message to the daemon via pipe \"\"\" # open a", "does not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return # not an", "== \"yes\"): def isnegate(x): return not x # check if this regular expression", "if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok =", "\"\"\" try: pid = os.fork() if pid > 0: # exit first parent", "(array of string length 2) or a specific index into a tag (array", "self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2 == False: v2 = r['value']", "= open(self.pipename, 'r') except OSError: print 'Error: could not open named pipe for", "have to be true for every image in the series (remove at the", "[] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str( int(data['NumFiles']) + 1 ) # add", "could in some cases be a tag, that would allow for relative comparisons", "break except ValueError: pass elif op == \"exist\": if isnegate(not tagthere): ok =", "= classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck and not ok and (t", "sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so", "#else: # continue # don't do anything because the file exists already #", "= False break except ValueError: pass elif op == \"exist\": if isnegate(not tagthere):", "taghere, v def classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules == 0:", "print \"Error: creating path \", fn, \" did not work\" fn2 = os.path.join(fn,", "elif op == \"<\": try: if isnegate(not float(v2) > float(v)): ok = False", "os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the named pipe %s' %", "dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID", "sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r,", "could be found\" def resolveClassifyRules(self, classify_rules ): # add recursively rules back until", "isinstance( v, (int, float) )): # we get this if there is no", "could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop()", "\"\"\" Restart the daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You should override", "data[tag[0]] elif len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0) ) in dataset:", "stdout self.stderr = stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\"", "elif op == \"==\": try: if isnegate(not float(v2) == float(v)): ok = False", "second fork try: pid = os.fork() if pid > 0: # exit from", "= classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule = \"rule\" if negate: ruleornotrule", "ValueError: continue # the 'value' could in some cases be a tag, that", "def restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You", "the background. Send file names for processing using 'send'.\" print \"Test the rules", "else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start()", "check to the program to make sure that the rules are ok #", "= str(err) if err.find(\"No such process\") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else:", "information and creates a Study/Series symbolic link structure. \"\"\" import sys, os, time,", "not exist, forget the pid and wait to be restarted.. pid = None", "not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't do anything because the", "\"\"\" Start the daemon \"\"\" # Check for a pidfile to see if", "redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout,", "for the daemon # the second is the named pipe in /tmp/.processSingleFile #", "pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except: pass", "= '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid'", "A generic daemon class. Usage: subclass the Daemon class and override the run()", "slice locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3):", "fn3 = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) + \".json\" data = {} try: data['Manufacturer'] =", "with open(fn3, 'r') as f: data = json.load(f) if currentSliceLocation != None: try:", "pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass", "message to the daemon via pipe \"\"\" # open a named pipe and", "the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err", "return taghere, v def classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules ==", "relative comparisons in the classification v2 = r['value'] taghere2 = True try: taghere2,", "len(sys.argv) == 2: if 'start' == sys.argv[1]: try: daemon.start() except: print \"Error: could", "pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r') pid", "tag[0] in data: if not tag[0] in dataset: taghere = False else: v", "not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else: v =", "process does not exist, forget the pid and wait to be restarted.. pid", "print 'OSERROR on creating the named pipe %s' % self.pipename pass try: rp", "os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn):", "r[\"operator\"] = \"regexp\" # default value op = r[\"operator\"] if op == \"notexist\":", "# keep the slice location (use the maximum values for all slice locations)", "3 entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read the classify", "pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except: pass try: data['ImageType'] = str(dataset[0x08,0x08].value) except: pass", "False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not (", "pid file exits - but the process is not running (crashed). try: os.kill(pid,", "a tag (array of string length 2) or a specific index into a", "and v2 is: \", v2 vstring = str(v) if isnegate(not pattern.search(vstring)): # this", "True if len(tag) == 1: if not tag[0] in data: if not tag[0]", "daemon.init() if len(sys.argv) == 2: if 'start' == sys.argv[1]: try: daemon.start() except: print", "fast using a daemon process that creates study/series directories with symbolic links.\" print", "pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except: pass def", "if its close to a specific value approxLevel = 1e-4 if 'approxLevel' in", "in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok = True for", "and append instead of the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr =", "pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message =", "could have a negated rule here def isnegate(x): return x if ('negate' in", "= None os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start the daemon') self.daemonize()", "be found\" def resolveClassifyRules(self, classify_rules ): # add recursively rules back until no", "range(len(classify_rules)): if \"id\" in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id", "daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]:", "pass if os.path.exists(fn3): with open(fn3, 'r') as f: data = json.load(f) if currentSliceLocation", "print(\"Could not find file:\", response) continue except InvalidDicomError: print(\"Not a DICOM file: \",", "2, or 3 entries in array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read", "in some cases be a tag, that would allow for relative comparisons in", "anything because the file exists already # lets store some data in a", "Study/Series symbolic link structure. \"\"\" import sys, os, time, atexit, stat, tempfile, copy", "elif op == \">\": try: if isnegate(not float(v2) < float(v)): ok = False", "break except ValueError: pass elif op == \"!=\": try: if isnegate(not float(v2) !=", "and (t in classifyTypes): classifyTypes = [y for y in classifyTypes if y", "int(tag[1],0)].value elif len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0) ) in dataset:", "try: data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try:", "sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1)", "\"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir()", "\"SeriesLevel\"): seriesLevelCheck = True ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r =", "in v): ok = False break elif op == \"approx\": # check each", "'/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if 'start' == sys.argv[1]:", "float(v2) > float(v)): ok = False break except ValueError: pass elif op ==", "float(v2) != float(v)): ok = False break except ValueError: pass elif op ==", "('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok = True", "def run(self): \"\"\" You should override this method when you subclass Daemon. It", "copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag to this rule for i", "try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r') as f:", "we could have a negated rule here def isnegate(x): return x if ('negate'", "= os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError,", "open(self.pipename, 'r') except OSError: print 'Error: could not open named pipe for reading", "we should resolve dependencies between rules, this could introduce a problem with termination,", "data = {} try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality", "= True ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] #", "dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic daemon class. Usage: subclass the", "does not fit here\" ok = False break if isinstance( v, (int, float)", "break except ValueError: pass elif op == \">\": try: if isnegate(not float(v2) <", "attempt in range(100): didChange = False for rule in range(len(classify_rules)): for entry in", "test send a DICOM directory by:\" print \" find <dicomdir> -type f -print", "v = data[tag[0]] elif len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0) )", "python \"\"\" Create a daemon process that listens to send messages and reads", "% self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does not exist\\n\")", "start the daemon') self.daemonize() print ' done' self.run() def send(self,arg): \"\"\" Send a", "the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin", "daemonize(self): \"\"\" do the UNIX double-fork magic, see Stevens' \"Advanced Programming in the", "file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message", "True ok = True for entry in range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we", "self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules", "#si = file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0)", "sys.exit(0) elif len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print", "Usage: subclass the Daemon class and override the run() method \"\"\" def __init__(self,", "False break except ValueError: pass elif op == \"!=\": try: if isnegate(not float(v2)", "str(dataset[0x08,0x08].value) except: pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value)", "to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start the daemon print('", "classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print \"Error: could not find a", "lets store some data in a series specific file fn3 = os.path.join(outdir, dataset.StudyInstanceUID,", "for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check on the", "= file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se = file(self.stderr, 'a+', 0) #os.dup2(si.fileno(),", "indir does not exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile", "False break # ok nobody failed, this is it if ok: classifyTypes =", "% sys.argv[0] print \"\" print \"For a simple test send a DICOM directory", "(int, float)): #print \"v is : \", v, \" and v2 is: \",", "while True: response = rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try: dataset", "the images in the series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType']", "a Study/Series symbolic link structure. \"\"\" import sys, os, time, atexit, stat, tempfile,", "dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise ValueError('Error: tag", "the rules and append instead of the reference rule findID = True classify_rules[rule]['rules'].remove(r)", "except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the slice location", "and not ok and (t in classifyTypes): classifyTypes = [y for y in", "except: pass try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except:", "pass try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except: pass", "daemon class. Usage: subclass the Daemon class and override the run() method \"\"\"", "e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid() os.umask(0) # do second", "True if not findID: print \"Error: could not find a rule with ID", "tag (array of string length 1) or a tag (array of string length", "into a tag (array of string length 3) v = '' taghere =", "all slice locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except: pass if", "os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\" self.stop()", "find the rule with that ID findID = False for rule2 in range(len(classify_rules)):", "to be able to reference a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules)", "Daemon class and override the run() method \"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null',", "0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f)", "daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0)", "link structure. \"\"\" import sys, os, time, atexit, stat, tempfile, copy import dicom,", "structure, should be 1, 2, or 3 entries in array') print(\"Error: tag with", "'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]:", "except: pass try: data['StudyDate'] = dataset.StudyDate except: pass try: data['StudyDescription'] = dataset.StudyDescription except:", "len(tag) == 1: if not tag[0] in data: if not tag[0] in dataset:", "pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass", "files that make this thing work, one is the .pid file for the", "didChange = True if not findID: print \"Error: could not find a rule", "is : \", v, \" and v2 is: \", v2 vstring = str(v)", "= 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules =", "and wait to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) # Start the", "ValueError: pass elif op == \"exist\": if isnegate(not tagthere): ok = False break", "json.load(f) # we should resolve dependencies between rules, this could introduce a problem", "{} try: data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except: pass", "sys.stderr.write(\"Error: the connection to the daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\"", "directories with symbolic links.\" print \"Use 'start' to start the daemon in the", "= os.fork() if pid > 0: # exit from second parent sys.exit(0) except", "if os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart the", "% self.pipename pass try: rp = open(self.pipename, 'r') except OSError: print 'Error: could", "= False break elif op == \"contains\": if isnegate(v2 not in v): ok", "tagthere): ok = False break elif op == \"contains\": if isnegate(v2 not in", "daemon \"\"\" # Check for a pidfile to see if the daemon already", "0) except OSError: # The process does not exist, forget the pid and", "found (this will create all type that map to any of the images", "str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass", "the daemon \"\"\" # Check for a pidfile to see if the daemon", "rules, this could introduce a problem with termination, # Todo: add a check", "self.pidfile) return # not an error in a restart # Try killing the", "to start the daemon in the background. Send file names for processing using", "= '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir =", "daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You should override this method when", "sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start() def run(self): \"\"\"", "the UNIX double-fork magic, see Stevens' \"Advanced Programming in the UNIX Environment\" for", "tag will be empty\" % self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t", "if seriesLevelCheck and not ok and (t in classifyTypes): classifyTypes = [y for", "%d (%s)\\n\" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir(\"/\") os.setsid()", "break elif op == \"contains\": if isnegate(v2 not in v): ok = False", "if not \"operator\" in r: r[\"operator\"] = \"regexp\" # default value op =", "rules and append instead of the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr", "pass try: data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass", "start(self): \"\"\" Start the daemon \"\"\" # Check for a pidfile to see", "are found (this will create all type that map to any of the", "flag to this rule for i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange", "try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType'", "# Start the daemon print(' start the daemon') self.daemonize() print ' done' self.run()", "index into a tag (array of string length 3) v = '' taghere", "data['Manufacturer'] = dataset.Manufacturer except: pass try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID']", "range(100): didChange = False for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r", "a value can be a tag (array of string length 1) or a", "pid > 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork", "pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if", "# copy the rules and append instead of the reference rule findID =", "run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on creating the named pipe", "the pid and wait to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1) #", "the daemon # the second is the named pipe in /tmp/.processSingleFile # Hauke,", "1) or a tag (array of string length 2) or a specific index", "\"Warning: no classify rules found in %s, ClassifyType tag will be empty\" %", "dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path", "Start the daemon \"\"\" # Check for a pidfile to see if the", "vstring = v if isinstance(v, (int, float)): #print \"v is : \", v,", "data['SliceSpacing'] = str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName']", "sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown", "Send file names for processing using 'send'.\" print \"Test the rules by running", "that listens to send messages and reads a DICOM file, extracts the header", "(array of string length 1) or a tag (array of string length 2)", "1: if not tag[0] in data: if not tag[0] in dataset: taghere =", "(not isinstance( v, (int, float) )): # we get this if there is", "is no value in v, fail in this case ok = False break", "tag[0] in dataset: taghere = False else: v = dataset[tag[0]] else: v =", "\"Use 'start' to start the daemon in the background. Send file names for", "+ list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There", "sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) == 3: if", "restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1)", "try: pid = os.fork() if pid > 0: # exit from second parent", "try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could in", "pass try: data['Modality'] = dataset.Modality except: pass try: data['StudyInstanceUID'] = dataset.StudyInstanceUID except: pass", "= self.classify_rules[rule]['type'] # if we check on the series level all rules have", "problem with termination, # Todo: add a check to the program to make", "== \"exist\": if isnegate(not tagthere): ok = False break elif op == \"contains\":", "except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except: pass try: data['StudyTime'] = str(dataset[0x08,0x30].value) except:", "data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() #", "str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try:", "in classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this rule refers", "not find file:\", response) continue except InvalidDicomError: print(\"Not a DICOM file: \", response)", "daemon.start() except: print \"Error: could not create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif", "taghere2 == False: v2 = r['value'] if not \"operator\" in r: r[\"operator\"] =", "str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try:", "in array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read the classify rules if", "no classify rules found in %s, ClassifyType tag will be empty\" % self.rulesFile", "daemon process that creates study/series directories with symbolic links.\" print \"Use 'start' to", "except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except:", "find file:\", response) continue except InvalidDicomError: print(\"Not a DICOM file: \", response) continue", "try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try:", "None try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r') as", ": \", v, \" and v2 is: \", v2 vstring = str(v) if", "if not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] =", "be true for every image in the series (remove at the end) seriesLevelCheck", "file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid:", "False if ('check' in self.classify_rules[rule]) and (self.classify_rules[rule]['check'] == \"SeriesLevel\"): seriesLevelCheck = True ok", "values for all slice locations) currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except:", "os.path.exists(self.pidfile): os.remove(self.pidfile) os.remove(self.pipename) else: print str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon", "rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check on the series", "ok = False break except ValueError: pass elif op == \"!=\": try: if", "classifyTypes if y != t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except", "data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType']))", "int(tag[1],0) ) in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else:", "% sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print", "the slice location (use the maximum values for all slice locations) currentSliceLocation =", "\"Process DICOM files fast using a daemon process that creates study/series directories with", "add a check to the program to make sure that the rules are", "not in v): ok = False break elif op == \"approx\": # check", "need to be able to reference a specific rule (id tag?) self.classify_rules =", "by running test:\" print \" python2.7 %s test\" % sys.argv[0] print \"\" print", "do the UNIX double-fork magic, see Stevens' \"Advanced Programming in the UNIX Environment\"", "ok = False break except ValueError: pass elif op == \"exist\": if isnegate(not", "if negate: # add the negate flag to this rule for i in", "ok = False break if isinstance( v, list ) and isinstance(v2, list) and", "subclass Daemon. It will be called after the process has been daemonized by", "os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename = tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init()", "sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se = file(self.stderr,", "file could be found\" def resolveClassifyRules(self, classify_rules ): # add recursively rules back", "in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule = \"rule\"", "should be 1, 2, or 3 entries in array') print(\"Error: tag with unknown", "the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: #", "data['RepetitionTime'] = str(dataset.RepetitionTime) except: pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber']", "unknown structure, should be 1, 2, or 3 entries in array') print(\"Error: tag", "daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError:", "pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon does", "2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not", "# not an error in a restart # Try killing the daemon process", "json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that make this thing work, one", "symbolic link structure. \"\"\" import sys, os, time, atexit, stat, tempfile, copy import", "ruleornotrule = \"notrule\" if ruleornotrule in r: # find the rule with that", "specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file", "json, re from signal import SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\"", "!= t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR", "not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\" # Get the", "t] return classifyTypes def run(self): try: os.mkfifo(self.pipename) atexit.register(self.delpipe) except OSError: print 'OSERROR on", "\"\"\" self.stop() self.start() def run(self): \"\"\" You should override this method when you", "pass elif op == \"exist\": if isnegate(not tagthere): ok = False break elif", "'value' could in some cases be a tag, that would allow for relative", "str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value)", "try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try:", "the daemon does not exist\\n\") sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\"", "x # check if this regular expression matches the current type t taghere", "= '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we", "pass def start(self): \"\"\" Start the daemon \"\"\" # Check for a pidfile", "= r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok = False break elif", "of the reference rule findID = True classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate:", "entry in range(len(classify_rules[rule]['rules'])): r = classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule =", "if len(sys.argv) == 2: if 'start' == sys.argv[1]: try: daemon.start() except: print \"Error:", "False: v2 = r['value'] if not \"operator\" in r: r[\"operator\"] = \"regexp\" #", "> float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType' in data: data['ClassifyType']", "\"\" print \"Usage: %s start|stop|restart|send|test\" % sys.argv[0] print \"\" print \"For a simple", "the next ok = False break elif op == \"==\": try: if isnegate(not", "# Todo: add a check to the program to make sure that the", "data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep", "named pipe in /tmp/.processSingleFile # Hauke, July 2015 if __name__ == \"__main__\": pidfilename", "is it if ok: classifyTypes = classifyTypes + list(set([t]) - set(classifyTypes)) if seriesLevelCheck", "or a specific index into a tag (array of string length 3) v", "\"Warning: no /data/code/bin/classifyRules.json file could be found\" def resolveClassifyRules(self, classify_rules ): # add", "try: if isnegate(not float(v2) != float(v)): ok = False break except ValueError: pass", "def resolveClassifyRules(self, classify_rules ): # add recursively rules back until no more changes", "3: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False else:", "self.start() def run(self): \"\"\" You should override this method when you subclass Daemon.", "the process has been daemonized by start() or restart(). \"\"\" class ProcessSingleFile(Daemon): def", "= json.load(f) # we should resolve dependencies between rules, this could introduce a", "def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except: pass def", "if isnegate(not float(v2) != float(v)): ok = False break except ValueError: pass elif", "types as they are found (this will create all type that map to", "daemon print(' start the daemon') self.daemonize() print ' done' self.run() def send(self,arg): \"\"\"", "on creating the named pipe %s' % self.pipename pass try: rp = open(self.pipename,", "exits - but the process is not running (crashed). try: os.kill(pid, 0) except", "pass try: data['PatientID'] = dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except: pass", "reads a DICOM file, extracts the header information and creates a Study/Series symbolic", "try: data['SeriesInstanceUID'] = dataset.SeriesInstanceUID except: pass try: data['PatientID'] = dataset.PatientID except: pass try:", "import SIGTERM from dicom.filereader import InvalidDicomError class Daemon: \"\"\" A generic daemon class.", "def delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start the daemon \"\"\"", "environment os.chdir(\"/\") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if", "value approxLevel = 1e-4 if 'approxLevel' in r: approxLevel = float(r['approxLevel']) if (not", "\"Test the rules by running test:\" print \" python2.7 %s test\" % sys.argv[0]", ") in dataset: taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value[int(tag[2],0)] else: raise", "length 1) or a tag (array of string length 2) or a specific", "data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber']", "\"\"\" do the UNIX double-fork magic, see Stevens' \"Advanced Programming in the UNIX", "= str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] =", "to send messages and reads a DICOM file, extracts the header information and", "Restart the daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You should override this", "rules have to be true for every image in the series (remove at", "an error in a restart # Try killing the daemon process try: while", "numerical entry if its close to a specific value approxLevel = 1e-4 if", "pid: message = \"pidfile %s does not exist. Daemon not running?\\n\" sys.stderr.write(message %", "> float(v)): ok = False break except ValueError: pass elif op == \">\":", "# if we check on the series level all rules have to be", "v, \" and v2 is: \", v2 vstring = str(v) if isnegate(not pattern.search(vstring)):", "true for every image in the series (remove at the end) seriesLevelCheck =", "isnegate(not float(v2) == float(v)): ok = False break except ValueError: pass elif op", "currentSliceLocation = None try: currentSliceLocation = data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3,", "\"approx\": # check each numerical entry if its close to a specific value", "int(data['NumFiles']) + 1 ) # add new types as they are found (this", "directory by:\" print \" find <dicomdir> -type f -print | grep -v .json", "file for the daemon # the second is the named pipe in /tmp/.processSingleFile", "float(v)): ok = False break except ValueError: pass elif op == \">\": try:", "<dicomdir> -type f -print | grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\"", "classify_rules[rule]['rules'].remove(r) cr = copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag to this", "pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except", ".pid file for the daemon # the second is the named pipe in", "pass elif op == \"<\": try: if isnegate(not float(v2) > float(v)): ok =", "outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir,", "else: v = data[tag[0]] elif len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0)", "not running (crashed). try: os.kill(pid, 0) except OSError: # The process does not", "taghere = True if len(tag) == 1: if not tag[0] in data: if", "a simple test send a DICOM directory by:\" print \" find <dicomdir> -type", "the daemon in the background. Send file names for processing using 'send'.\" print", "0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed:", "open named pipe for reading commands' sys.exit(1) while True: response = rp.readline()[:-1] if", "\"pidfile %s does not exist. Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return #", "rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except IOError:", "series) data['ClassifyType'] = self.classify(dataset, data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) -", "float(v2) == float(v)): ok = False break except ValueError: pass elif op ==", "if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close()", "find a rule with ID %s\" % r[ruleornotrule] continue if not didChange: break", "op == \"exist\": if isnegate(not tagthere): ok = False break elif op ==", "fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print", "they are found (this will create all type that map to any of", "= True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if", "except: pass def start(self): \"\"\" Start the daemon \"\"\" # Check for a", "= str(dataset[0x18,0x88].value) except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] =", "0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d", "if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we should resolve", "OSError: print 'OSERROR on creating the named pipe %s' % self.pipename pass try:", "= False break except ValueError: pass elif op == \"!=\": try: if isnegate(not", "first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" % (e.errno,", "= dicom.read_file(response) except IOError: print(\"Could not find file:\", response) continue except InvalidDicomError: print(\"Not", "classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this rule refers to # copy", "__name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p = os.path.abspath(pidfilename) if not os.path.exists(p): pidfilename", "can be done for attempt in range(100): didChange = False for rule in", "except: pass try: data['ScanningSequence'] = str(dataset[0x18,0x20].value) except: pass try: data['PulseSequenceName'] = str(dataset[0x19,0x109c].value) except:", "ok = False break else: ok = False break # ok nobody failed,", "def send(self,arg): \"\"\" Send a message to the daemon via pipe \"\"\" #", "if pid > 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork", "init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as f:", "ok = False break except ValueError: pass elif op == \"<\": try: if", "r[ruleornotrule] continue if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a value", "exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1 failed: %d (%s)\\n\" %", "daemon # the second is the named pipe in /tmp/.processSingleFile # Hauke, July", "if not os.path.exists(fn): os.makedirs(fn) if not os.path.exists(fn): print \"Error: creating path \", fn,", "open a named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd =", "classify_rules ): # add recursively rules back until no more changes can be", "start the daemon in the background. Send file names for processing using 'send'.\"", "print(\"Not a DICOM file: \", response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir):", "except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value) except:", "= open(self.pipename, 'w') wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print 'Error: could", "= r['value'] if taghere2 == False: v2 = r['value'] if not \"operator\" in", "= rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except", "print \"Use 'start' to start the daemon in the background. Send file names", "r: # find the rule with that ID findID = False for rule2", "len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not", "'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid", "%s\" % r[ruleornotrule] continue if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): #", "daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err =", "Todo: add a check to the program to make sure that the rules", "os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid >", "check on the series level all rules have to be true for every", "| grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\" >> /tmp/.processSingleFilePipe\" print \"\"", "\", fn, \" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2):", "sys, os, time, atexit, stat, tempfile, copy import dicom, json, re from signal", "a tag (array of string length 1) or a tag (array of string", "data['SliceLocation'] except: pass if os.path.exists(fn3): with open(fn3, 'r') as f: data = json.load(f)", "didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a value can be a tag", "with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close() # There are two files that make", "ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule in r: #", "= copy.deepcopy(classify_rules[rule2]['rules']) if negate: # add the negate flag to this rule for", "this if there is no value in v, fail in this case ok", "isnegate(tagthere): ok = False break elif op == \"regexp\": pattern = re.compile(v2) vstring", "pattern failed, fail the whole type and continue with the next ok =", "= \"regexp\" # default value op = r[\"operator\"] if op == \"notexist\": if", "try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if", "= stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile self.pipename =", "isinstance(v2, list) and len(v) == len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) >", "dependencies between rules, this could introduce a problem with termination, # Todo: add", "stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self): \"\"\" do the UNIX", "pass elif op == \"!=\": try: if isnegate(not float(v2) != float(v)): ok =", "# Hauke, July 2015 if __name__ == \"__main__\": pidfilename = '/data/.pids/processSingleFile.pid' p =", "\" did not work\" fn2 = os.path.join(fn, dataset.SOPInstanceUID) if not os.path.isfile(fn2): os.symlink(response, fn2)", "a DICOM file: \", response) continue indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error:", "if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType' in", "open(self.rulesFile,'r') as f: self.classify_rules = json.load(f) # we should resolve dependencies between rules,", "+ \"\\n\") wd.flush() wd.close() except IOError: print 'Error: could not open the pipe", "# add recursively rules back until no more changes can be done for", "= False break except ValueError: pass elif op == \">\": try: if isnegate(not", "= \"pidfile %s already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe", "override this method when you subclass Daemon. It will be called after the", "details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid > 0:", "os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start the daemon') self.daemonize() print '", "with ID %s\" % r[ruleornotrule] continue if not didChange: break return classify_rules def", "str( int(data['NumFiles']) + 1 ) # add new types as they are found", "- but the process is not running (crashed). try: os.kill(pid, 0) except OSError:", "len(v) == len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx", "already exist. Daemon already running?\\n\" sys.stderr.write(message % self.pidfile) # Maybe the pid file", "not pid: message = \"pidfile %s does not exist. Daemon not running?\\n\" sys.stderr.write(message", "# found the id this rule refers to # copy the rules and", "we check on the series level all rules have to be true for", "taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value']", "tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could be found\"", "classify_rules[rule2] and classify_rules[rule2]['id'] == r[ruleornotrule]: # found the id this rule refers to", "range(len(self.classify_rules[rule]['rules'])): r = self.classify_rules[rule]['rules'][entry] # we could have a negated rule here def", "be a tag, that would allow for relative comparisons in the classification v2", "= \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID: print \"Error: could not", "that would allow for relative comparisons in the classification v2 = r['value'] taghere2", "print \" find <dicomdir> -type f -print | grep -v .json | xargs", "to the daemon via pipe \"\"\" # open a named pipe and write", "wd.write(arg + \"\\n\") wd.flush() wd.close() except IOError: print 'Error: could not open the", "not response: time.sleep(0.1) continue else: try: dataset = dicom.read_file(response) except IOError: print(\"Could not", "< float(v)): ok = False break except ValueError: pass elif op == \"exist\":", "= str( int(data['NumFiles']) + 1 ) # add new types as they are", "can be a tag (array of string length 1) or a tag (array", ") print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv)", "pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the slice location (use", "fn2) #else: # continue # don't do anything because the file exists already", "isinstance( v, list ) and isinstance(v2, list) and len(v) == len(v2): for i", "InvalidDicomError class Daemon: \"\"\" A generic daemon class. Usage: subclass the Daemon class", "\"<\": try: if isnegate(not float(v2) > float(v)): ok = False break except ValueError:", "sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try", "could not find a rule with ID %s\" % r[ruleornotrule] continue if not", "os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID, dataset.SeriesInstanceUID) if not os.path.exists(fn): os.makedirs(fn)", "= \"rule\" if negate: ruleornotrule = \"notrule\" if ruleornotrule in r: # find", "a DICOM directory by:\" print \" find <dicomdir> -type f -print | grep", "print \" python2.7 %s test\" % sys.argv[0] print \"\" print \"Usage: %s start|stop|restart|send|test\"", "pid = os.fork() if pid > 0: # exit from second parent sys.exit(0)", "os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e:", "processing using 'send'.\" print \"Test the rules by running test:\" print \" python2.7", "True try: taghere, v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could", "print json.dumps(r, sort_keys=True, indent=2) else: print \"Unknown command\" sys.exit(2) sys.exit(0) elif len(sys.argv) ==", "exit from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d (%s)\\n\"", "v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if not ( int(tag[0],0), int(tag[1],0)", "pass try: data['SeriesNumber'] = str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass", "== 2: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere = False", "Daemon not running?\\n\" sys.stderr.write(message % self.pidfile) return # not an error in a", "taghere = False else: v = dataset[int(tag[0],0), int(tag[1],0)].value elif len(tag) == 3: if", "a message to the daemon via pipe \"\"\" # open a named pipe", "header information and creates a Study/Series symbolic link structure. \"\"\" import sys, os,", "try: dataset = dicom.read_file(response) except IOError: print(\"Could not find file:\", response) continue except", "classification v2 = r['value'] taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except", "array\") return taghere, v def classify(self,dataset,data,classifyTypes): # read the classify rules if self.classify_rules", "in r: r[\"operator\"] = \"regexp\" # default value op = r[\"operator\"] if op", "r) and (r['negate'] == \"yes\"): def isnegate(x): return not x # check if", "reference a specific rule (id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no", "ok = False break except ValueError: pass elif op == \">\": try: if", "except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039']", "sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() elif 'test' == sys.argv[1]: r =", "length 2) or a specific index into a tag (array of string length", "% (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si =", "data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime'] = str(dataset.EchoTime) except: pass try: data['RepetitionTime']", "not find a rule with ID %s\" % r[ruleornotrule] continue if not didChange:", "the rules by running test:\" print \" python2.7 %s test\" % sys.argv[0] print", "daemon.restart() elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True,", "no value in v, fail in this case ok = False break if", "file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so = file(self.stdout, 'a+') #se", "make this thing work, one is the .pid file for the daemon #", "in this case ok = False break if isinstance( v, list ) and", "try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass # keep the slice location (use the", "create processing daemon: \", sys.exc_info()[0] sys.exit(-1) elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart'", "try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except: pass try:", "print \"Error: could not find a rule with ID %s\" % r[ruleornotrule] continue", "classify_rules[rule]['rules'][entry] negate = (\"notrule\" in r) ruleornotrule = \"rule\" if negate: ruleornotrule =", "\"\"\" def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout", "OSError: # The process does not exist, forget the pid and wait to", "= tempfile.gettempdir() + '/processSingleFile.pid' daemon = ProcessSingleFile(pidfilename) daemon.init() if len(sys.argv) == 2: if", "elif len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0) ) in dataset: taghere", "Send a message to the daemon via pipe \"\"\" # open a named", "pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] =", "in the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid =", "here\" ok = False break if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2))", "i in cr: i['negate'] = \"yes\" classify_rules[rule]['rules'].extend(cr) didChange = True if not findID:", "sys.exit(1) def stop(self): \"\"\" Stop the daemon \"\"\" # Get the pid from", "data, data['ClassifyType']) #data['ClassifyType'] = data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as", "in the series (remove at the end) seriesLevelCheck = False if ('check' in", "\"exist\": if isnegate(not tagthere): ok = False break elif op == \"contains\": if", "stop(self): \"\"\" Stop the daemon \"\"\" # Get the pid from the pidfile", "Programming in the UNIX Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid", "restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start() def run(self): \"\"\" You should", "indir = '/data/scratch/archive/' if not os.path.exists(indir): print(\"Error: indir does not exist\") continue outdir", "IOError: print 'Error: could not open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename)", "import dicom, json, re from signal import SIGTERM from dicom.filereader import InvalidDicomError class", "str(err) sys.exit(1) def restart(self): \"\"\" Restart the daemon \"\"\" self.stop() self.start() def run(self):", "It will be called after the process has been daemonized by start() or", "str(dataset.SeriesNumber) except: pass try: data['InstanceNumber'] = str(dataset.InstanceNumber) except: pass try: data['SliceThickness'] = str(dataset[0x18,0x50].value)", "the rule with that ID findID = False for rule2 in range(len(classify_rules)): if", "float(v)): ok = False break except ValueError: pass elif op == \"exist\": if", "pid > 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #1", "elif 'test' == sys.argv[1]: r = daemon.resolveClassifyRules( daemon.classify_rules ) print json.dumps(r, sort_keys=True, indent=2)", "forget the pid and wait to be restarted.. pid = None os.remove(self.pidfile) sys.exit(1)", "but the process is not running (crashed). try: os.kill(pid, 0) except OSError: #", "could not open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection", "= '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn = os.path.join(outdir, dataset.StudyInstanceUID,", "does not exist\") continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile =", "if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print \"approx does not fit here\" ok = False", "the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error: the connection to the daemon", "= data[tag[0]] elif len(tag) == 2: if not ( int(tag[0],0), int(tag[1],0) ) in", "if os.path.exists(fn3): with open(fn3, 'r') as f: data = json.load(f) if currentSliceLocation !=", "v = self.resolveValue(r['tag'],dataset,data) except ValueError: continue # the 'value' could in some cases", "classify rules found in %s, ClassifyType tag will be empty\" % self.rulesFile return", "list) and len(v) == len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel):", "if not os.path.exists(fn): print \"Error: creating path \", fn, \" did not work\"", "IOError: pid = None if pid: message = \"pidfile %s already exist. Daemon", "op == \"regexp\": pattern = re.compile(v2) vstring = v if isinstance(v, (int, float)):", "# exit from second parent sys.exit(0) except OSError, e: sys.stderr.write(\"fork #2 failed: %d", "False break if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok", "grep -v .json | xargs -i echo \\\"/path/to/input/{}\\\" >> /tmp/.processSingleFilePipe\" print \"\" sys.exit(2)", "sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\"", "int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = \"pidfile", "sys.exit(1) while True: response = rp.readline()[:-1] if not response: time.sleep(0.1) continue else: try:", "data['StudyTime'] = str(dataset[0x08,0x30].value) except: pass data['NumFiles'] = str(0) try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except:", "not didChange: break return classify_rules def resolveValue(self,tag,dataset,data): # a value can be a", "file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename)", "be done for attempt in range(100): didChange = False for rule in range(len(classify_rules)):", "= str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile) except: pass def delpipe(self):", "and len(v) == len(v2): for i in range(len(v)): if isnegate(abs(float(v[i])-float(v2[i])) > approxLevel): #print", "v, fail in this case ok = False break if isinstance( v, list", "dataset.PatientID except: pass try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate", "the whole type and continue with the next ok = False break elif", "if not os.path.isfile(fn2): os.symlink(response, fn2) #else: # continue # don't do anything because", "in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we check on the series level", "method when you subclass Daemon. It will be called after the process has", "continue with the next ok = False break elif op == \"==\": try:", "#!/Usr/bin/env python \"\"\" Create a daemon process that listens to send messages and", "class. Usage: subclass the Daemon class and override the run() method \"\"\" def", "try: data['Private0019_10BB'] = str(dataset[0x0019,0x10BB].value) except: pass try: data['Private0043_1039'] = dataset[0x0043,0x1039].value except: pass #", "# redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() #si = file(self.stdin, 'r') #so =", "elif len(sys.argv) == 3: if 'send' == sys.argv[1]: daemon.send(sys.argv[2]) sys.exit(0) else: print \"Process", "stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile", "to # copy the rules and append instead of the reference rule findID", "vstring = str(v) if isnegate(not pattern.search(vstring)): # this pattern failed, fail the whole", "ID %s\" % r[ruleornotrule] continue if not didChange: break return classify_rules def resolveValue(self,tag,dataset,data):", "with that ID findID = False for rule2 in range(len(classify_rules)): if \"id\" in", "no more changes can be done for attempt in range(100): didChange = False", "file, extracts the header information and creates a Study/Series symbolic link structure. \"\"\"", "import InvalidDicomError class Daemon: \"\"\" A generic daemon class. Usage: subclass the Daemon", "False break except ValueError: pass elif op == \">\": try: if isnegate(not float(v2)", "find <dicomdir> -type f -print | grep -v .json | xargs -i echo", "= stdout self.stderr = stderr self.pidfile = pidfile self.pipename = '/tmp/.processSingleFilePipe' def daemonize(self):", "didChange = False for rule in range(len(classify_rules)): for entry in range(len(classify_rules[rule]['rules'])): r =", "OSError: print 'Error: could not open named pipe for reading commands' sys.exit(1) while", "#print \"v is : \", v, \" and v2 is: \", v2 vstring", "extracts the header information and creates a Study/Series symbolic link structure. \"\"\" import", "os.remove(self.pidfile) except: pass def delpipe(self): try: os.remove(self.pipename) except: pass def start(self): \"\"\" Start", "sys.stderr.write(message % self.pidfile) # Maybe the pid file exits - but the process", "= data['ClassifyType'] + list(set(self.classify(dataset, data)) - set(data['ClassifyType'])) with open(fn3,'w') as f: json.dump(data,f,indent=2,sort_keys=True) rp.close()", "the classification v2 = r['value'] taghere2 = True try: taghere2, v2 = self.resolveValue(v2,dataset,data)", "print \"Process DICOM files fast using a daemon process that creates study/series directories", "some cases be a tag, that would allow for relative comparisons in the", "named pipe %s' % self.pipename pass try: rp = open(self.pipename, 'r') except OSError:", "break elif op == \"approx\": # check each numerical entry if its close", "in v, fail in this case ok = False break if isinstance( v,", "comparisons in the classification v2 = r['value'] taghere2 = True try: taghere2, v2", "except: pass # keep the slice location (use the maximum values for all", "(id tag?) self.classify_rules = self.resolveClassifyRules(self.classify_rules) else: print \"Warning: no /data/code/bin/classifyRules.json file could be", "False break elif op == \"contains\": if isnegate(v2 not in v): ok =", "Environment\" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 \"\"\" try: pid = os.fork() if pid", "self.rulesFile return classifyTypes for rule in range(len(self.classify_rules)): t = self.classify_rules[rule]['type'] # if we", "write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode): try: wd = open(self.pipename, 'w') wd.write(arg + \"\\n\")", "= dataset[0x0043,0x1039].value except: pass # keep the slice location (use the maximum values", "def init(self): self.classify_rules = 0 self.rulesFile = '/data/code/bin/classifyRules.json' if os.path.exists(self.rulesFile): with open(self.rulesFile,'r') as", "negated rule here def isnegate(x): return x if ('negate' in r) and (r['negate']", "found\" def resolveClassifyRules(self, classify_rules ): # add recursively rules back until no more", "tag (array of string length 3) v = '' taghere = True if", "elif op == \"contains\": if isnegate(v2 not in v): ok = False break", "data['SliceLocation'] = currentSliceLocation; except: pass if not 'ClassifyType' in data: data['ClassifyType'] = []", "except: pass try: data['PatientName'] = dataset.PatientName except: pass try: data['StudyDate'] = dataset.StudyDate except:", "None os.remove(self.pidfile) sys.exit(1) # Start the daemon print(' start the daemon') self.daemonize() print", "write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write(\"%s\\n\" % pid) def delpid(self): try: os.remove(self.pidfile)", "do anything because the file exists already # lets store some data in", "print 'Error: could not open the pipe %s' % self.pipename else: sys.stderr.write(self.pipename) sys.stderr.write(\"Error:", "data['StudyDescription'] = dataset.StudyDescription except: pass try: data['SeriesDescription'] = dataset.SeriesDescription except: pass try: data['EchoTime']", "except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] = str(dataset[0x08,0x50].value) except:", "def resolveValue(self,tag,dataset,data): # a value can be a tag (array of string length", "x if ('negate' in r) and (r['negate'] == \"yes\"): def isnegate(x): return not", "continue outdir = '/data/scratch/views/raw' if not os.path.exists(outdir): os.makedirs(outdir) infile = os.path.basename(response) fn =", "None: try: if float(data['SliceLocation']) > float(currentSliceLocation): data['SliceLocation'] = currentSliceLocation; except: pass if not", "break if isinstance( v, (int, float) ): if isnegate(abs(float(v)-float(v2)) > approxLevel): ok =", "classifyTypes = [y for y in classifyTypes if y != t] return classifyTypes", "send a DICOM directory by:\" print \" find <dicomdir> -type f -print |", "pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr", "\"For a simple test send a DICOM directory by:\" print \" find <dicomdir>", "default value op = r[\"operator\"] if op == \"notexist\": if isnegate(tagthere): ok =", "False break else: ok = False break # ok nobody failed, this is", "rule with that ID findID = False for rule2 in range(len(classify_rules)): if \"id\"", "True try: taghere2, v2 = self.resolveValue(v2,dataset,data) except ValueError: v2 = r['value'] if taghere2", "not 'ClassifyType' in data: data['ClassifyType'] = [] data['StudyInstanceUID'] = dataset.StudyInstanceUID data['NumFiles'] = str(", "= (\"notrule\" in r) ruleornotrule = \"rule\" if negate: ruleornotrule = \"notrule\" if", "\"contains\": if isnegate(v2 not in v): ok = False break elif op ==", "isnegate(abs(float(v)-float(v2)) > approxLevel): ok = False break else: ok = False break #", "def stop(self): \"\"\" Stop the daemon \"\"\" # Get the pid from the", "have a negated rule here def isnegate(x): return x if ('negate' in r)", "= str(dataset[0x19,0x109c].value) except: pass try: data['SliceLocation'] = str(dataset[0x20,0x1041].value) except: pass try: data['AccessionNumber'] =", "pipe \"\"\" # open a named pipe and write to it if stat.S_ISFIFO(os.stat(self.pipename).st_mode):", "termination, # Todo: add a check to the program to make sure that", "thing work, one is the .pid file for the daemon # the second", "= file(self.stderr, 'a+', 0) #os.dup2(si.fileno(), sys.stdin.fileno()) #os.dup2(so.fileno(), sys.stdout.fileno()) #os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile", "rules by running test:\" print \" python2.7 %s test\" % sys.argv[0] print \"\"" ]
[ "# Process only those entities existing in entity_id collection. eId = \"m.\" +", "{\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\"", "\"[**] Processed\", len( nDoc ), \"redirect entries in block\", requestId, \"in\", endTime -", "Processing\", directory ) files = os.listdir( fullDir ) # Get all files in", "text is the surface form. if len( surfaceForm ) > 128: # Skip", ") requests = [] if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests.", "etc. chunks = [] MAX_CHUNK_SIZE = 20 for directory in directories: fullDir =", "html import sys from . import Parser as P importlib.reload( P ) class", "by this non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't exist in the", "): \"\"\" Grab surface forms and link relationships from wikilinks in valid entity", "len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests(", "# Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments )", "Process remaining chunks of documents. endTotalTime = time.time() print( \"[!] Completed process in\",", "totalRequests, \"processed\" ) endTime = time.time() print( \"[!] Done after\", endTime - startTime,", ") if m is not None: isDisambiguation = True # We'll be processing", "REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\",", "seekByte ) # Read block of data. block = bz2File.read( count ) dData", ":param docs: List or chunk of document dictionaries to process: {id:int, title:str, lines:[str]}.", "): +1 } }, upsert=True ) ) totalRequests += 1 if len( requests", "surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"],", "the IDs of entities that current document points to, as long as current", "1 # Entity is referred to by this surface form one more time", "): print( \"[*] Processing\", directory ) files = os.listdir( fullDir ) # Get", "\"secs\" ) blockRequests = [] startTime = time.time() seekByte = newSeekByte # Add", "self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update collections in DB. chunks =", "isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of page IDs pointed to by", "forms and links from Wikilinks and Disambiguation pages -------\" ) startTotalTime = time.time()", "else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr )", ") # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. #", "to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last block. print( \"[*]\",", "# else: # print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr", "self, sfDocuments ): \"\"\" Update the NED dictionary of surface forms. :param sfDocuments:", "requests = [] BATCH_SIZE = 10000 totalRequests = 0 for to in toFrom:", "to another disambiguation page or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity )", "encoding=\"utf-8\" ) as indexFile: seekByte = -1 for lineNumber, line in enumerate( indexFile", "title and redirect titles from read block. lines = dData.split( \"\\n\" ) skipLine", "pages. We don't modify the ned_linking collection in this function since redirect pages", "= 0 for sfDoc in sfDocuments: if not sfDoc: continue # Skip empty", "int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection", "len( requests ) == BATCH_SIZE: # Send lots of update requests at once.", "= time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule", "P.Parser.__init__( self ) # Defining connections to collections for entity disambiguation. self._mNed_Dictionary =", "A list of dicts of the form {from:int, to: set{int, int, ..., int}}.", "block = bz2File.read( -1 ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append(", "Output dictionary. for line in lines: line = line.strip() if not line: #", "print( \"[!] Detected\", nEntities, \"entities in entity_id collection\" ) requests = [] #", "Reached the body of the page? skipLine = True # No need to", "toFrom.get( to ) is None: toFrom[to] = {} toFrom[to][fId] = True # Now,", "MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all requests in this", "import Pool from pymongo import MongoClient import pymongo from urllib.parse import unquote import", ").count() if n == 1: # One match? Then retrieve entity ID. record", "} ) if record: # Process only those entities existing in entity_id collection.", "for that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations have been dropped\"", "nDoc = {} # This dict stores the surface forms and their corresponding", "data from a block in multi-stream Wikipedia dump file. :param block: A tuple", "\"\"\" startTime = time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks )", "disambiguation pages differently than regular valid pages. surfaceForm = \"\" isDisambiguation = False", "the form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool = Pool() rChunks", "= time.time() directories = os.listdir( extractedDir ) # Get directories of the form", "DB that the referenced real-world entity exists in entity_id collection. # Skip links", "output dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get(", "\"[*]\", totalRequests, \"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) #", "= time.time() print( \"[**] Processed\", len( nDoc ), \"redirect entries in block\", requestId,", "): \"\"\" Parse inter-Wikilinks from an entity page or disambiguation page to obtain", "\"------- Creating surface forms and links from Wikilinks and Disambiguation pages -------\" )", "(i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of", "}, { \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests += 1 if len(", "update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" ) requests = []", "\"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\" ) requests =", "empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\"", "Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" )", "\"\\n\" ) skipLine = False # To avoid unnecessary checks. title = None", "entries in block\", requestId, \"in\", endTime - startTime ) return nDoc def initDBCollections(", "def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED dictionary of surface forms.", "string block of data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,...,", "of tuples with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "\"... Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet } )", "doc[\"from\"] ) # --> from 12 to \"f.12\". for to in doc[\"to\"]: if", "\"\"\" Parse inter-Wikilinks from an entity page or disambiguation page to obtain surface", "form {from:int, to: set{int, int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" )", "\"doesn't exist in the DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm,", "= {} # This dict stores the surface forms and their corresponding entity", "NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if m: entity = m.group( 1", ") elif n > 1: # If more than one record, then Wikilink", "entity_id collection\" ) requests = [] # We'll use bulk writes to speed", "lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" ) requests", "wait for work to finish. # Split rChunks' lists of tuples into surface", "True # Found what we wanted... skip the rest of the page. elif", "bytes to read from bz2 stream. bz2File.seek( seekByte ) # Read block of", "pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of document objects in its own", "isDisambiguation = True # We'll be processing a disambiguation page. surfaceForm = m.group(", "# One single connection to rule all requests in this block. mNED =", ") startTotalTime = time.time() startTime = time.time() blockRequests = [] # Accumulate blocks", "redirect pages are only aliases for entity pages. :param msIndexFilePath: Multistream index file", "in link: we may have ALGOL and Algol... n = mEntity_ID.find( { \"e_l\":", "components[0] ) # Find the next seek byte start that is different to", "path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print(", ").strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B", "record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( title ) is", "def initDBCollections( self ): \"\"\" Reset the DB collections to start afresh. \"\"\"", "requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining", "MAX_CHUNK_SIZE = 20 for directory in directories: fullDir = extractedDir + directory if", "# Read bz2 file and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" )", "another of the form {from:int, to: set{int, int, ..., int}}. \"\"\" mClient =", "name: case sensitive. record = mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True", "\"/\". \"\"\" print( \"------- Creating surface forms and links from Wikilinks and Disambiguation", "int( components[0] ) # Find the next seek byte start that is different", "importlib.reload( P ) class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream", "\"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) #", "record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True } ) elif", "line: # Skip empty lines. continue if line == \"</page>\": # End of", "in block\", requestId, \"in\", endTime - startTime ) return nDoc def initDBCollections( self", "= self._mEntity_ID.count() # Retrieve number of entities in DB. startTime = time.time() print(", "requests at once. self._mNed_Linking.bulk_write( requests ) requests = [] if requests: self._mNed_Linking.bulk_write( requests", "speed up process. BATCH_SIZE = 10000 totalRequests = 0 for t in self._mEntity_ID.find():", "line ) if m: title = m.group( 1 ).lower() # Now reading a", ") # Process remaining chunks of documents. endTotalTime = time.time() print( \"[!] Completed", "totalRequests, \"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process", "of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient", "= 0 nDoc[title][eId] += 1 # Entity is referred to by this surface", "if seekByte == -1: # First time reading seek byte from file. seekByte", "files, etc. Use this method for incremental analysis of extracted Wikipedia BZ2 files.", "# Defining connections to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str,", "what we wanted... skip the rest of the page. elif line.find( \"<text\", 0,", "blocks starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) blockRequests", "\"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) #", "surface form. else: m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if", "redirect pages. We don't modify the ned_linking collection in this function since redirect", "objects in its own thread. pool.close() pool.join() # Close pool and wait for", "Add documents to a chunk list in preparation for multiprocessing. chunks.append( documents )", "-- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}.", "# Creating entry in output dict. if nDoc.get( title ) is None: nDoc[title]", "We'll use bulk writes to speed up process. BATCH_SIZE = 10000 totalRequests =", "eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity is", "e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile = fullDir + \"/\" +", "f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames( self ): \"\"\"", "= dData.split( \"\\n\" ) skipLine = False # To avoid unnecessary checks. title", "the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in", "{ \"_id\": int( to ) }, { \"$set\": toFrom[to] }, upsert=True ) )", "= fullDir + \"/\" + file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file", "= [] # We'll use bulk writes to speed up process. BATCH_SIZE =", "doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to] = {} toFrom[to][fId] = True", "== BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\",", "newSeekByte = int( components[0] ) # Find the next seek byte start that", "document. else: print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr )", "+ str( t[\"_id\"] ): +1 } }, upsert=True ) ) totalRequests += 1", "current doc is a non-disambiguatio page. :param docs: List or chunk of document", "connections to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,...,", "Changed seek-byte? requestId += 1 count = newSeekByte - seekByte # Number of", "else: # print( \"[W] Skipping entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr", "\"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1 for lineNumber, line in enumerate(", "new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last block.", "A list of lists of extracted wiki documents of the form {id:int, title:str,", ":param requests: A list of tuples of the form (requestID, blockStringData) \"\"\" pool", "\"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\" ) requests", "here: use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms", "than regular valid pages. surfaceForm = \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match(", "from file. seekByte = newSeekByte continue if newSeekByte != seekByte: # Changed seek-byte?", "after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab", "chunk of document dictionaries to process: {id:int, title:str, lines:[str]}. :return: A list of", "sfDoc: continue # Skip empty sf dictionaries. for sf in sfDoc: # Iterate", "+ str( record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( surfaceForm", "= set() # Stores the IDs of pages pointed to by this non-disambiguation", "have been dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from", "of documents. endTotalTime = time.time() print( \"[!] Completed process in\", endTotalTime - startTotalTime,", "\"\"\" Grab the entity names from entity_id collection and insert their surface forms", "empty for a disambiguation page). # Treat disambiguation pages differently than regular valid", "1: # One match? Then retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\":", "and linking dicts. sfDocuments = [] linkDocuments = [] for chunk in rChunks:", "surface form one more time (i.e. increase count). # else: # print( \"[!]", "\"processed\" ) endTime = time.time() print( \"[!] Done after\", endTime - startTime, \"secs.\"", "Send lots of update requests at once. self._mNed_Linking.bulk_write( requests ) requests = []", "of tuples into surface form dicts and linking dicts. sfDocuments = [] linkDocuments", "pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block", "blocks starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime", "the lowercase version given in link: we may have ALGOL and Algol... n", "enumerate( indexFile ): # Read index line by line. components = line.strip().split( \":\"", "# Reached the body of the page? skipLine = True # No need", "self, chunks ): \"\"\" Extract wikilinks from regular and disambiguation pages, and write", "line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links to avoid false", "startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms from", "requests ) print( \"[*]\", totalRequests, \"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write(", "if toFrom.get( to ) is None: toFrom[to] = {} toFrom[to][fId] = True #", "valid entity pages. Skip processing disambiguation pages, lists, and Wikipedia templates, files, etc.", "line ) # Remove external links to avoid false positives. for matchTuple in", "empty sf dictionaries. for sf in sfDoc: # Iterate over surface forms in", "dictionary and the inter-links table. \"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\",", "self, requests ): \"\"\" Read surface forms from blocks of Wikipedia documents obtained", "is None: toFrom[to] = {} toFrom[to][fId] = True # Now, upsert ned_linking collection", "inter-Wikilinks from an entity page or disambiguation page to obtain surface forms (by", "if not line: # Skip empty lines. continue if line == \"</page>\": #", "# print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, { \"from\":", "print( \"[!] Done after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir", "Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {}", "is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity is referred to", "if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of page IDs pointed", "sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request tuple in its", "_extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from regular and disambiguation pages, and", "to by this non-disambiguation document (e.g. nSet is empty for a disambiguation page).", "newSeekByte # Add the last seek byte with count = -1 to read", "documents obtained from the BZ2 multi-stream dump file. :param requests: A list of", "\"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" )", "for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m", "from multiprocessing import Pool from pymongo import MongoClient import pymongo from urllib.parse import", "to obtain surface forms (by convention these will be lowercased). Also, collect the", "to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape(", "by this non-disambiguation document (e.g. nSet is empty for a disambiguation page). #", ") class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream archives to", "linking dicts. sfDocuments = [] linkDocuments = [] for chunk in rChunks: for", "\"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests += 1", "Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last", "# Find redirect title. if m: entity = m.group( 1 ) # Check", "entity_id collection. # Skip links to another disambiguation page or an invalid entity", "process for redirect surface forms in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests(", "dictionaries to process: {id:int, title:str, lines:[str]}. :return: A list of tuples with two", "links to another disambiguation page or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity", "computations have been dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks", ").decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new block to requests.", "false positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0]", "surface forms and links from Wikilinks and Disambiguation pages -------\" ) startTotalTime =", "self._mNed_Dictionary.drop() # Note that we don't drop the entity_id collection here: use the", "that the referenced real-world entity exists in entity_id collection. # Skip links to", "True # No need to continue checking for redirect until page ends in", "pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" + str( t[\"_id\"] ):", "to ) is None: toFrom[to] = {} toFrom[to][fId] = True # Now, upsert", "bz2File.read( count ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData)", "Wikipedia extracted and multistream archives to construct the surface forms dictionary and the", "one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of", "endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract", "as indexFile: seekByte = -1 for lineNumber, line in enumerate( indexFile ): #", "_TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def", "import MongoClient import pymongo from urllib.parse import unquote import html import sys from", "etc. Use this method for incremental analysis of extracted Wikipedia BZ2 files. :param", "{ \"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close() return result def _updateSurfaceFormsDictionary(", "referred to by this surface form one more time (i.e. increase count). if", "= block[0] dData = block[1] # Obtain the title and redirect titles from", ") # Each block request tuple in its own thread. pool.close() pool.join() #", "referenced real-world entity exists in entity_id collection. # Skip links to another disambiguation", "= mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n == 1: # One", "the form {from:int, to: set{int, int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking", ") > 128: # Skip too long of a surface form. continue #", "nSet } ) ) mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\"", "requests: A list of tuples of the form (requestID, blockStringData) \"\"\" pool =", "doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) #", "these will be lowercased). Also, collect the IDs of entities that current document", "import bz2 import os import time import re from multiprocessing import Pool from", "form. continue # Skip links to another disambiguation page or an invalid entity", "of data. block = bz2File.read( -1 ) dData = bz2.decompress( block ).decode( \"utf-8\"", "a surface form. continue # Skip links to another disambiguation page or an", "archives to construct the surface forms dictionary and the inter-links table. \"\"\" #", "titles from read block. lines = dData.split( \"\\n\" ) skipLine = False #", "byte start that is different to current (defines a block). if seekByte ==", "# Find the next seek byte start that is different to current (defines", "\"\"\" Read surface forms from blocks of Wikipedia documents obtained from the BZ2", "number of entities in DB. startTime = time.time() print( \"------- Creating surface forms", "(requestID, blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) #", "to invalid entity\", entity, file=sys.stderr ) skipLine = True # Found what we", "= html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" ->", "time import re from multiprocessing import Pool from pymongo import MongoClient import pymongo", "exist in the DB!\", file=sys.stderr ) # else: # print( \"[W] Skipping entry\",", "= [] for doc in docs: nDoc = {} # This dict stores", "may have ALGOL and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count()", "with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1 for lineNumber,", "disambiguation pages, anchor text is the surface form. if len( surfaceForm ) >", "in doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to] = {} toFrom[to][fId] =", "1 if len( requests ) == BATCH_SIZE: # Send lots of update requests", "invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity )", "collection... \", end=\"\" ) # Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True},", "\"redirect entries in block\", requestId, \"in\", endTime - startTime ) return nDoc def", "For non disambiguation pages, anchor text is the surface form. if len( surfaceForm", "pointed to by this non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't exist", "nDoc[title] = {} if nDoc[title].get( eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId]", "speed up process. BATCH_SIZE = 10000 totalRequests = 0 for sfDoc in sfDocuments:", "and wait for work to finish. # Split rChunks' lists of tuples into", "): # Read bz2 file and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\"", "mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for doc in docs: nDoc =", "Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\" Read", "(e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"-------", "= \"f.\" + str( doc[\"from\"] ) # --> from 12 to \"f.12\". for", "in DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining", "P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity ) is None: record =", "from a block in multi-stream Wikipedia dump file. :param block: A tuple containing", "skipLine = False title = None elif not skipLine: if not title: #", ") endTime = time.time() print( \"[**] Processed\", len( chunks ), \"chunks in\", endTime", ") is None: nDoc[title] = {} if nDoc[title].get( eId ) is None: nDoc[title][eId]", "for redirect until page ends in </page>. mClient.close() endTime = time.time() print( \"[**]", "in this function since redirect pages are only aliases for entity pages. :param", "\"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from regular and", "10000 totalRequests = 0 for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int(", "count = newSeekByte - seekByte # Number of bytes to read from bz2", "document (e.g. nSet is empty for a disambiguation page). # Treat disambiguation pages", "for chunk in rChunks: for doc in chunk: if doc[0]: sfDocuments.append( doc[0] )", "if nDoc.get( title ) is None: nDoc[title] = {} if nDoc[title].get( eId )", "Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections to collections for entity disambiguation.", "documents of the form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool =", "redirect surface forms in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests", "requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental", "of the page? skipLine = True # No need to continue checking for", "and P.Parser._FilenamePattern.match( file ): # Read bz2 file and process it. with bz2.open(", "multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open( msDumpFilePath, \"rb\" )", "Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr ) # print( \"[***]\",", "(i.e. increase count). # else: # print( \"[!] Entity\", entity, \"doesn't exist in", "else: # print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr )", "\"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\":", "msDumpFilePath ): \"\"\" Extract surface form from redirect pages. We don't modify the", "for to in doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to] = {}", "Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time() print(", "members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I )", "start that is different to current (defines a block). if seekByte == -1:", "}, projection={ \"_id\": True } ) elif n > 1: # If more", "Read index line by line. components = line.strip().split( \":\" ) # [ByteStart, DocID,", "self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from redirect pages. We don't", "a reference count. nSet = set() # Stores the IDs of pages pointed", "record[\"_id\"] ) # Keep track of page IDs pointed to by this non-disambiguation", "the BZ2 multi-stream dump file. :param requests: A list of tuples of the", "if line == \"</page>\": # End of document? skipLine = False title =", ") # One single connection to rule all docs' DB requests. mNED =", "indexFile: seekByte = -1 for lineNumber, line in enumerate( indexFile ): # Read", "analysis of extracted Wikipedia BZ2 files. :param extractedDir: Directory where the individual BZ2", "\"parsed after\", time.time() - startTime, \"secs\" ) blockRequests = [] startTime = time.time()", "lowercased). Also, collect the IDs of entities that current document points to, as", "open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1 for lineNumber, line", "bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1 for", "Processed\", len( nDoc ), \"redirect entries in block\", requestId, \"in\", endTime - startTime", "by line. components = line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte =", "non disambiguation pages, anchor text is the surface form. if len( surfaceForm )", "DB. # First check how many entities match the lowercase version given in", "_extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an entity page or disambiguation page", "if os.path.isdir( fullDir ): print( \"[*] Processing\", directory ) files = os.listdir( fullDir", "to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc", "one record, then Wikilink must match the true entity name: case sensitive. record", "parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms and link relationships from wikilinks", "is not None: isDisambiguation = True # We'll be processing a disambiguation page.", "starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) blockRequests =", "{} # Output dictionary. for line in lines: line = line.strip() if not", "pages pointed to by this non-disambiguation document (e.g. nSet is empty for a", "lists of tuples into surface form dicts and linking dicts. sfDocuments = []", "blockRequests = [] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId", "msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms", "BATCH_SIZE = 10000 totalRequests = 0 for t in self._mEntity_ID.find(): # Surface forms", "title = None elif not skipLine: if not title: # Find page title", "requests ) # Process remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime =", "# Treat disambiguation pages differently than regular valid pages. surfaceForm = \"\" isDisambiguation", ") def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from redirect", "will be lowercased). Also, collect the IDs of entities that current document points", ") is None and P.Parser._SkipTitlePattern.match( entity ) is None: record = None #", "pages, lists, and Wikipedia templates, files, etc. Use this method for incremental analysis", "the next seek byte start that is different to current (defines a block).", "str( record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( title )", "in multi-stream Wikipedia dump file. :param block: A tuple containing (requestId, string block", "# Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\"", "into surface form dicts and linking dicts. sfDocuments = [] linkDocuments = []", "IDs of entities that current document points to, as long as current doc", "bz2File.seek( seekByte ) # Read block of data. block = bz2File.read( -1 )", "use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations", "TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations have been", "form. if len( surfaceForm ) > 128: # Skip too long of a", "linkDocuments = [] for chunk in rChunks: for doc in chunk: if doc[0]:", "+= 1 count = newSeekByte - seekByte # Number of bytes to read", "\"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new block to requests. self._parseMSBZ2BlockRequests(", "# Skip links to another disambiguation page or an invalid entity page. if", "collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**] Processed\",", "the title and redirect titles from read block. lines = dData.split( \"\\n\" )", ") != -1: # Reached the body of the page? skipLine = True", ") == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update collections in", "= bz2File.read( count ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId,", "# Entity is referred to by this surface form one more time (i.e.", "continue # Skip links to another disambiguation page or an invalid entity page.", "\"e_l\": entity.lower() }, projection={ \"_id\": True } ) elif n > 1: #", "We'll be processing a disambiguation page. surfaceForm = m.group( 1 ).strip().lower() # This", "work to finish. # Split rChunks' lists of tuples into surface form dicts", "self ) # Defining connections to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"]", "for work to finish. # Split rChunks' lists of tuples into surface form", "msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path", "collection. eId = \"m.\" + str( record[\"_id\"] ) # Creating entry in output", "ned_linking collection with UpdateOne bulk writes. requests = [] BATCH_SIZE = 10000 totalRequests", "line == \"</page>\": # End of document? skipLine = False title = None", "forms dictionary and the inter-links table. \"\"\" # Static members. _TitlePattern = re.compile(", "_processMSBZ2Block( block ): \"\"\" Read and process data from a block in multi-stream", "ned_dictionary and ned_linking collections. :param chunks: A list of lists of extracted wiki", "# One match? Then retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower()", ") skipLine = True # Found what we wanted... skip the rest of", "- startTime ) return nDoc def initDBCollections( self ): \"\"\" Reset the DB", "requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" + str( t[\"_id\"]", "the referenced real-world entity exists in entity_id collection. # Skip links to another", "True } ) elif n > 1: # If more than one record,", "-1: # First time reading seek byte from file. seekByte = newSeekByte continue", ") and P.Parser._FilenamePattern.match( file ): # Read bz2 file and process it. with", "# Now, upsert ned_linking collection with UpdateOne bulk writes. requests = [] BATCH_SIZE", "against DB that the referenced real-world entity exists in entity_id collection. # Skip", "{} toFrom[to][fId] = True # Now, upsert ned_linking collection with UpdateOne bulk writes.", "}, upsert=True ) ) totalRequests += 1 if len( requests ) == BATCH_SIZE:", "page or disambiguation page to obtain surface forms (by convention these will be", "don't modify the ned_linking collection in this function since redirect pages are only", "tuples of the form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map(", "Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities, \"entities in entity_id collection\" )", "skipLine = False # To avoid unnecessary checks. title = None nDoc =", "where the individual BZ2 files are located: must end in \"/\". \"\"\" print(", "\"\"\" print( \"------- Creating surface forms from redirect pages -------\" ) startTotalTime =", "to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to ) }, { \"$set\":", "linkDocuments: fId = \"f.\" + str( doc[\"from\"] ) # --> from 12 to", "+ \"/\" + file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): #", "requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) #", "(requestId, dData) ) # Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) #", "block request tuple in its own thread. pool.close() pool.join() # Update ned_dictionary collection.", "f stands for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the entity names", "remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time() print( \"[!] Done", "lines: line = line.strip() if not line: # Skip empty lines. continue if", "dData = block[1] # Obtain the title and redirect titles from read block.", "Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet } ) )", "of Wikipedia documents obtained from the BZ2 multi-stream dump file. :param requests: A", "and P.Parser._SkipTitlePattern.match( entity ) is None: record = None # Sentinel for found", "convention these will be lowercased). Also, collect the IDs of entities that current", "entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append(", "&amp; W\" -> \"B & W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() #", "process. BATCH_SIZE = 10000 totalRequests = 0 for sfDoc in sfDocuments: if not", "MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update collections in DB. chunks", "entity page. if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity ) is", "page). # Treat disambiguation pages differently than regular valid pages. surfaceForm = \"\"", "for multiprocessing. chunks.append( documents ) if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks", "seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) blockRequests = [] startTime =", "index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2).", "and process data from a block in multi-stream Wikipedia dump file. :param block:", "bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False", "if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): # Read bz2 file and", "of update requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests", "import unquote import html import sys from . import Parser as P importlib.reload(", "# else: # print( \"[W] Skipping entry\", title, \"pointing to invalid entity\", entity,", "# Read block of data. block = bz2File.read( count ) dData = bz2.decompress(", "or disambiguation page to obtain surface forms (by convention these will be lowercased).", "disambiguation page). # Treat disambiguation pages differently than regular valid pages. surfaceForm =", "dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time()", "NEDParser._extractWikilinks, chunks ) # Each chunk of document objects in its own thread.", "\"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\" )", "entity ) is None: record = None # Sentinel for found entity in", "entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"],", "form AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE = 20 for directory", "[] for chunk in rChunks: for doc in chunk: if doc[0]: sfDocuments.append( doc[0]", "\"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) # else: #", "\"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the form {from:int, to: set{int,", "documents to a chunk list in preparation for multiprocessing. chunks.append( documents ) if", "def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms from blocks of Wikipedia", "Get all files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in", "sfDoc[sf] }, upsert=True ) ) totalRequests += 1 if len( requests ) ==", "bulk writes. requests = [] BATCH_SIZE = 10000 totalRequests = 0 for to", ") _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\" Constructor.", "block = bz2File.read( count ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append(", "referred to by this surface form one more time (i.e. increase count). #", "-> \"B &amp; W\" -> \"B & W\". if not isDisambiguation: surfaceForm =", "multistream archives to construct the surface forms dictionary and the inter-links table. \"\"\"", "): \"\"\" Update the NED dictionary of surface forms. :param sfDocuments: List of", "nDoc[title].get( eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity", "collections in DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks ) # Process", "matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0] ) ).strip() #", "= [] for chunk in rChunks: for doc in chunk: if doc[0]: sfDocuments.append(", "lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" + str(", "are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\"", "surface forms (by convention these will be lowercased). Also, collect the IDs of", "wikilinks within current disambiguation page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\",", "self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**] Processed\", len(", "stream. bz2File.seek( seekByte ) # Read block of data. block = bz2File.read( count", "entity exists in entity_id collection. # Skip links to another disambiguation page or", "the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations have", "-> \"B & W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non", "Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g.", ") requests = [] # We'll use bulk writes to speed up process.", ") files = os.listdir( fullDir ) # Get all files in current parsing", "been dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an", "surface forms from redirect pages -------\" ) startTotalTime = time.time() startTime = time.time()", "\"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime = time.time() print( \"[!] Completed", "we don't drop the entity_id collection here: use the TFIDFParser for that. self._mNed_Linking.drop()", "nSet is empty for a disambiguation page). # Treat disambiguation pages differently than", "\"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the form {from:int, to: set{int, int,", "time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk", ") ) mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the", "tuples with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...},", "count = -1 to read all until EOF. requestId += 1 bz2File.seek( seekByte", "an entity page or disambiguation page to obtain surface forms (by convention these", "= mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData = block[1] # Obtain", "valid pages. surfaceForm = \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] )", "re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self", "title:str, lines:[str]}. \"\"\" startTime = time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks,", "surface form dicts and linking dicts. sfDocuments = [] linkDocuments = [] for", "blocks of Wikipedia documents obtained from the BZ2 multi-stream dump file. :param requests:", "Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self,", "block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last block. print(", "Disambiguation pages -------\" ) startTotalTime = time.time() directories = os.listdir( extractedDir ) #", ") as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents", "t[\"e_l\"] }, { \"$inc\": { \"m.\" + str( t[\"_id\"] ): +1 } },", "need to continue checking for redirect until page ends in </page>. mClient.close() endTime", "seekByte == -1: # First time reading seek byte from file. seekByte =", "and ned_linking collections. :param chunks: A list of lists of extracted wiki documents", "page title first. m = NEDParser._TitlePattern.search( line ) if m: title = m.group(", "record = mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True } ) if", "self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\"", "start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't drop the entity_id collection", "docs: List or chunk of document dictionaries to process: {id:int, title:str, lines:[str]}. :return:", "for directory in directories: fullDir = extractedDir + directory if os.path.isdir( fullDir ):", "Grab surface forms and link relationships from wikilinks in valid entity pages. Skip", ") is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity is referred", "= time.time() seekByte = newSeekByte # Add the last seek byte with count", "int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule", "ned_linking collection. :param linkDocuments: A list of dicts of the form {from:int, to:", "entity_id collection. eId = \"m.\" + str( record[\"_id\"] ) # Creating entry in", "to ) }, { \"$set\": toFrom[to] }, upsert=True ) ) totalRequests += 1", "\"------- Creating surface forms from Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities,", "then Wikilink must match the true entity name: case sensitive. record = mEntity_ID.find_one(", "non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr", "that we don't drop the entity_id collection here: use the TFIDFParser for that.", "requests ) == BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests )", "# Skip empty sf dictionaries. for sf in sfDoc: # Iterate over surface", "def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an entity page or disambiguation", "Wikilink must match the true entity name: case sensitive. record = mEntity_ID.find_one( {", "page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove", "for line in lines: line = line.strip() if not line: # Skip empty", "linkDocuments.append( doc[1] ) # Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments )", "in files: fullFile = fullDir + \"/\" + file if os.path.isfile( fullFile )", "time.time() print( \"------- Creating surface forms from Wikipedia titles -------\" ) print( \"[!]", "1 ) # Check against DB that the referenced real-world entity exists in", ":param sfDocuments: List of (possibly empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,...,", "\"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add", "starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime =", "= bz2File.read( -1 ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId,", "for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open( msDumpFilePath, \"rb\"", "# Surface forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, {", "case sensitive. record = mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True }", "and disambiguation pages, and write results to ned_dictionary and ned_linking collections. :param chunks:", "reading seek byte from file. seekByte = newSeekByte continue if newSeekByte != seekByte:", "Remove external links to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line ):", "surface form. continue # Skip links to another disambiguation page or an invalid", "line in enumerate( indexFile ): # Read index line by line. components =", "Read surface forms from blocks of Wikipedia documents obtained from the BZ2 multi-stream", "page? skipLine = True # No need to continue checking for redirect until", "\"\"\" self._mNed_Dictionary.drop() # Note that we don't drop the entity_id collection here: use", "all wikilinks within current disambiguation page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub(", "= 0 for t in self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append(", "None: toFrom[to] = {} toFrom[to][fId] = True # Now, upsert ned_linking collection with", "thread. pool.close() pool.join() # Close pool and wait for work to finish. #", "t[\"_id\"] ): +1 } }, upsert=True ) ) totalRequests += 1 if len(", "docs ): \"\"\" Parse inter-Wikilinks from an entity page or disambiguation page to", "to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}.", "line.strip() if not line: # Skip empty lines. continue if line == \"</page>\":", "in enumerate( indexFile ): # Read index line by line. components = line.strip().split(", "\"in\", endTime - startTime ) return nDoc def initDBCollections( self ): \"\"\" Reset", "): \"\"\" Read and process data from a block in multi-stream Wikipedia dump", "print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time() print( \"[!] Done after\", endTime", "importlib import bz2 import os import time import re from multiprocessing import Pool", "totalRequests += 1 if len( requests ) == BATCH_SIZE: # Send lots of", ") @staticmethod def _processMSBZ2Block( block ): \"\"\" Read and process data from a", "up process. BATCH_SIZE = 10000 totalRequests = 0 for sfDoc in sfDocuments: if", "Wikilinks and Disambiguation pages -------\" ) startTotalTime = time.time() directories = os.listdir( extractedDir", "= 10000 totalRequests = 0 for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\":", "{ \"$inc\": { \"m.\" + str( t[\"_id\"] ): +1 } }, upsert=True )", "form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests )", "for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands", "time.time() blockRequests = [] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000", "== -1: # First time reading seek byte from file. seekByte = newSeekByte", "by this surface form one more time (i.e. increase count). if not isDisambiguation:", "avoid unnecessary checks. title = None nDoc = {} # Output dictionary. for", "BZ2 files are located: must end in \"/\". \"\"\" print( \"------- Creating surface", "sys from . import Parser as P importlib.reload( P ) class NEDParser( P.Parser", "time (i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track", "Collections for surface forms computations have been dropped\" ) @staticmethod def _extractWikilinks( docs", "and multistream archives to construct the surface forms dictionary and the inter-links table.", ") return nDoc def initDBCollections( self ): \"\"\" Reset the DB collections to", ") ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" ->", "the DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid", "Creating surface forms and links from Wikilinks and Disambiguation pages -------\" ) startTotalTime", "int}}. \"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\" ) # Conform input", "skip the rest of the page. elif line.find( \"<text\", 0, 6 ) !=", "is empty for a disambiguation page). # Treat disambiguation pages differently than regular", "# Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if", "sfDocuments ): \"\"\" Update the NED dictionary of surface forms. :param sfDocuments: List", "rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of document objects in", "self ): \"\"\" Reset the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() #", "doc in chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]:", "this non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't exist in the DB!\",", "= {} for doc in linkDocuments: fId = \"f.\" + str( doc[\"from\"] )", "pages are only aliases for entity pages. :param msIndexFilePath: Multistream index file path", "list of tuples of the form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments", "(requestId, dData) ) # Append new block to requests. if len( blockRequests )", "docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating", "disambiguation pages, lists, and Wikipedia templates, files, etc. Use this method for incremental", "Split rChunks' lists of tuples into surface form dicts and linking dicts. sfDocuments", "to current (defines a block). if seekByte == -1: # First time reading", "stands for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the entity names from", "= os.listdir( fullDir ) # Get all files in current parsing directory, e.g.", "connection to rule all requests in this block. mNED = mClient.ned mEntity_ID =", "print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"],", "\"rb\" ) as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte", "= None # Sentinel for found entity in DB. # First check how", "= self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking", "from . import Parser as P importlib.reload( P ) class NEDParser( P.Parser ):", "-------\" ) print( \"[!] Detected\", nEntities, \"entities in entity_id collection\" ) requests =", "entity mappings with a reference count. nSet = set() # Stores the IDs", "in docs: nDoc = {} # This dict stores the surface forms and", "nDoc ), \"redirect entries in block\", requestId, \"in\", endTime - startTime ) return", "file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\"", "Found what we wanted... skip the rest of the page. elif line.find( \"<text\",", "the surface form. if len( surfaceForm ) > 128: # Skip too long", "# Found what we wanted... skip the rest of the page. elif line.find(", "(requestId, string block of data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "# Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom =", ":param chunks: A list of lists of extracted wiki documents of the form", "disambiguation page. surfaceForm = m.group( 1 ).strip().lower() # This will become the common", "the surface forms dictionary and the inter-links table. \"\"\" # Static members. _TitlePattern", "only aliases for entity pages. :param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt).", "bz2 file and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File:", "byte with count = -1 to read all until EOF. requestId += 1", "forms and their corresponding entity mappings with a reference count. nSet = set()", "Read block of data. block = bz2File.read( -1 ) dData = bz2.decompress( block", ").lower() # Now reading a <page>. Make title a lowercase surface form. else:", "# Changed seek-byte? requestId += 1 count = newSeekByte - seekByte # Number", "# End of document? skipLine = False title = None elif not skipLine:", "how many entities match the lowercase version given in link: we may have", "byte from file. seekByte = newSeekByte continue if newSeekByte != seekByte: # Changed", "than one record, then Wikilink must match the true entity name: case sensitive.", ") # Find redirect title. if m: entity = m.group( 1 ) #", "BATCH_SIZE = 10000 totalRequests = 0 for to in toFrom: requests.append( pymongo.UpdateOne( {", "# Remove external links to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line", "nEntities, \"entities in entity_id collection\" ) requests = [] # We'll use bulk", "chunks ), \"chunks in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath,", "surfaceForm ) > 128: # Skip too long of a surface form. continue", ") ) totalRequests += 1 if len( requests ) == BATCH_SIZE: # Send", "-1 ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) )", "stores the surface forms and their corresponding entity mappings with a reference count.", "from urllib.parse import unquote import html import sys from . import Parser as", ") # One single connection to rule all requests in this block. mNED", "\"m.\" + str( t[\"_id\"] ): +1 } }, upsert=True ) ) totalRequests +=", "requestId += 1 count = newSeekByte - seekByte # Number of bytes to", "for redirect surface forms in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self,", "of data. block = bz2File.read( count ) dData = bz2.decompress( block ).decode( \"utf-8\"", "requestId += 1 bz2File.seek( seekByte ) # Read block of data. block =", ") # Defining connections to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] #", "startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to", "positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0] )", "= Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of document", "if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId )", "if record: # Process only those entities existing in entity_id collection. eId =", "this function since redirect pages are only aliases for entity pages. :param msIndexFilePath:", "pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ):", "Skip links to another disambiguation page or an invalid entity page. if P.Parser._DisambiguationPattern.match(", "requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print(", "in valid entity pages. Skip processing disambiguation pages, lists, and Wikipedia templates, files,", "sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link references to", "nDoc.get( title ) is None: nDoc[title] = {} if nDoc[title].get( eId ) is", "bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new block", "unquote import html import sys from . import Parser as P importlib.reload( P", "# Close pool and wait for work to finish. # Split rChunks' lists", "= NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if m: entity = m.group(", "surface form. if len( surfaceForm ) > 128: # Skip too long of", "nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity is referred to by this", "time.time() print( \"[!] Done after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self,", "= 0 nDoc[surfaceForm][eId] += 1 # Entity is referred to by this surface", "this surface form one more time (i.e. increase count). # else: # print(", "# Keep track of page IDs pointed to by this non-disambiguation document. else:", "endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks", "process data from a block in multi-stream Wikipedia dump file. :param block: A", "= {} toFrom[to][fId] = True # Now, upsert ned_linking collection with UpdateOne bulk", "entity_id collection here: use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for", "for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ), \"request blocks", "Read block of data. block = bz2File.read( count ) dData = bz2.decompress( block", "to speed up process. BATCH_SIZE = 10000 totalRequests = 0 for t in", ":param block: A tuple containing (requestId, string block of data). :return: A dictionary", "{from:int, to: set{int, int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking collection... \",", "# Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this", "document? skipLine = False title = None elif not skipLine: if not title:", "for sf in sfDoc: # Iterate over surface forms in current dict. requests.append(", "== BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests =", "+= 1 if len( requests ) == BATCH_SIZE: # Send lots of update", "to construct the surface forms dictionary and the inter-links table. \"\"\" # Static", "rest of the page. elif line.find( \"<text\", 0, 6 ) != -1: #", "dictionary of surface forms. :param sfDocuments: List of (possibly empty) surface form docs", "results to ned_dictionary and ned_linking collections. :param chunks: A list of lists of", "is different to current (defines a block). if seekByte == -1: # First", "ned_linking collections. :param chunks: A list of lists of extracted wiki documents of", "= None elif not skipLine: if not title: # Find page title first.", "sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link", "not title: # Find page title first. m = NEDParser._TitlePattern.search( line ) if", "directories = os.listdir( extractedDir ) # Get directories of the form AA, AB,", "mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True } ) elif n >", "form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the form {from:int,", "No need to continue checking for redirect until page ends in </page>. mClient.close()", "DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**]", "lines:[str]}. \"\"\" startTime = time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks", "= line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte = int( components[0] )", "totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link", "\"secs\" ) endTotalTime = time.time() print( \"[!] Completed process for redirect surface forms", "# No need to continue checking for redirect until page ends in </page>.", "long of a surface form. continue # Skip links to another disambiguation page", "skipLine: if not title: # Find page title first. m = NEDParser._TitlePattern.search( line", "more link references to the ned_linking collection. :param linkDocuments: A list of dicts", "\"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\" ) # Conform input to", ") skipLine = False # To avoid unnecessary checks. title = None nDoc", "entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands", "non-disambiguatio page. :param docs: List or chunk of document dictionaries to process: {id:int,", "is None and P.Parser._SkipTitlePattern.match( entity ) is None: record = None # Sentinel", "BATCH_SIZE = 10000 totalRequests = 0 for sfDoc in sfDocuments: if not sfDoc:", "if len( requests ) == BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write(", "forms and link relationships from wikilinks in valid entity pages. Skip processing disambiguation", "{id:int, title:str, lines:[str]}. :return: A list of tuples with two dicts: one of", "time.time() print( \"[**] Processed\", len( chunks ), \"chunks in\", endTime - startTime, \"secs\"", "1 bz2File.seek( seekByte ) # Read block of data. block = bz2File.read( -1", "toFrom[to] }, upsert=True ) ) totalRequests += 1 if len( requests ) ==", "{ \"e\": entity }, projection={ \"_id\": True } ) if record: # Process", "with open( msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" )", "to speed up process. BATCH_SIZE = 10000 totalRequests = 0 for sfDoc in", "block\", requestId, \"in\", endTime - startTime ) return nDoc def initDBCollections( self ):", "remaining chunks of documents. endTotalTime = time.time() print( \"[!] Completed process in\", endTotalTime", "{} if nDoc[title].get( eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1", "import sys from . import Parser as P importlib.reload( P ) class NEDParser(", ":param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file", "[] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0", "if not title: # Find page title first. m = NEDParser._TitlePattern.search( line )", "# First check how many entities match the lowercase version given in link:", "-1: # Reached the body of the page? skipLine = True # No", "None # Sentinel for found entity in DB. # First check how many", "-1 to read all until EOF. requestId += 1 bz2File.seek( seekByte ) #", ") endTotalTime = time.time() print( \"[!] Completed process for redirect surface forms in\",", "linkDocuments ): \"\"\" Add more link references to the ned_linking collection. :param linkDocuments:", "to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't drop the entity_id", "= MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all docs' DB", "Find the next seek byte start that is different to current (defines a", "Pool from pymongo import MongoClient import pymongo from urllib.parse import unquote import html", "One single connection to rule all docs' DB requests. mNED = mClient.ned mEntity_ID", "seek byte start that is different to current (defines a block). if seekByte", "extracted Wikipedia BZ2 files. :param extractedDir: Directory where the individual BZ2 files are", "forms in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\"", "m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. --", "re from multiprocessing import Pool from pymongo import MongoClient import pymongo from urllib.parse", "of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary", "- startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms", "Each chunk of document objects in its own thread. pool.close() pool.join() # Close", "more time (i.e. increase count). # else: # print( \"[!] Entity\", entity, \"doesn't", "names from entity_id collection and insert their surface forms in ned_dictionary. \"\"\" nEntities", "of the form AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE = 20", "extracted wiki documents of the form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time()", "fId = \"f.\" + str( doc[\"from\"] ) # --> from 12 to \"f.12\".", "...}, \\ and another of the form {from:int, to: set{int, int, ..., int}}.", "doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet }", "1 count = newSeekByte - seekByte # Number of bytes to read from", "P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream archives to construct the surface", "the inter-links table. \"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I )", "of tuples of the form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments =", "requests ) # Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\" )", "self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\",", "byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime = time.time() print(", "update requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests )", "multiprocessing. chunks.append( documents ) if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks )", "+ file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): # Read bz2", ") # Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom", "to by this surface form one more time (i.e. increase count). # else:", "len( blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed after\", time.time() -", "!= -1: # Reached the body of the page? skipLine = True #", "in its own thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments )", ":return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime", "page. surfaceForm = m.group( 1 ).strip().lower() # This will become the common surface", "block to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests", "# One single connection to rule all docs' DB requests. mNED = mClient.ned", "end=\"\" ) requests = [] # We'll use bulk writes to speed up", "None: record = None # Sentinel for found entity in DB. # First", "# We'll be processing a disambiguation page. surfaceForm = m.group( 1 ).strip().lower() #", "def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms and link relationships from", ") if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks", "writes. requests = [] BATCH_SIZE = 10000 totalRequests = 0 for to in", "process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2(", "toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to ) }, { \"$set\": toFrom[to] },", "= m.group( 1 ).strip().lower() # This will become the common surface name for", "{\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the form {from:int, to:", "regular and disambiguation pages, and write results to ned_dictionary and ned_linking collections. :param", "chunks ) # Each chunk of document objects in its own thread. pool.close()", "\"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not", "# --> from 12 to \"f.12\". for to in doc[\"to\"]: if toFrom.get( to", "Retrieve number of entities in DB. startTime = time.time() print( \"------- Creating surface", "surface forms computations have been dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\"", "write results to ned_dictionary and ned_linking collections. :param chunks: A list of lists", "self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" ) requests = [] if requests:", "method for incremental analysis of extracted Wikipedia BZ2 files. :param extractedDir: Directory where", ") # Get all files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for", "doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet", "single connection to rule all docs' DB requests. mNED = mClient.ned mEntity_ID =", "sensitive. record = mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True } )", "by this surface form one more time (i.e. increase count). # else: #", "\":\" ) # [ByteStart, DocID, DocTitle] newSeekByte = int( components[0] ) # Find", "mClient.close() endTime = time.time() print( \"[**] Processed\", len( nDoc ), \"redirect entries in", "at once. self._mNed_Linking.bulk_write( requests ) requests = [] if requests: self._mNed_Linking.bulk_write( requests )", "lineNumber, line in enumerate( indexFile ): # Read index line by line. components", "different to current (defines a block). if seekByte == -1: # First time", "MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all docs' DB requests.", "result = [] for doc in docs: nDoc = {} # This dict", "Iterate over surface forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf },", "a disambiguation page. surfaceForm = m.group( 1 ).strip().lower() # This will become the", "process in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\"", "for entity pages. :param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath:", "upsert ned_linking collection with UpdateOne bulk writes. requests = [] BATCH_SIZE = 10000", "first. m = NEDParser._TitlePattern.search( line ) if m: title = m.group( 1 ).lower()", "dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append", "NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream archives to construct the", "indexFile ): # Read index line by line. components = line.strip().split( \":\" )", "thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block(", "# First time reading seek byte from file. seekByte = newSeekByte continue if", "dictionary. for line in lines: line = line.strip() if not line: # Skip", "{id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool = Pool() rChunks = pool.map(", "# Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B &", "1 ).strip().lower() # This will become the common surface name for all wikilinks", "--> from 12 to \"f.12\". for to in doc[\"to\"]: if toFrom.get( to )", "dict. if nDoc.get( title ) is None: nDoc[title] = {} if nDoc[title].get( eId", "to a chunk list in preparation for multiprocessing. chunks.append( documents ) if len(", "Creating entry in output dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] =", "requests ) == BATCH_SIZE: # Send lots of update requests at once. self._mNed_Linking.bulk_write(", "} ) elif n > 1: # If more than one record, then", "to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for", "..., int}}. \"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\" ) # Conform", "msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1 for lineNumber, line in", "[] for doc in docs: nDoc = {} # This dict stores the", "of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" ) requests =", "{ \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests += 1 if len( requests", "P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links to avoid false positives. for", "Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B & W\".", "in the DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to", "the entity_id collection here: use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections", "Wikipedia dump file. :param block: A tuple containing (requestId, string block of data).", "= Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request tuple", "of the form {from:int, to: set{int, int, ..., int}}. \"\"\" mClient = MongoClient(", "\"e_l\": entity.lower() } ).count() if n == 1: # One match? Then retrieve", "chunks ) # Extract Wikilinks and update collections in DB. chunks = []", "Extract Wikilinks and update collections in DB. chunks = [] if chunks: self._extractAndProcessWikilinks(", "files. :param extractedDir: Directory where the individual BZ2 files are located: must end", ") # --> from 12 to \"f.12\". for to in doc[\"to\"]: if toFrom.get(", "surface name for all wikilinks within current disambiguation page. for line in doc[\"lines\"]:", "result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close() return", "os import time import re from multiprocessing import Pool from pymongo import MongoClient", "extractedDir ) # Get directories of the form AA, AB, AC, etc. chunks", "files = os.listdir( fullDir ) # Get all files in current parsing directory,", "lowercase version given in link: we may have ALGOL and Algol... n =", "entity = m.group( 1 ) # Check against DB that the referenced real-world", "avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote(", "collection in this function since redirect pages are only aliases for entity pages.", "title:str, lines:[str]}. :return: A list of tuples with two dicts: one of the", ") blockRequests = [] startTime = time.time() seekByte = newSeekByte # Add the", "remaining requests. print( \"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments", "match the lowercase version given in link: we may have ALGOL and Algol...", "two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and", "forms (by convention these will be lowercased). Also, collect the IDs of entities", "pool.close() pool.join() # Close pool and wait for work to finish. # Split", "- startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms", "this method for incremental analysis of extracted Wikipedia BZ2 files. :param extractedDir: Directory", "pages -------\" ) startTotalTime = time.time() directories = os.listdir( extractedDir ) # Get", "To avoid unnecessary checks. title = None nDoc = {} # Output dictionary.", ") result.append( ( nDoc, { \"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close()", "\"\"\" Parsing Wikipedia extracted and multistream archives to construct the surface forms dictionary", "\"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each block", "sfDoc in sfDocuments: if not sfDoc: continue # Skip empty sf dictionaries. for", "A list of tuples with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external", "def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from regular and disambiguation pages,", "process. BATCH_SIZE = 10000 totalRequests = 0 for t in self._mEntity_ID.find(): # Surface", "forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of entities in", "= time.time() startTime = time.time() blockRequests = [] # Accumulate blocks for multithreading", "self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] },", "file=sys.stderr ) # else: # print( \"[W] Skipping entry\", title, \"pointing to invalid", "urllib.parse import unquote import html import sys from . import Parser as P", "= line.strip() if not line: # Skip empty lines. continue if line ==", "startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form", "their corresponding entity mappings with a reference count. nSet = set() # Stores", "is referred to by this surface form one more time (i.e. increase count).", "containing (requestId, string block of data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,...,", ") def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link references to the", "# Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. # Update", "page or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is None and", "entity pages. Skip processing disambiguation pages, lists, and Wikipedia templates, files, etc. Use", "insert their surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number", "of extracted wiki documents of the form {id:int, title:str, lines:[str]}. \"\"\" startTime =", "blockRequests = [] startTime = time.time() seekByte = newSeekByte # Add the last", "= pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of document objects in its", "surfaceForm = \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m", "writes to speed up process. BATCH_SIZE = 10000 totalRequests = 0 for sfDoc", "docs: nDoc = {} # This dict stores the surface forms and their", "from regular and disambiguation pages, and write results to ned_dictionary and ned_linking collections.", ") self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**] Processed\", len( chunks ),", "in linkDocuments: fId = \"f.\" + str( doc[\"from\"] ) # --> from 12", "P ) class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream archives", "str( t[\"_id\"] ): +1 } }, upsert=True ) ) totalRequests += 1 if", "- seekByte # Number of bytes to read from bz2 stream. bz2File.seek( seekByte", "form. else: m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if m:", "entity }, projection={ \"_id\": True } ) if record: # Process only those", "format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments: fId", ") print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed", "of entities that current document points to, as long as current doc is", "__init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections to", "file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc,", "@staticmethod def _processMSBZ2Block( block ): \"\"\" Read and process data from a block", ") mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED", "page ends in </page>. mClient.close() endTime = time.time() print( \"[**] Processed\", len( nDoc", "in entity_id collection. eId = \"m.\" + str( record[\"_id\"] ) # Creating entry", "= P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None: isDisambiguation = True #", "in output dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {} if", "{ \"$set\": toFrom[to] }, upsert=True ) ) totalRequests += 1 if len( requests", "the last seek byte with count = -1 to read all until EOF.", "entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B & W\". if", "startTime = time.time() blockRequests = [] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT", "= matchTuple[1].lower() # For non disambiguation pages, anchor text is the surface form.", "mEntity_ID = mNED[\"entity_id\"] result = [] for doc in docs: nDoc = {}", "Creating entry in output dict. if nDoc.get( title ) is None: nDoc[title] =", "references to the ned_linking collection. :param linkDocuments: A list of dicts of the", "\"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of entities in DB. startTime =", "continue if newSeekByte != seekByte: # Changed seek-byte? requestId += 1 count =", "): entity = html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity name: e.g.", "Done after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\"", "if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity ) is None: record", "dData.split( \"\\n\" ) skipLine = False # To avoid unnecessary checks. title =", "\"\"\" Update the NED dictionary of surface forms. :param sfDocuments: List of (possibly", "r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ):", "\"to\": nSet } ) ) mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ):", "nDoc = {} # Output dictionary. for line in lines: line = line.strip()", "for file in files: fullFile = fullDir + \"/\" + file if os.path.isfile(", "from the BZ2 multi-stream dump file. :param requests: A list of tuples of", "long as current doc is a non-disambiguatio page. :param docs: List or chunk", "processing a disambiguation page. surfaceForm = m.group( 1 ).strip().lower() # This will become", "int( to ) }, { \"$set\": toFrom[to] }, upsert=True ) ) totalRequests +=", "from Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities, \"entities in entity_id collection\"", "not skipLine: if not title: # Find page title first. m = NEDParser._TitlePattern.search(", "as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte = -1", "collections. :param chunks: A list of lists of extracted wiki documents of the", "pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request tuple in its own thread.", "lots of update requests at once. self._mNed_Linking.bulk_write( requests ) requests = [] if", "mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True } ) if record: #", "title ) is None: nDoc[title] = {} if nDoc[title].get( eId ) is None:", "collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. --", "= mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for doc in docs: nDoc", "None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity is referred to by", "surfaceForm = m.group( 1 ).strip().lower() # This will become the common surface name", "with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\", "print( \"[!] Completed process for redirect surface forms in\", endTotalTime - startTotalTime, \"secs\"", "dicts and linking dicts. sfDocuments = [] linkDocuments = [] for chunk in", "\"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections to collections for entity", "str( record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( surfaceForm )", "\"\"\" Extract wikilinks from regular and disambiguation pages, and write results to ned_dictionary", "blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open( msDumpFilePath,", "# Append new block to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: #", "Creating surface forms from redirect pages -------\" ) startTotalTime = time.time() startTime =", "to invalid entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\"", "bulk writes to speed up process. BATCH_SIZE = 10000 totalRequests = 0 for", "must match the true entity name: case sensitive. record = mEntity_ID.find_one( { \"e\":", "encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add", "-------\" ) startTotalTime = time.time() directories = os.listdir( extractedDir ) # Get directories", ") # Read block of data. block = bz2File.read( -1 ) dData =", "list of tuples with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,...,", ". import Parser as P importlib.reload( P ) class NEDParser( P.Parser ): \"\"\"", "toFrom[to] = {} toFrom[to][fId] = True # Now, upsert ned_linking collection with UpdateOne", "information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime =", "\"m.\" + str( record[\"_id\"] ) # Creating entry in output dict. if nDoc.get(", "\"[!] Collections for surface forms computations have been dropped\" ) @staticmethod def _extractWikilinks(", "as P importlib.reload( P ) class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted", ") # Process remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time()", "- startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface", "and write results to ned_dictionary and ned_linking collections. :param chunks: A list of", "in self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"]", "fullFile ) and P.Parser._FilenamePattern.match( file ): # Read bz2 file and process it.", ") # Creating entry in output dict. if nDoc.get( title ) is None:", "doc[\"title\"] ) if m is not None: isDisambiguation = True # We'll be", "entity pages. :param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream", "chunk in rChunks: for doc in chunk: if doc[0]: sfDocuments.append( doc[0] ) #", "tuple in its own thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments", "at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime = time.time()", "m: title = m.group( 1 ).lower() # Now reading a <page>. Make title", "open( msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as", "1 ).lower() # Now reading a <page>. Make title a lowercase surface form.", "disambiguation page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) #", "# Find page title first. m = NEDParser._TitlePattern.search( line ) if m: title", "surfaceForm ) is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is None:", "= 1000 requestId = 0 with open( msDumpFilePath, \"rb\" ) as bz2File: with", "Number of bytes to read from bz2 stream. bz2File.seek( seekByte ) # Read", "= time.time() print( \"[!] Done after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks(", "only those entities existing in entity_id collection. eId = \"m.\" + str( record[\"_id\"]", "track of page IDs pointed to by this non-disambiguation document. else: print( \"[!]", "print( \"[!] Collections for surface forms computations have been dropped\" ) @staticmethod def", "in sfDoc: # Iterate over surface forms in current dict. requests.append( pymongo.UpdateOne( {", "skipLine = True # No need to continue checking for redirect until page", "[] if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print( \"Done with\",", ":return: A list of tuples with two dicts: one of the form {\"sf1\":{\"m.EID1\":int,...,", ") is None: record = None # Sentinel for found entity in DB.", "isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation pages, anchor text is the", "the form AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE = 20 for", "in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read", "common surface name for all wikilinks within current disambiguation page. for line in", "\"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true,", "entity.lower() } ).count() if n == 1: # One match? Then retrieve entity", "AA/wiki_00.bz2. files.sort() for file in files: fullFile = fullDir + \"/\" + file", "# Read index line by line. components = line.strip().split( \":\" ) # [ByteStart,", "set() # Stores the IDs of pages pointed to by this non-disambiguation document", "= [] BATCH_SIZE = 10000 totalRequests = 0 for to in toFrom: requests.append(", "== 1: # One match? Then retrieve entity ID. record = mEntity_ID.find_one( {", "its own thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod", "collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\" Read and process", "Directory where the individual BZ2 files are located: must end in \"/\". \"\"\"", "print( \"[*]\", totalRequests, \"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests )", "not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation pages, anchor text is", ") # Each chunk of document objects in its own thread. pool.close() pool.join()", "of update requests at once. self._mNed_Linking.bulk_write( requests ) requests = [] if requests:", "doc is a non-disambiguatio page. :param docs: List or chunk of document dictionaries", "\"mongodb://localhost:27017/\" ) # One single connection to rule all docs' DB requests. mNED", "blockRequests.append( (requestId, dData) ) # Append new block to requests. if len( blockRequests", "nDoc, { \"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close() return result def", "forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf]", "import importlib import bz2 import os import time import re from multiprocessing import", "m = NEDParser._TitlePattern.search( line ) if m: title = m.group( 1 ).lower() #", "the entity names from entity_id collection and insert their surface forms in ned_dictionary.", "nSet = set() # Stores the IDs of pages pointed to by this", "fullFile = fullDir + \"/\" + file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match(", "DocID, DocTitle] newSeekByte = int( components[0] ) # Find the next seek byte", "forms. :param sfDocuments: List of (possibly empty) surface form docs of the form", "\"\"\" Reset the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that", "in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\"", "time reading seek byte from file. seekByte = newSeekByte continue if newSeekByte !=", "= time.time() print( \"------- Creating surface forms from Wikipedia titles -------\" ) print(", "are only aliases for entity pages. :param msIndexFilePath: Multistream index file path (e.g.", "requests ): \"\"\" Read surface forms from blocks of Wikipedia documents obtained from", "once. self._mNed_Linking.bulk_write( requests ) requests = [] if requests: self._mNed_Linking.bulk_write( requests ) #", "requests ) # Each block request tuple in its own thread. pool.close() pool.join()", "{ \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" + str( t[\"_id\"] ): +1", "+ str( record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( title", "startTime, \"secs\" ) endTotalTime = time.time() print( \"[!] Completed process for redirect surface", "+= 1 # Entity is referred to by this surface form one more", "retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True", "chunks of documents. endTotalTime = time.time() print( \"[!] Completed process in\", endTotalTime -", "following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments:", "sf dictionaries. for sf in sfDoc: # Iterate over surface forms in current", "= time.time() print( \"[!] Completed process for redirect surface forms in\", endTotalTime -", "self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations have been dropped\" ) @staticmethod", "\"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed after\", time.time()", "current (defines a block). if seekByte == -1: # First time reading seek", "current disambiguation page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line )", "self ): \"\"\" Grab the entity names from entity_id collection and insert their", "requestId, \"in\", endTime - startTime ) return nDoc def initDBCollections( self ): \"\"\"", "found entity in DB. # First check how many entities match the lowercase", "block. print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed", "lists of extracted wiki documents of the form {id:int, title:str, lines:[str]}. \"\"\" startTime", "[] startTime = time.time() seekByte = newSeekByte # Add the last seek byte", "sfDocuments: if not sfDoc: continue # Skip empty sf dictionaries. for sf in", "is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity is referred to", "pages, and write results to ned_dictionary and ned_linking collections. :param chunks: A list", "read block. lines = dData.split( \"\\n\" ) skipLine = False # To avoid", "False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None: isDisambiguation =", "of (possibly empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests,", "to read from bz2 stream. bz2File.seek( seekByte ) # Read block of data.", "\"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One", "Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open(", "a non-disambiguatio page. :param docs: List or chunk of document dictionaries to process:", "{} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1", "entity names from entity_id collection and insert their surface forms in ned_dictionary. \"\"\"", "AC, etc. chunks = [] MAX_CHUNK_SIZE = 20 for directory in directories: fullDir", "1 if len( requests ) == BATCH_SIZE: # Send lots of update requests.", "# Note that we don't drop the entity_id collection here: use the TFIDFParser", "1000 requestId = 0 with open( msDumpFilePath, \"rb\" ) as bz2File: with open(", "requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests, \"requests", "startTotalTime = time.time() directories = os.listdir( extractedDir ) # Get directories of the", "self, extractedDir ): \"\"\" Grab surface forms and link relationships from wikilinks in", "# Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection(", "collection and insert their surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() #", "[] MAX_CHUNK_SIZE = 20 for directory in directories: fullDir = extractedDir + directory", "Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n == 1:", "rChunks: for doc in chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface forms.", "the ned_linking collection in this function since redirect pages are only aliases for", "0 for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to ) },", "inter-links table. \"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern", "\"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new block to requests. if", "html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B", "for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to ) }, {", "P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity", "if nDoc[title].get( eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 #", "ends in </page>. mClient.close() endTime = time.time() print( \"[**] Processed\", len( nDoc ),", "( nDoc, { \"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close() return result", "startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms and", "block ): \"\"\" Read and process data from a block in multi-stream Wikipedia", "= os.listdir( extractedDir ) # Get directories of the form AA, AB, AC,", "if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and", "set{int, int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\" )", "= extractedDir + directory if os.path.isdir( fullDir ): print( \"[*] Processing\", directory )", "\"_id\": True } ) elif n > 1: # If more than one", "Add the last seek byte with count = -1 to read all until", "afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't drop the entity_id collection here:", "in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links to", "record, then Wikilink must match the true entity name: case sensitive. record =", "= False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None: isDisambiguation", "\"from\": doc[\"id\"], \"to\": nSet } ) ) mClient.close() return result def _updateSurfaceFormsDictionary( self,", "One match? Then retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() },", "elif n > 1: # If more than one record, then Wikilink must", "requests ) requests = [] if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining", "page to obtain surface forms (by convention these will be lowercased). Also, collect", "forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": {", ") if m: title = m.group( 1 ).lower() # Now reading a <page>.", "\"B & W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation", "}, projection={ \"_id\": True } ) if record: # Process only those entities", "= P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links to avoid false positives.", "current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True", "if m: entity = m.group( 1 ) # Check against DB that the", "time.time() startTime = time.time() blockRequests = [] # Accumulate blocks for multithreading processing.", "the individual BZ2 files are located: must end in \"/\". \"\"\" print( \"-------", "time (i.e. increase count). # else: # print( \"[!] Entity\", entity, \"doesn't exist", "pages. surfaceForm = \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if", ") # Get directories of the form AA, AB, AC, etc. chunks =", "P importlib.reload( P ) class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and", "...} \"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single", "\"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests += 1 if len( requests )", "dump file. :param requests: A list of tuples of the form (requestID, blockStringData)", "import Parser as P importlib.reload( P ) class NEDParser( P.Parser ): \"\"\" Parsing", "name for all wikilinks within current disambiguation page. for line in doc[\"lines\"]: line", "nSet.add( record[\"_id\"] ) # Keep track of page IDs pointed to by this", "import pymongo from urllib.parse import unquote import html import sys from . import", "the form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests", "a block). if seekByte == -1: # First time reading seek byte from", "if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 #", ") is None: toFrom[to] = {} toFrom[to][fId] = True # Now, upsert ned_linking", "requests = [] # We'll use bulk writes to speed up process. BATCH_SIZE", "extracted and multistream archives to construct the surface forms dictionary and the inter-links", "= True # Now, upsert ned_linking collection with UpdateOne bulk writes. requests =", "from pymongo import MongoClient import pymongo from urllib.parse import unquote import html import", "msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from redirect pages. We don't modify", "= True # Found what we wanted... skip the rest of the page.", "become the common surface name for all wikilinks within current disambiguation page. for", ") as indexFile: seekByte = -1 for lineNumber, line in enumerate( indexFile ):", "pages, anchor text is the surface form. if len( surfaceForm ) > 128:", "endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface", "directory if os.path.isdir( fullDir ): print( \"[*] Processing\", directory ) files = os.listdir(", "print( \"------- Creating surface forms from redirect pages -------\" ) startTotalTime = time.time()", "time.time() print( \"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks(", ") # Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse", "block). if seekByte == -1: # First time reading seek byte from file.", "it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(),", ") # [ByteStart, DocID, DocTitle] newSeekByte = int( components[0] ) # Find the", "ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\" Read and", "line in lines: line = line.strip() if not line: # Skip empty lines.", "redirect until page ends in </page>. mClient.close() endTime = time.time() print( \"[**] Processed\",", "of data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}", "= False title = None elif not skipLine: if not title: # Find", "mNED[\"entity_id\"] result = [] for doc in docs: nDoc = {} # This", "in DB. startTime = time.time() print( \"------- Creating surface forms from Wikipedia titles", "def _processMSBZ2Block( block ): \"\"\" Read and process data from a block in", "data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\"", ") # Remove external links to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall(", ":param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface", "@staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an entity page or", "connection to rule all docs' DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"]", "Surface forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\":", "DocTitle] newSeekByte = int( components[0] ) # Find the next seek byte start", "more time (i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep", "Process only those entities existing in entity_id collection. eId = \"m.\" + str(", "ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True } )", "): \"\"\" Parsing Wikipedia extracted and multistream archives to construct the surface forms", "version given in link: we may have ALGOL and Algol... n = mEntity_ID.find(", "don't drop the entity_id collection here: use the TFIDFParser for that. self._mNed_Linking.drop() print(", "surface forms. :param sfDocuments: List of (possibly empty) surface form docs of the", "files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile", "= time.time() print( \"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\" ) def", "r\"\\3\", line ) # Remove external links to avoid false positives. for matchTuple", "in lines: line = line.strip() if not line: # Skip empty lines. continue", "import os import time import re from multiprocessing import Pool from pymongo import", "BZ2 multi-stream dump file. :param requests: A list of tuples of the form", "lines. continue if line == \"</page>\": # End of document? skipLine = False", "of a surface form. continue # Skip links to another disambiguation page or", "= False # To avoid unnecessary checks. title = None nDoc = {}", "128: # Skip too long of a surface form. continue # Skip links", "> 128: # Skip too long of a surface form. continue # Skip", "# Check against DB that the referenced real-world entity exists in entity_id collection.", "fullDir = extractedDir + directory if os.path.isdir( fullDir ): print( \"[*] Processing\", directory", "as long as current doc is a non-disambiguatio page. :param docs: List or", "block of data). :return: A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "Skip empty lines. continue if line == \"</page>\": # End of document? skipLine", "increase count). # else: # print( \"[!] Entity\", entity, \"doesn't exist in the", "dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True )", "next seek byte start that is different to current (defines a block). if", "time.time() seekByte = newSeekByte # Add the last seek byte with count =", "to by this non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't exist in", "): # Read index line by line. components = line.strip().split( \":\" ) #", "newSeekByte != seekByte: # Changed seek-byte? requestId += 1 count = newSeekByte -", "\"[W] Skipping entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr ) skipLine =", "= int( components[0] ) # Find the next seek byte start that is", "= 10000 totalRequests = 0 for sfDoc in sfDocuments: if not sfDoc: continue", "seekByte: # Changed seek-byte? requestId += 1 count = newSeekByte - seekByte #", "# Skip empty lines. continue if line == \"</page>\": # End of document?", "{_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames( self ):", "endTime = time.time() print( \"[!] Done after\", endTime - startTime, \"secs.\" ) def", "in </page>. mClient.close() endTime = time.time() print( \"[**] Processed\", len( nDoc ), \"redirect", "path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from redirect pages -------\"", "nDoc[surfaceForm][eId] += 1 # Entity is referred to by this surface form one", "file in files: fullFile = fullDir + \"/\" + file if os.path.isfile( fullFile", "chunk of document objects in its own thread. pool.close() pool.join() # Close pool", "in sfDocuments: if not sfDoc: continue # Skip empty sf dictionaries. for sf", "Skip too long of a surface form. continue # Skip links to another", "in directories: fullDir = extractedDir + directory if os.path.isdir( fullDir ): print( \"[*]", "be lowercased). Also, collect the IDs of entities that current document points to,", "read all until EOF. requestId += 1 bz2File.seek( seekByte ) # Read block", "+ str( doc[\"from\"] ) # --> from 12 to \"f.12\". for to in", "== MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update collections in DB.", ") == BATCH_SIZE: # Send lots of update requests at once. self._mNed_Linking.bulk_write( requests", "rule all requests in this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId", "line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links", "collect the IDs of entities that current document points to, as long as", "directory in directories: fullDir = extractedDir + directory if os.path.isdir( fullDir ): print(", "blockRequests ) # And parse this last block. print( \"[*]\", len( blockRequests ),", "Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests:", "AB, AC, etc. chunks = [] MAX_CHUNK_SIZE = 20 for directory in directories:", "10000 totalRequests = 0 for sfDoc in sfDocuments: if not sfDoc: continue #", "= [] startTime = time.time() seekByte = newSeekByte # Add the last seek", "forms computations have been dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\" Parse", "...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\" ) requests = []", "of the form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool = Pool()", "[] BATCH_SIZE = 10000 totalRequests = 0 for to in toFrom: requests.append( pymongo.UpdateOne(", ") def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms and link relationships", "not None: isDisambiguation = True # We'll be processing a disambiguation page. surfaceForm", "# Send lots of update requests at once. self._mNed_Linking.bulk_write( requests ) requests =", "file ): # Read bz2 file and process it. with bz2.open( fullFile, \"rt\",", "print( \"[*] Updating ned_dictionary collection... \", end=\"\" ) requests = [] # We'll", "if newSeekByte != seekByte: # Changed seek-byte? requestId += 1 count = newSeekByte", "\"e\": entity }, projection={ \"_id\": True } ) if record: # Process only", "self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.'", "dicts: one of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another", "True # Now, upsert ned_linking collection with UpdateOne bulk writes. requests = []", "for lineNumber, line in enumerate( indexFile ): # Read index line by line.", "from blocks of Wikipedia documents obtained from the BZ2 multi-stream dump file. :param", "in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of entities in DB.", "entity page or disambiguation page to obtain surface forms (by convention these will", "new block to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT", "surface form one more time (i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"]", "for incremental analysis of extracted Wikipedia BZ2 files. :param extractedDir: Directory where the", "that is different to current (defines a block). if seekByte == -1: #", "endTotalTime = time.time() print( \"[!] Completed process for redirect surface forms in\", endTotalTime", "startTime = time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) #", "of surface forms. :param sfDocuments: List of (possibly empty) surface form docs of", "redirect titles from read block. lines = dData.split( \"\\n\" ) skipLine = False", "links from Wikilinks and Disambiguation pages -------\" ) startTotalTime = time.time() directories =", "= [] MAX_CHUNK_SIZE = 20 for directory in directories: fullDir = extractedDir +", "0 nDoc[title][eId] += 1 # Entity is referred to by this surface form", "Read and process data from a block in multi-stream Wikipedia dump file. :param", ") def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from regular and disambiguation", "result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED dictionary of surface", "wikilinks from regular and disambiguation pages, and write results to ned_dictionary and ned_linking", "\"_id\": True } ) if record: # Process only those entities existing in", "skipLine = True # Found what we wanted... skip the rest of the", "continue # Skip empty sf dictionaries. for sf in sfDoc: # Iterate over", "(defines a block). if seekByte == -1: # First time reading seek byte", "re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\"", "self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.'", "a block in multi-stream Wikipedia dump file. :param block: A tuple containing (requestId,", "dicts. sfDocuments = [] linkDocuments = [] for chunk in rChunks: for doc", "files: fullFile = fullDir + \"/\" + file if os.path.isfile( fullFile ) and", "Read bz2 file and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as", "chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update collections", "UpdateOne bulk writes. requests = [] BATCH_SIZE = 10000 totalRequests = 0 for", "not line: # Skip empty lines. continue if line == \"</page>\": # End", "title = m.group( 1 ).lower() # Now reading a <page>. Make title a", ") print( \"[!] Detected\", nEntities, \"entities in entity_id collection\" ) requests = []", "last seek byte with count = -1 to read all until EOF. requestId", "DB. startTime = time.time() print( \"------- Creating surface forms from Wikipedia titles -------\"", "'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the entity names from entity_id collection", "after\", time.time() - startTime, \"secs\" ) endTotalTime = time.time() print( \"[!] Completed process", "for a disambiguation page). # Treat disambiguation pages differently than regular valid pages.", "Updating ned_dictionary collection... \", end=\"\" ) requests = [] # We'll use bulk", "body of the page? skipLine = True # No need to continue checking", "print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr ) #", "current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile = fullDir", "or chunk of document dictionaries to process: {id:int, title:str, lines:[str]}. :return: A list", "= newSeekByte # Add the last seek byte with count = -1 to", "and the inter-links table. \"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I", "NEDParser._processMSBZ2Block, requests ) # Each block request tuple in its own thread. pool.close()", "for doc in docs: nDoc = {} # This dict stores the surface", "pages differently than regular valid pages. surfaceForm = \"\" isDisambiguation = False m", "os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): # Read bz2 file and process", "file. :param block: A tuple containing (requestId, string block of data). :return: A", "an invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity", "those entities existing in entity_id collection. eId = \"m.\" + str( record[\"_id\"] )", "points to, as long as current doc is a non-disambiguatio page. :param docs:", "One single connection to rule all requests in this block. mNED = mClient.ned", "startTime, \"secs\" ) blockRequests = [] startTime = time.time() seekByte = newSeekByte #", "): \"\"\" Add more link references to the ned_linking collection. :param linkDocuments: A", "# Split rChunks' lists of tuples into surface form dicts and linking dicts.", "this surface form one more time (i.e. increase count). if not isDisambiguation: nSet.add(", ") # Creating entry in output dict. if nDoc.get( surfaceForm ) is None:", ") startTotalTime = time.time() directories = os.listdir( extractedDir ) # Get directories of", "_updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED dictionary of surface forms. :param", "= self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to a chunk list", "= 0 for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to )", "\"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks", "empty lines. continue if line == \"</page>\": # End of document? skipLine =", "if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation pages, anchor text", "surface forms in\", endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ):", "at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) blockRequests = []", "requests.append( pymongo.UpdateOne( { \"_id\": int( to ) }, { \"$set\": toFrom[to] }, upsert=True", "startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from regular", "update requests at once. self._mNed_Linking.bulk_write( requests ) requests = [] if requests: self._mNed_Linking.bulk_write(", "DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for doc", "request tuple in its own thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary(", "Find page title first. m = NEDParser._TitlePattern.search( line ) if m: title =", "1: # If more than one record, then Wikilink must match the true", "bz2File.read( -1 ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData)", "chunks ): \"\"\" Extract wikilinks from regular and disambiguation pages, and write results", "= m.group( 1 ).lower() # Now reading a <page>. Make title a lowercase", "true entity name: case sensitive. record = mEntity_ID.find_one( { \"e\": entity }, projection={", "from redirect pages -------\" ) startTotalTime = time.time() startTime = time.time() blockRequests =", "form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient = MongoClient(", "increase count). if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of page", "extractedDir ): \"\"\" Grab surface forms and link relationships from wikilinks in valid", "# Number of bytes to read from bz2 stream. bz2File.seek( seekByte ) #", "one more time (i.e. increase count). # else: # print( \"[!] Entity\", entity,", "the page? skipLine = True # No need to continue checking for redirect", "all until EOF. requestId += 1 bz2File.seek( seekByte ) # Read block of", "mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData = block[1] # Obtain the", "Completed process for redirect surface forms in\", endTotalTime - startTotalTime, \"secs\" ) def", "\"\"\" Add more link references to the ned_linking collection. :param linkDocuments: A list", "\"[!] Detected\", nEntities, \"entities in entity_id collection\" ) requests = [] # We'll", "{ \"e_l\": entity.lower() } ).count() if n == 1: # One match? Then", "ned_linking collection... \", end=\"\" ) # Conform input to the following format: {\"eId1\":{\"f.eId2\":True,", "is the surface form. if len( surfaceForm ) > 128: # Skip too", "# This will become the common surface name for all wikilinks within current", "# {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames( self", "# Creating entry in output dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm]", "# [ByteStart, DocID, DocTitle] newSeekByte = int( components[0] ) # Find the next", "and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n ==", "if m is not None: isDisambiguation = True # We'll be processing a", "entities match the lowercase version given in link: we may have ALGOL and", "\"\"\" print( \"------- Creating surface forms and links from Wikilinks and Disambiguation pages", "pool and wait for work to finish. # Split rChunks' lists of tuples", "} ) ) mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update", "Sentinel for found entity in DB. # First check how many entities match", "entity.lower() }, projection={ \"_id\": True } ) elif n > 1: # If", "_updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link references to the ned_linking collection.", "parse this last block. print( \"[*]\", len( blockRequests ), \"request blocks starting at", "t in self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append( pymongo.UpdateOne( { \"_id\":", "# Retrieve number of entities in DB. startTime = time.time() print( \"------- Creating", "print( \"[W] Skipping entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr ) skipLine", "NED dictionary of surface forms. :param sfDocuments: List of (possibly empty) surface form", "== BATCH_SIZE: # Send lots of update requests at once. self._mNed_Linking.bulk_write( requests )", "= NEDParser._TitlePattern.search( line ) if m: title = m.group( 1 ).lower() # Now", "surface forms and link relationships from wikilinks in valid entity pages. Skip processing", "name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B & W\". if not", "chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1]", "blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests", "if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests,", "bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to a", "First time reading seek byte from file. seekByte = newSeekByte continue if newSeekByte", "entity ) is None and P.Parser._SkipTitlePattern.match( entity ) is None: record = None", "links to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity =", "with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more", "): \"\"\" Extract surface form from redirect pages. We don't modify the ned_linking", "P.Parser._FilenamePattern.match( file ): # Read bz2 file and process it. with bz2.open( fullFile,", "{_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] #", "fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False )", ") blockRequests.append( (requestId, dData) ) # Append new block to requests. if len(", "20 for directory in directories: fullDir = extractedDir + directory if os.path.isdir( fullDir", "None: isDisambiguation = True # We'll be processing a disambiguation page. surfaceForm =", "Wikipedia documents obtained from the BZ2 multi-stream dump file. :param requests: A list", "totalRequests = 0 for to in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to", "entry in output dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {}", "Note that we don't drop the entity_id collection here: use the TFIDFParser for", "a chunk list in preparation for multiprocessing. chunks.append( documents ) if len( chunks", "_RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\" Constructor. \"\"\"", "endTotalTime = time.time() print( \"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\" )", "[] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"Done with\",", "in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0] ) ).strip() # Clean", "line ): entity = html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity name:", ") # And parse this last block. print( \"[*]\", len( blockRequests ), \"request", "processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open( msDumpFilePath, \"rb\" ) as", "line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte = int( components[0] ) #", "6 ) != -1: # Reached the body of the page? skipLine =", "# Stores the IDs of pages pointed to by this non-disambiguation document (e.g.", "self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames(", "12 to \"f.12\". for to in doc[\"to\"]: if toFrom.get( to ) is None:", ") # Append new block to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT:", "dicts of the form {from:int, to: set{int, int, ..., int}}. \"\"\" print( \"[*]", "document points to, as long as current doc is a non-disambiguatio page. :param", "print( \"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self,", "index line by line. components = line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle]", "requests. self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last block. print( \"[*]\", len(", "surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of entities", "IDs of pages pointed to by this non-disambiguation document (e.g. nSet is empty", "ALGOL and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n", "Updating ned_linking collection... \", end=\"\" ) # Conform input to the following format:", "False # To avoid unnecessary checks. title = None nDoc = {} #", "for doc in linkDocuments: fId = \"f.\" + str( doc[\"from\"] ) # -->", "True } ) if record: # Process only those entities existing in entity_id", "collection with UpdateOne bulk writes. requests = [] BATCH_SIZE = 10000 totalRequests =", "A tuple containing (requestId, string block of data). :return: A dictionary of the", "[] linkDocuments = [] for chunk in rChunks: for doc in chunk: if", "stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f", "checks. title = None nDoc = {} # Output dictionary. for line in", "exists in entity_id collection. # Skip links to another disambiguation page or an", ") def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms from blocks of", "BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests = []", "in output dict. if nDoc.get( title ) is None: nDoc[title] = {} if", "title a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line ) # Find", "surface forms from Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities, \"entities in", "# Now reading a <page>. Make title a lowercase surface form. else: m", "title = None nDoc = {} # Output dictionary. for line in lines:", ") else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr", "sfDoc: # Iterate over surface forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\":", "ned_dictionary collection... \", end=\"\" ) requests = [] # We'll use bulk writes", "corresponding entity mappings with a reference count. nSet = set() # Stores the", "if doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] )", "block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData = block[1]", "line by line. components = line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte", "Wikipedia templates, files, etc. Use this method for incremental analysis of extracted Wikipedia", "document dictionaries to process: {id:int, title:str, lines:[str]}. :return: A list of tuples with", "nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is", "{} # This dict stores the surface forms and their corresponding entity mappings", "end=\"\" ) # Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}}", "fullDir ): print( \"[*] Processing\", directory ) files = os.listdir( fullDir ) #", "..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to", "eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity is", "another disambiguation page or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is", "print( \"[**] Processed\", len( nDoc ), \"redirect entries in block\", requestId, \"in\", endTime", "eId = \"m.\" + str( record[\"_id\"] ) # Creating entry in output dict.", "continue checking for redirect until page ends in </page>. mClient.close() endTime = time.time()", "blockRequests ) print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte,", "for t in self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append( pymongo.UpdateOne( {", "entity_id collection and insert their surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count()", "count ) dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) )", "list of lists of extracted wiki documents of the form {id:int, title:str, lines:[str]}.", "[] if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of documents. endTotalTime", "collection. # Skip links to another disambiguation page or an invalid entity page.", "= -1 to read all until EOF. requestId += 1 bz2File.seek( seekByte )", "extractedDir: Directory where the individual BZ2 files are located: must end in \"/\".", "Make title a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line ) #", "Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests", "incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ), \"request blocks starting", "(e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from redirect pages -------\" )", "line. components = line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte = int(", "seekByte = -1 for lineNumber, line in enumerate( indexFile ): # Read index", "requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ), \"request", "Check against DB that the referenced real-world entity exists in entity_id collection. #", "for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the entity names from entity_id", "entry in output dict. if nDoc.get( title ) is None: nDoc[title] = {}", "MongoClient import pymongo from urllib.parse import unquote import html import sys from .", "Process remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time() print( \"[!]", "W\" -> \"B & W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For", "in this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData", "in entity_id collection\" ) requests = [] # We'll use bulk writes to", "pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of", "Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request tuple in", "lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect title.", "startTime ) return nDoc def initDBCollections( self ): \"\"\" Reset the DB collections", "print( \"[**] Processed\", len( chunks ), \"chunks in\", endTime - startTime, \"secs\" )", "toFrom[to][fId] = True # Now, upsert ned_linking collection with UpdateOne bulk writes. requests", "pages -------\" ) startTotalTime = time.time() startTime = time.time() blockRequests = [] #", "{ \"e_l\": entity.lower() }, projection={ \"_id\": True } ) elif n > 1:", "startTime = time.time() print( \"------- Creating surface forms from Wikipedia titles -------\" )", "dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from redirect", "components = line.strip().split( \":\" ) # [ByteStart, DocID, DocTitle] newSeekByte = int( components[0]", "requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"[*]\", totalRequests, \"processed\" )", "own thread. pool.close() pool.join() # Close pool and wait for work to finish.", "count). # else: # print( \"[!] Entity\", entity, \"doesn't exist in the DB!\",", "requests. print( \"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ):", "= mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True } ) elif n", "the form {from:int, to: set{int, int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\"", "\"[**] Processed\", len( chunks ), \"chunks in\", endTime - startTime, \"secs\" ) def", "seek byte with count = -1 to read all until EOF. requestId +=", "= 20 for directory in directories: fullDir = extractedDir + directory if os.path.isdir(", "} }, upsert=True ) ) totalRequests += 1 if len( requests ) ==", "Close pool and wait for work to finish. # Split rChunks' lists of", "# And parse this last block. print( \"[*]\", len( blockRequests ), \"request blocks", "mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData = block[1] #", "entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( (", "# Get directories of the form AA, AB, AC, etc. chunks = []", ") == BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print(", "<page>. Make title a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line )", "if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. # Update DB collections. self._updateSurfaceFormsDictionary(", "doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line ) # Remove external links to avoid", "m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None: isDisambiguation = True", "requests = [] if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print(", "wikilinks in valid entity pages. Skip processing disambiguation pages, lists, and Wikipedia templates,", "self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process", "page IDs pointed to by this non-disambiguation document. else: print( \"[!] Entity\", entity,", ") def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining", "parseSFFromEntityNames( self ): \"\"\" Grab the entity names from entity_id collection and insert", "{\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments: fId =", "with UpdateOne bulk writes. requests = [] BATCH_SIZE = 10000 totalRequests = 0", "doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information.", "the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime = time.time() mClient =", "lowerCase=False ) # Add documents to a chunk list in preparation for multiprocessing.", "# We'll use bulk writes to speed up process. BATCH_SIZE = 10000 totalRequests", "process: {id:int, title:str, lines:[str]}. :return: A list of tuples with two dicts: one", "= time.time() pool = Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each", "up process. BATCH_SIZE = 10000 totalRequests = 0 for t in self._mEntity_ID.find(): #", "entity, \"doesn't exist in the DB!\", file=sys.stderr ) # else: # print( \"[W]", "List or chunk of document dictionaries to process: {id:int, title:str, lines:[str]}. :return: A", "title: # Find page title first. m = NEDParser._TitlePattern.search( line ) if m:", "\"entities in entity_id collection\" ) requests = [] # We'll use bulk writes", "or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match(", "msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile:", "First check how many entities match the lowercase version given in link: we", "their surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of", "Surface forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. # Update DB", "mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all docs'", "a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect", "class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia extracted and multistream archives to construct", "disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for", "def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link references to the ned_linking", "= True # No need to continue checking for redirect until page ends", "and Disambiguation pages -------\" ) startTotalTime = time.time() directories = os.listdir( extractedDir )", "Use this method for incremental analysis of extracted Wikipedia BZ2 files. :param extractedDir:", "\"[*] Updating ned_dictionary collection... \", end=\"\" ) requests = [] # We'll use", "mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData = block[1] # Obtain the title", "anchor text is the surface form. if len( surfaceForm ) > 128: #", "= re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__(", ") # Extract Wikilinks and update collections in DB. chunks = [] if", "own thread. pool.close() pool.join() # Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def", "surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print(", "is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] =", "multiprocessing import Pool from pymongo import MongoClient import pymongo from urllib.parse import unquote", "fullDir ) # Get all files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort()", ") }, { \"$set\": toFrom[to] }, upsert=True ) ) totalRequests += 1 if", "= [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"Done", "form one more time (i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"] )", "pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests", "bz2 import os import time import re from multiprocessing import Pool from pymongo", "# Each block request tuple in its own thread. pool.close() pool.join() # Update", "{} for doc in linkDocuments: fId = \"f.\" + str( doc[\"from\"] ) #", "len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract Wikilinks and update", "Reset the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we", "\\ and another of the form {from:int, to: set{int, int, ..., int}}. \"\"\"", "byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) blockRequests = [] startTime", "disambiguation page or an invalid entity page. if P.Parser._DisambiguationPattern.match( entity ) is None", "files are located: must end in \"/\". \"\"\" print( \"------- Creating surface forms", "= bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new", "elif not skipLine: if not title: # Find page title first. m =", "block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) # Append new block to", "Extract surface form from redirect pages. We don't modify the ned_linking collection in", "requestId = block[0] dData = block[1] # Obtain the title and redirect titles", "n > 1: # If more than one record, then Wikilink must match", "tuples into surface form dicts and linking dicts. sfDocuments = [] linkDocuments =", "# Get all files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file", "surfaceForm = matchTuple[1].lower() # For non disambiguation pages, anchor text is the surface", "Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from", "import html import sys from . import Parser as P importlib.reload( P )", "from Wikilinks and Disambiguation pages -------\" ) startTotalTime = time.time() directories = os.listdir(", "\"\"\" Read and process data from a block in multi-stream Wikipedia dump file.", "keepDisambiguation=True, lowerCase=False ) # Add documents to a chunk list in preparation for", "-1 for lineNumber, line in enumerate( indexFile ): # Read index line by", "to continue checking for redirect until page ends in </page>. mClient.close() endTime =", "len( nDoc ), \"redirect entries in block\", requestId, \"in\", endTime - startTime )", "False title = None elif not skipLine: if not title: # Find page", "\"m.EIDn\":int}, ...}, \\ and another of the form {from:int, to: set{int, int, ...,", "if not sfDoc: continue # Skip empty sf dictionaries. for sf in sfDoc:", "= None nDoc = {} # Output dictionary. for line in lines: line", "lists, and Wikipedia templates, files, etc. Use this method for incremental analysis of", "re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self", "This will become the common surface name for all wikilinks within current disambiguation", "A dictionary of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...} \"\"\" startTime =", "if len( requests ) == BATCH_SIZE: # Send lots of update requests at", "== REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print(", "== \"</page>\": # End of document? skipLine = False title = None elif", "\"$set\": toFrom[to] }, upsert=True ) ) totalRequests += 1 if len( requests )", "rule all docs' DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result =", "newSeekByte continue if newSeekByte != seekByte: # Changed seek-byte? requestId += 1 count", "Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I", "all requests in this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId =", ") if record: # Process only those entities existing in entity_id collection. eId", "nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity is referred to by this", "the common surface name for all wikilinks within current disambiguation page. for line", "block. lines = dData.split( \"\\n\" ) skipLine = False # To avoid unnecessary", "# To avoid unnecessary checks. title = None nDoc = {} # Output", "parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile = fullDir +", "of lists of extracted wiki documents of the form {id:int, title:str, lines:[str]}. \"\"\"", ") # Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments", "doc[1] ) # Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection(", "to rule all requests in this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"]", "drop the entity_id collection here: use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!]", "to, as long as current doc is a non-disambiguatio page. :param docs: List", "print( \"------- Creating surface forms from Wikipedia titles -------\" ) print( \"[!] Detected\",", "entity = html.unescape( unquote( matchTuple[0] ) ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\"", "construct the surface forms dictionary and the inter-links table. \"\"\" # Static members.", "of the form (requestID, blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block,", "matchTuple[0] ) ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\"", "page. if P.Parser._DisambiguationPattern.match( entity ) is None and P.Parser._SkipTitlePattern.match( entity ) is None:", "time.time() print( \"[**] Processed\", len( nDoc ), \"redirect entries in block\", requestId, \"in\",", "in chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if doc[1][\"to\"]: linkDocuments.append(", "\"pointing to invalid entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"...", "title first. m = NEDParser._TitlePattern.search( line ) if m: title = m.group( 1", "since redirect pages are only aliases for entity pages. :param msIndexFilePath: Multistream index", "many entities match the lowercase version given in link: we may have ALGOL", "to process: {id:int, title:str, lines:[str]}. :return: A list of tuples with two dicts:", "non-disambiguation document (e.g. nSet is empty for a disambiguation page). # Treat disambiguation", "fullDir + \"/\" + file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ):", "(by convention these will be lowercased). Also, collect the IDs of entities that", "= re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__(", "this non-disambiguation document (e.g. nSet is empty for a disambiguation page). # Treat", "for sfDoc in sfDocuments: if not sfDoc: continue # Skip empty sf dictionaries.", "\"B &amp; W\" -> \"B & W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower()", "os.listdir( extractedDir ) # Get directories of the form AA, AB, AC, etc.", "def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections", "= [] if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of documents.", "form {from:int, to: set{int, int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking collection...", "m: entity = m.group( 1 ) # Check against DB that the referenced", "page. :param docs: List or chunk of document dictionaries to process: {id:int, title:str,", "): \"\"\" Read surface forms from blocks of Wikipedia documents obtained from the", "dictionaries. for sf in sfDoc: # Iterate over surface forms in current dict.", ") dData = bz2.decompress( block ).decode( \"utf-8\" ) blockRequests.append( (requestId, dData) ) #", "nDoc[title][eId] += 1 # Entity is referred to by this surface form one", "mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all requests", "blockRequests.append( (requestId, dData) ) # Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests )", "pymongo import MongoClient import pymongo from urllib.parse import unquote import html import sys", ") # Find the next seek byte start that is different to current", "all docs' DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result = []", "Append new block to requests. if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate", "real-world entity exists in entity_id collection. # Skip links to another disambiguation page", "# Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with", "import re from multiprocessing import Pool from pymongo import MongoClient import pymongo from", "differently than regular valid pages. surfaceForm = \"\" isDisambiguation = False m =", "writes to speed up process. BATCH_SIZE = 10000 totalRequests = 0 for t", "to by this surface form one more time (i.e. increase count). if not", "# Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time()", "sfDocuments: List of (possibly empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int},", "in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile =", "Entity is referred to by this surface form one more time (i.e. increase", "Obtain the title and redirect titles from read block. lines = dData.split( \"\\n\"", "processing disambiguation pages, lists, and Wikipedia templates, files, etc. Use this method for", "is None: record = None # Sentinel for found entity in DB. #", "print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) else: print(", "-------\" ) startTotalTime = time.time() startTime = time.time() blockRequests = [] # Accumulate", "Skip empty sf dictionaries. for sf in sfDoc: # Iterate over surface forms", "= newSeekByte - seekByte # Number of bytes to read from bz2 stream.", "disambiguation page to obtain surface forms (by convention these will be lowercased). Also,", "- startTime, \"secs\" ) endTotalTime = time.time() print( \"[!] Completed process for redirect", "the page. elif line.find( \"<text\", 0, 6 ) != -1: # Reached the", "\"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from", "time.time() print( \"[!] Completed process for redirect surface forms in\", endTotalTime - startTotalTime,", "aliases for entity pages. :param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param", "\", end=\"\" ) # Conform input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ...,", "list in preparation for multiprocessing. chunks.append( documents ) if len( chunks ) ==", "None elif not skipLine: if not title: # Find page title first. m", "chunks ) # Process remaining chunks of documents. endTotalTime = time.time() print( \"[!]", "entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr ) skipLine = True #", "And parse this last block. print( \"[*]\", len( blockRequests ), \"request blocks starting", "from bz2 stream. bz2File.seek( seekByte ) # Read block of data. block =", "invalid entity\", entity, file=sys.stderr ) skipLine = True # Found what we wanted...", "P.Parser._SkipTitlePattern.match( entity ) is None: record = None # Sentinel for found entity", "continue if line == \"</page>\": # End of document? skipLine = False title", "): \"\"\" Extract wikilinks from regular and disambiguation pages, and write results to", "update collections in DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks ) #", "regular valid pages. surfaceForm = \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"]", "in toFrom: requests.append( pymongo.UpdateOne( { \"_id\": int( to ) }, { \"$set\": toFrom[to]", ") print( \"[*]\", totalRequests, \"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests", "-- f stands for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the entity", "re.I ) def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) #", "Parsing Wikipedia extracted and multistream archives to construct the surface forms dictionary and", "\"chunks in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ):", "else: print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) else:", "endTime - startTime ) return nDoc def initDBCollections( self ): \"\"\" Reset the", ") is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId]", "BATCH_SIZE: # Send lots of update requests at once. self._mNed_Linking.bulk_write( requests ) requests", "), \"request blocks starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\"", "requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True ) )", "to finish. # Split rChunks' lists of tuples into surface form dicts and", "\"[!] Done after\", endTime - startTime, \"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ):", "seekByte = newSeekByte continue if newSeekByte != seekByte: # Changed seek-byte? requestId +=", "\"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab the", "count. nSet = set() # Stores the IDs of pages pointed to by", "!= seekByte: # Changed seek-byte? requestId += 1 count = newSeekByte - seekByte", "Grab the entity names from entity_id collection and insert their surface forms in", "in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract", "forms from redirect pages -------\" ) startTotalTime = time.time() startTime = time.time() blockRequests", "# Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile( r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\",", ").strip().lower() # This will become the common surface name for all wikilinks within", "reference count. nSet = set() # Stores the IDs of pages pointed to", "pymongo.UpdateOne( { \"_id\": int( to ) }, { \"$set\": toFrom[to] }, upsert=True )", "= 0 with open( msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath, \"r\",", "with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True,", "with a reference count. nSet = set() # Stores the IDs of pages", "title, \"pointing to invalid entity\", entity, file=sys.stderr ) skipLine = True # Found", "seekByte, \"parsed after\", time.time() - startTime, \"secs\" ) endTotalTime = time.time() print( \"[!]", "the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't", "its own thread. pool.close() pool.join() # Close pool and wait for work to", "pages. :param msIndexFilePath: Multistream index file path (e.g. enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump", "[] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"[*]\", totalRequests,", "given in link: we may have ALGOL and Algol... n = mEntity_ID.find( {", "e.g. \"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B & W\". if not isDisambiguation:", "check how many entities match the lowercase version given in link: we may", "dropped\" ) @staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an entity", "toFrom = {} for doc in linkDocuments: fId = \"f.\" + str( doc[\"from\"]", "document objects in its own thread. pool.close() pool.join() # Close pool and wait", "return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED dictionary of", "newSeekByte - seekByte # Number of bytes to read from bz2 stream. bz2File.seek(", "of dicts of the form {from:int, to: set{int, int, ..., int}}. \"\"\" print(", "def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from redirect pages.", "are located: must end in \"/\". \"\"\" print( \"------- Creating surface forms and", "= {} # Output dictionary. for line in lines: line = line.strip() if", "# Add documents to a chunk list in preparation for multiprocessing. chunks.append( documents", "after\", time.time() - startTime, \"secs\" ) blockRequests = [] startTime = time.time() seekByte", "\"pointing to invalid entity\", entity, file=sys.stderr ) skipLine = True # Found what", "surface forms dictionary and the inter-links table. \"\"\" # Static members. _TitlePattern =", "sfDocuments = [] linkDocuments = [] for chunk in rChunks: for doc in", "the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection...", "'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for", "match the true entity name: case sensitive. record = mEntity_ID.find_one( { \"e\": entity", "m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if m: entity =", "if n == 1: # One match? Then retrieve entity ID. record =", "print( \"Done with\", totalRequests, \"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\"", "None and P.Parser._SkipTitlePattern.match( entity ) is None: record = None # Sentinel for", "in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\": sfDoc[sf] },", "\"$inc\": { \"m.\" + str( t[\"_id\"] ): +1 } }, upsert=True ) )", "to rule all docs' DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result", "W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation pages, anchor", "count). if not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of page IDs", "mappings with a reference count. nSet = set() # Stores the IDs of", "pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request", "# Process remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time() print(", "[] # We'll use bulk writes to speed up process. BATCH_SIZE = 10000", "= m.group( 1 ) # Check against DB that the referenced real-world entity", "preparation for multiprocessing. chunks.append( documents ) if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks(", "= {} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] +=", "# {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"]", "title. if m: entity = m.group( 1 ) # Check against DB that", "endTime = time.time() print( \"[**] Processed\", len( nDoc ), \"redirect entries in block\",", "incremental analysis of extracted Wikipedia BZ2 files. :param extractedDir: Directory where the individual", "dump file. :param block: A tuple containing (requestId, string block of data). :return:", "\"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments: fId = \"f.\" + str(", "Skipping entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr ) skipLine = True", "line.find( \"<text\", 0, 6 ) != -1: # Reached the body of the", "Keep track of page IDs pointed to by this non-disambiguation document. else: print(", "matchTuple[1].lower() # For non disambiguation pages, anchor text is the surface form. if", "self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"[*]\", totalRequests, \"processed\" ) endTime", "= mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\": True } ) if record:", "Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) else: print( \"[W] Skipping", "obtained from the BZ2 multi-stream dump file. :param requests: A list of tuples", "chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of documents. endTotalTime = time.time()", "time.time() - startTime, \"secs\" ) blockRequests = [] startTime = time.time() seekByte =", "the IDs of pages pointed to by this non-disambiguation document (e.g. nSet is", ") @staticmethod def _extractWikilinks( docs ): \"\"\" Parse inter-Wikilinks from an entity page", "forms from blocks of Wikipedia documents obtained from the BZ2 multi-stream dump file.", "\"<text\", 0, 6 ) != -1: # Reached the body of the page?", ") # Read block of data. block = bz2File.read( count ) dData =", "form one more time (i.e. increase count). # else: # print( \"[!] Entity\",", "This dict stores the surface forms and their corresponding entity mappings with a", "directory ) files = os.listdir( fullDir ) # Get all files in current", "data. block = bz2File.read( -1 ) dData = bz2.decompress( block ).decode( \"utf-8\" )", "0 nDoc[surfaceForm][eId] += 1 # Entity is referred to by this surface form", "# This dict stores the surface forms and their corresponding entity mappings with", "if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"[*]\", totalRequests, \"processed\"", "n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n == 1: #", "from 12 to \"f.12\". for to in doc[\"to\"]: if toFrom.get( to ) is", "the NED dictionary of surface forms. :param sfDocuments: List of (possibly empty) surface", "Each block request tuple in its own thread. pool.close() pool.join() # Update ned_dictionary", "file=sys.stderr ) skipLine = True # Found what we wanted... skip the rest", "P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None: isDisambiguation = True # We'll", "Pool() rChunks = pool.map( NEDParser._extractWikilinks, chunks ) # Each chunk of document objects", "last block. print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte,", "True # We'll be processing a disambiguation page. surfaceForm = m.group( 1 ).strip().lower()", "file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from redirect pages", "pages. Skip processing disambiguation pages, lists, and Wikipedia templates, files, etc. Use this", "collection\" ) requests = [] # We'll use bulk writes to speed up", "linkDocuments ) endTime = time.time() print( \"[**] Processed\", len( chunks ), \"chunks in\",", "link: we may have ALGOL and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower()", "\"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms from blocks", "print( \"------- Creating surface forms and links from Wikilinks and Disambiguation pages -------\"", "Add more link references to the ned_linking collection. :param linkDocuments: A list of", ") == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests )", "finish. # Split rChunks' lists of tuples into surface form dicts and linking", "bz2 stream. bz2File.seek( seekByte ) # Read block of data. block = bz2File.read(", "set{int, int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single", "\"_id\": int( to ) }, { \"$set\": toFrom[to] }, upsert=True ) ) totalRequests", "upsert=True ) ) totalRequests += 1 if len( requests ) == BATCH_SIZE: #", "from wikilinks in valid entity pages. Skip processing disambiguation pages, lists, and Wikipedia", "Completed process in\", endTotalTime - startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ):", "link relationships from wikilinks in valid entity pages. Skip processing disambiguation pages, lists,", "0 with open( msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\"", "self._mNed_Linking.bulk_write( requests ) requests = [] if requests: self._mNed_Linking.bulk_write( requests ) # Process", "Parser as P importlib.reload( P ) class NEDParser( P.Parser ): \"\"\" Parsing Wikipedia", "self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to a chunk list in", "\"------- Creating surface forms from redirect pages -------\" ) startTotalTime = time.time() startTime", "\"\"\" Grab surface forms and link relationships from wikilinks in valid entity pages.", "totalRequests = 0 for t in self._mEntity_ID.find(): # Surface forms are in lowercase.", "line ) # Find redirect title. if m: entity = m.group( 1 )", "# If more than one record, then Wikilink must match the true entity", "entity, file=sys.stderr ) skipLine = True # Found what we wanted... skip the", "multi-stream dump file. :param requests: A list of tuples of the form (requestID,", "and Wikipedia templates, files, etc. Use this method for incremental analysis of extracted", "block in multi-stream Wikipedia dump file. :param block: A tuple containing (requestId, string", "sf }, { \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests += 1 if", "docs' DB requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for", "dict stores the surface forms and their corresponding entity mappings with a reference", "redirect title. if m: entity = m.group( 1 ) # Check against DB", "else: m = NEDParser._RedirectTitlePattern.search( line ) # Find redirect title. if m: entity", "surface form from redirect pages. We don't modify the ned_linking collection in this", "# Obtain the title and redirect titles from read block. lines = dData.split(", "lines:[str]}. :return: A list of tuples with two dicts: one of the form", "dData) ) # Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests ) # And", "# print( \"[W] Skipping entry\", title, \"pointing to invalid entity\", entity, file=sys.stderr )", "print( \"[*] Updating ned_linking collection... \", end=\"\" ) # Conform input to the", "dData) ) # Append new block to requests. if len( blockRequests ) ==", ") # else: # print( \"[W] Skipping entry\", title, \"pointing to invalid entity\",", "the surface forms and their corresponding entity mappings with a reference count. nSet", "\", end=\"\" ) requests = [] # We'll use bulk writes to speed", "\"/\" + file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): # Read", "endTotalTime - startTotalTime, \"secs\" ) def _parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface", "mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for doc in docs:", "REQUESTS_BLOCK_COUNT = 1000 requestId = 0 with open( msDumpFilePath, \"rb\" ) as bz2File:", "We don't modify the ned_linking collection in this function since redirect pages are", ") blockRequests.append( (requestId, dData) ) # Append new block to requests. self._parseMSBZ2BlockRequests( blockRequests", "table. \"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern =", "10000 totalRequests = 0 for t in self._mEntity_ID.find(): # Surface forms are in", "elif line.find( \"<text\", 0, 6 ) != -1: # Reached the body of", "None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0", "not sfDoc: continue # Skip empty sf dictionaries. for sf in sfDoc: #", "form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*]", "surface forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, { \"$inc\":", "seekByte ) # Read block of data. block = bz2File.read( -1 ) dData", "Stores the IDs of pages pointed to by this non-disambiguation document (e.g. nSet", "= [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"[*]\",", "= {} if nDoc[title].get( eId ) is None: nDoc[title][eId] = 0 nDoc[title][eId] +=", "record = None # Sentinel for found entity in DB. # First check", "Parse inter-Wikilinks from an entity page or disambiguation page to obtain surface forms", "in its own thread. pool.close() pool.join() # Close pool and wait for work", "\"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity, file=sys.stderr ) # print(", "ned_linking collection in this function since redirect pages are only aliases for entity", ":param extractedDir: Directory where the individual BZ2 files are located: must end in", "reading a <page>. Make title a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search(", "), \"chunks in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath", "= newSeekByte continue if newSeekByte != seekByte: # Changed seek-byte? requestId += 1", "DB!\", file=sys.stderr ) # else: # print( \"[W] Skipping entry\", title, \"pointing to", "(possibly empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}.", "totalRequests = 0 for sfDoc in sfDocuments: if not sfDoc: continue # Skip", "all files in current parsing directory, e.g. AA/wiki_00.bz2. files.sort() for file in files:", "match? Then retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={", "len( chunks ), \"chunks in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages( self,", "of pages pointed to by this non-disambiguation document (e.g. nSet is empty for", "entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\": True }", "{ \"_id\": sf }, { \"$inc\": sfDoc[sf] }, upsert=True ) ) totalRequests +=", "a disambiguation page). # Treat disambiguation pages differently than regular valid pages. surfaceForm", "time.time() directories = os.listdir( extractedDir ) # Get directories of the form AA,", "directory, e.g. AA/wiki_00.bz2. files.sort() for file in files: fullFile = fullDir + \"/\"", "one more time (i.e. increase count). if not isDisambiguation: nSet.add( record[\"_id\"] ) #", "\"\"\" P.Parser.__init__( self ) # Defining connections to collections for entity disambiguation. self._mNed_Dictionary", "seekByte # Number of bytes to read from bz2 stream. bz2File.seek( seekByte )", "too long of a surface form. continue # Skip links to another disambiguation", "sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**] Processed\", len( chunks", "= [] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT = 1000 requestId =", "to: set{int, int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One", "of page IDs pointed to by this non-disambiguation document. else: print( \"[!] Entity\",", "print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) # else:", "sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\" Read and process data from", "initDBCollections( self ): \"\"\" Reset the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop()", "Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments ) self._updateLinkingCollection( linkDocuments ) endTime", "collection here: use the TFIDFParser for that. self._mNed_Linking.drop() print( \"[!] Collections for surface", "requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests, \"requests", "unnecessary checks. title = None nDoc = {} # Output dictionary. for line", "nEntities = self._mEntity_ID.count() # Retrieve number of entities in DB. startTime = time.time()", "\"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) else: print( \"[W]", "A list of tuples of the form (requestID, blockStringData) \"\"\" pool = Pool()", "Defining connections to collections for entity disambiguation. self._mNed_Dictionary = self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int,", "Creating surface forms from Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities, \"entities", "chunk list in preparation for multiprocessing. chunks.append( documents ) if len( chunks )", "the body of the page? skipLine = True # No need to continue", "end in \"/\". \"\"\" print( \"------- Creating surface forms and links from Wikilinks", "collection... \", end=\"\" ) requests = [] # We'll use bulk writes to", "\"doesn't exist in the DB!\", file=sys.stderr ) # else: # print( \"[W] Skipping", "# Skip too long of a surface form. continue # Skip links to", "enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating surface forms from redirect pages -------\" ) startTotalTime", "form from redirect pages. We don't modify the ned_linking collection in this function", "), \"redirect entries in block\", requestId, \"in\", endTime - startTime ) return nDoc", "entity, \"doesn't exist in the DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\",", "of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the", "list of dicts of the form {from:int, to: set{int, int, ..., int}}. \"\"\"", "obtain surface forms (by convention these will be lowercased). Also, collect the IDs", "pool.join() # Close pool and wait for work to finish. # Split rChunks'", "data. block = bz2File.read( count ) dData = bz2.decompress( block ).decode( \"utf-8\" )", "= mNED[\"entity_id\"] requestId = block[0] dData = block[1] # Obtain the title and", "and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents =", "mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments ): \"\"\" Update the NED dictionary", "entity in DB. # First check how many entities match the lowercase version", "(e.g. nSet is empty for a disambiguation page). # Treat disambiguation pages differently", "existing in entity_id collection. eId = \"m.\" + str( record[\"_id\"] ) # Creating", ") == BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests", "page. elif line.find( \"<text\", 0, 6 ) != -1: # Reached the body", "Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) # else: # print(", "doc in linkDocuments: fId = \"f.\" + str( doc[\"from\"] ) # --> from", "= time.time() blockRequests = [] # Accumulate blocks for multithreading processing. REQUESTS_BLOCK_COUNT =", "for all wikilinks within current disambiguation page. for line in doc[\"lines\"]: line =", "use bulk writes to speed up process. BATCH_SIZE = 10000 totalRequests = 0", "& W\". if not isDisambiguation: surfaceForm = matchTuple[1].lower() # For non disambiguation pages,", "None: nDoc[title] = {} if nDoc[title].get( eId ) is None: nDoc[title][eId] = 0", "= mNED[\"entity_id\"] result = [] for doc in docs: nDoc = {} #", "\"\"\" Extract surface form from redirect pages. We don't modify the ned_linking collection", "Extract wikilinks from regular and disambiguation pages, and write results to ned_dictionary and", "\"B%20%26amp%3B%20W\" -> \"B &amp; W\" -> \"B & W\". if not isDisambiguation: surfaceForm", "seek-byte? requestId += 1 count = newSeekByte - seekByte # Number of bytes", "surface forms and their corresponding entity mappings with a reference count. nSet =", "blockStringData) \"\"\" pool = Pool() sfDocuments = pool.map( NEDParser._processMSBZ2Block, requests ) # Each", "# Output dictionary. for line in lines: line = line.strip() if not line:", "more than one record, then Wikilink must match the true entity name: case", "from an entity page or disambiguation page to obtain surface forms (by convention", "# Extract Wikilinks and update collections in DB. chunks = [] if chunks:", "collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't drop the", "DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks", ") # Check against DB that the referenced real-world entity exists in entity_id", "block of data. block = bz2File.read( count ) dData = bz2.decompress( block ).decode(", "of document objects in its own thread. pool.close() pool.join() # Close pool and", "None nDoc = {} # Output dictionary. for line in lines: line =", "projection={ \"_id\": True } ) elif n > 1: # If more than", "will become the common surface name for all wikilinks within current disambiguation page.", "End of document? skipLine = False title = None elif not skipLine: if", "BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests,", "for surface forms computations have been dropped\" ) @staticmethod def _extractWikilinks( docs ):", "in entity_id collection. # Skip links to another disambiguation page or an invalid", ") is None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity is referred", "of the page. elif line.find( \"<text\", 0, 6 ) != -1: # Reached", "lines = dData.split( \"\\n\" ) skipLine = False # To avoid unnecessary checks.", "be processing a disambiguation page. surfaceForm = m.group( 1 ).strip().lower() # This will", "= \"m.\" + str( record[\"_id\"] ) # Creating entry in output dict. if", "block: A tuple containing (requestId, string block of data). :return: A dictionary of", "n == 1: # One match? Then retrieve entity ID. record = mEntity_ID.find_one(", "time.time() - startTime, \"secs\" ) endTotalTime = time.time() print( \"[!] Completed process for", "if m: title = m.group( 1 ).lower() # Now reading a <page>. Make", "[ByteStart, DocID, DocTitle] newSeekByte = int( components[0] ) # Find the next seek", "exist in the DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm, \"pointing", "the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}, \\ and another of the form", "requests. self._mNed_Dictionary.bulk_write( requests ) print( \"[*]\", totalRequests, \"processed\" ) requests = [] if", "\"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def parseSFFromEntityNames( self ): \"\"\" Grab", "def parseSFFromEntityNames( self ): \"\"\" Grab the entity names from entity_id collection and", "\"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" + str( t[\"_id\"] ): +1 }", "r\"<redirect\\s+title=\\\"\\s*(.+?)\\s*\\\"\\s*/>\", re.I ) def __init__( self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self )", "from read block. lines = dData.split( \"\\n\" ) skipLine = False # To", "bz2File.seek( seekByte ) # Read block of data. block = bz2File.read( count )", "\"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\" ) requests = [] #", "# print( \"[!] Entity\", entity, \"doesn't exist in the DB!\", file=sys.stderr ) #", "and redirect titles from read block. lines = dData.split( \"\\n\" ) skipLine =", "until page ends in </page>. mClient.close() endTime = time.time() print( \"[**] Processed\", len(", "within current disambiguation page. for line in doc[\"lines\"]: line = P.Parser._ExternalLinkPattern.sub( r\"\\3\", line", "doc[\"id\"], \"to\": nSet } ) ) mClient.close() return result def _updateSurfaceFormsDictionary( self, sfDocuments", "\"[!] Completed process for redirect surface forms in\", endTotalTime - startTotalTime, \"secs\" )", "and link relationships from wikilinks in valid entity pages. Skip processing disambiguation pages,", "entities existing in entity_id collection. eId = \"m.\" + str( record[\"_id\"] ) #", "blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed after\", time.time() - startTime,", "for doc in chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface forms. if", "# Process remaining chunks of documents. endTotalTime = time.time() print( \"[!] Completed process", "EOF. requestId += 1 bz2File.seek( seekByte ) # Read block of data. block", "templates, files, etc. Use this method for incremental analysis of extracted Wikipedia BZ2", "nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId]", "the ned_linking collection. :param linkDocuments: A list of dicts of the form {from:int,", "= [] if requests: self._mNed_Linking.bulk_write( requests ) # Process remaining requests. print( \"Done", "isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is not None:", "m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int,", "directories of the form AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE =", "Processed\", len( chunks ), \"chunks in\", endTime - startTime, \"secs\" ) def parseSFFromRedirectPages(", "\"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking = self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,...,", "\"[*] Processing\", directory ) files = os.listdir( fullDir ) # Get all files", "# Read block of data. block = bz2File.read( -1 ) dData = bz2.decompress(", "chunks = [] if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of", "file and process it. with bz2.open( fullFile, \"rt\", encoding=\"utf-8\" ) as bz2File: documents", "form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \",", "requestId = 0 with open( msDumpFilePath, \"rb\" ) as bz2File: with open( msIndexFilePath,", "of document dictionaries to process: {id:int, title:str, lines:[str]}. :return: A list of tuples", "dict. if nDoc.get( surfaceForm ) is None: nDoc[surfaceForm] = {} if nDoc[surfaceForm].get( eId", "documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to a chunk", "m.group( 1 ).strip().lower() # This will become the common surface name for all", "until EOF. requestId += 1 bz2File.seek( seekByte ) # Read block of data.", "parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ), \"request blocks starting at", ") # Keep track of page IDs pointed to by this non-disambiguation document.", ":param linkDocuments: A list of dicts of the form {from:int, to: set{int, int,", "Also, collect the IDs of entities that current document points to, as long", "REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len( blockRequests ),", "self ): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections to collections", "is a non-disambiguatio page. :param docs: List or chunk of document dictionaries to", "}, { \"$set\": toFrom[to] }, upsert=True ) ) totalRequests += 1 if len(", "- startTotalTime, \"secs\" ) def _extractAndProcessWikilinks( self, chunks ): \"\"\" Extract wikilinks from", "time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all", "from entity_id collection and insert their surface forms in ned_dictionary. \"\"\" nEntities =", "extractedDir + directory if os.path.isdir( fullDir ): print( \"[*] Processing\", directory ) files", "entities that current document points to, as long as current doc is a", "IDs pointed to by this non-disambiguation document. else: print( \"[!] Entity\", entity, \"doesn't", "block[0] dData = block[1] # Obtain the title and redirect titles from read", "located: must end in \"/\". \"\"\" print( \"------- Creating surface forms and links", "m.group( 1 ) # Check against DB that the referenced real-world entity exists", "self, linkDocuments ): \"\"\" Add more link references to the ned_linking collection. :param", "Now reading a <page>. Make title a lowercase surface form. else: m =", "is None: nDoc[title] = {} if nDoc[title].get( eId ) is None: nDoc[title][eId] =", "m is not None: isDisambiguation = True # We'll be processing a disambiguation", "> 1: # If more than one record, then Wikilink must match the", "return nDoc def initDBCollections( self ): \"\"\" Reset the DB collections to start", "{ \"m.\" + str( t[\"_id\"] ): +1 } }, upsert=True ) ) totalRequests", "\"request blocks starting at byte\", seekByte, \"parsed after\", time.time() - startTime, \"secs\" )", "\"f.\" + str( doc[\"from\"] ) # --> from 12 to \"f.12\". for to", "in DB. # First check how many entities match the lowercase version given", "that. self._mNed_Linking.drop() print( \"[!] Collections for surface forms computations have been dropped\" )", "BZ2 files. :param extractedDir: Directory where the individual BZ2 files are located: must", "# Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing. self._parseMSBZ2BlockRequests( blockRequests ) print( \"[*]\", len(", "over surface forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf }, {", ") endTime = time.time() print( \"[!] Done after\", endTime - startTime, \"secs.\" )", "in rChunks: for doc in chunk: if doc[0]: sfDocuments.append( doc[0] ) # Surface", "read from bz2 stream. bz2File.seek( seekByte ) # Read block of data. block", "): \"\"\" Grab the entity names from entity_id collection and insert their surface", "not isDisambiguation: nSet.add( record[\"_id\"] ) # Keep track of page IDs pointed to", "str( doc[\"from\"] ) # --> from 12 to \"f.12\". for to in doc[\"to\"]:", "the rest of the page. elif line.find( \"<text\", 0, 6 ) != -1:", "# Sentinel for found entity in DB. # First check how many entities", "AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE = 20 for directory in", "this last block. print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\",", "single connection to rule all requests in this block. mNED = mClient.ned mEntity_ID", "output dict. if nDoc.get( title ) is None: nDoc[title] = {} if nDoc[title].get(", "= True # We'll be processing a disambiguation page. surfaceForm = m.group( 1", "# Update ned_dictionary collection. self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\"", "int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\" ) #", "= self._mNED[\"ned_linking\"] # {_id:int, f:{\"e_1\":true, \"e_2\":true,..., \"e_3\":true}}. -- f stands for 'from.' def", "= 10000 totalRequests = 0 for t in self._mEntity_ID.find(): # Surface forms are", "endTime = time.time() print( \"[**] Processed\", len( chunks ), \"chunks in\", endTime -", "the DB!\", file=sys.stderr ) # else: # print( \"[W] Skipping entry\", title, \"pointing", "form dicts and linking dicts. sfDocuments = [] linkDocuments = [] for chunk", "of bytes to read from bz2 stream. bz2File.seek( seekByte ) # Read block", "projection={ \"_id\": True } ) if record: # Process only those entities existing", "+1 } }, upsert=True ) ) totalRequests += 1 if len( requests )", "if chunks: self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of documents. endTotalTime =", "chunks: A list of lists of extracted wiki documents of the form {id:int,", "self._parseMSBZ2BlockRequests( blockRequests ) # And parse this last block. print( \"[*]\", len( blockRequests", "\"f.12\". for to in doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to] =", "</page>. mClient.close() endTime = time.time() print( \"[**] Processed\", len( nDoc ), \"redirect entries", "wanted... skip the rest of the page. elif line.find( \"<text\", 0, 6 )", "of entities in DB. startTime = time.time() print( \"------- Creating surface forms from", "# Each chunk of document objects in its own thread. pool.close() pool.join() #", "DB!\", file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\",", "\"</page>\": # End of document? skipLine = False title = None elif not", "Wikipedia BZ2 files. :param extractedDir: Directory where the individual BZ2 files are located:", "entity\", entity, file=sys.stderr ) skipLine = True # Found what we wanted... skip", "wiki documents of the form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool", "the true entity name: case sensitive. record = mEntity_ID.find_one( { \"e\": entity },", "= block[1] # Obtain the title and redirect titles from read block. lines", "DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note that we don't drop", "if len( surfaceForm ) > 128: # Skip too long of a surface", "\"mongodb://localhost:27017/\" ) # One single connection to rule all requests in this block.", "must end in \"/\". \"\"\" print( \"------- Creating surface forms and links from", "print( \"[*] Processing\", directory ) files = os.listdir( fullDir ) # Get all", ") # Add documents to a chunk list in preparation for multiprocessing. chunks.append(", "to in doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to] = {} toFrom[to][fId]", "linkDocuments: A list of dicts of the form {from:int, to: set{int, int, ...,", "Then retrieve entity ID. record = mEntity_ID.find_one( { \"e_l\": entity.lower() }, projection={ \"_id\":", "unquote( matchTuple[0] ) ).strip() # Clean entity name: e.g. \"B%20%26amp%3B%20W\" -> \"B &amp;", "enwiki-20141106-pages-articles-multistream-index.txt). :param msDumpFilePath: Multistream dump file path (e.g. enwiki-20141106-pages-articles-multistream.xml.bz2). \"\"\" print( \"------- Creating", "+ directory if os.path.isdir( fullDir ): print( \"[*] Processing\", directory ) files =", "titles -------\" ) print( \"[!] Detected\", nEntities, \"entities in entity_id collection\" ) requests", "link references to the ned_linking collection. :param linkDocuments: A list of dicts of", "and insert their surface forms in ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve", "Find redirect title. if m: entity = m.group( 1 ) # Check against", "file=sys.stderr ) else: print( \"[W] Skipping entry\", surfaceForm, \"pointing to invalid entity\", entity,", "requests. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] result = [] for doc in", "Update the NED dictionary of surface forms. :param sfDocuments: List of (possibly empty)", "to the ned_linking collection. :param linkDocuments: A list of dicts of the form", "directories: fullDir = extractedDir + directory if os.path.isdir( fullDir ): print( \"[*] Processing\",", "If more than one record, then Wikilink must match the true entity name:", "file. :param requests: A list of tuples of the form (requestID, blockStringData) \"\"\"", "): \"\"\" Reset the DB collections to start afresh. \"\"\" self._mNed_Dictionary.drop() # Note", "of the form {from:int, to: set{int, int, ..., int}}. \"\"\" print( \"[*] Updating", "ned_dictionary. \"\"\" nEntities = self._mEntity_ID.count() # Retrieve number of entities in DB. startTime", "files.sort() for file in files: fullFile = fullDir + \"/\" + file if", "pointed to by this non-disambiguation document (e.g. nSet is empty for a disambiguation", "function since redirect pages are only aliases for entity pages. :param msIndexFilePath: Multistream", "documents. endTotalTime = time.time() print( \"[!] Completed process in\", endTotalTime - startTotalTime, \"secs\"", "seekByte = newSeekByte # Add the last seek byte with count = -1", "List of (possibly empty) surface form docs of the form {\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,...,", "input to the following format: {\"eId1\":{\"f.eId2\":True, \"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for", "self._updateLinkingCollection( linkDocuments ) endTime = time.time() print( \"[**] Processed\", len( chunks ), \"chunks", "bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to a chunk list in preparation", "doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. # Update DB collections. self._updateSurfaceFormsDictionary( sfDocuments", "nDoc[surfaceForm].get( eId ) is None: nDoc[surfaceForm][eId] = 0 nDoc[surfaceForm][eId] += 1 # Entity", "as bz2File: documents = self._extractWikiPagesFromBZ2( bz2File.readlines(), keepDisambiguation=True, lowerCase=False ) # Add documents to", "mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if n == 1: # One match?", "to \"f.12\". for to in doc[\"to\"]: if toFrom.get( to ) is None: toFrom[to]", "Get directories of the form AA, AB, AC, etc. chunks = [] MAX_CHUNK_SIZE", "as current doc is a non-disambiguatio page. :param docs: List or chunk of", "we may have ALGOL and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() }", "we wanted... skip the rest of the page. elif line.find( \"<text\", 0, 6", "lots of update requests. self._mNed_Dictionary.bulk_write( requests ) requests = [] if requests: self._mNed_Dictionary.bulk_write(", "\"[*] Updating ned_linking collection... \", end=\"\" ) # Conform input to the following", "in the DB!\", file=sys.stderr ) # else: # print( \"[W] Skipping entry\", title,", "a <page>. Make title a lowercase surface form. else: m = NEDParser._RedirectTitlePattern.search( line", "chunks.append( documents ) if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) #", "seek byte from file. seekByte = newSeekByte continue if newSeekByte != seekByte: #", "forms from Wikipedia titles -------\" ) print( \"[!] Detected\", nEntities, \"entities in entity_id", "file. seekByte = newSeekByte continue if newSeekByte != seekByte: # Changed seek-byte? requestId", "disambiguation pages, and write results to ned_dictionary and ned_linking collections. :param chunks: A", "Now, upsert ned_linking collection with UpdateOne bulk writes. requests = [] BATCH_SIZE =", "mNED[\"entity_id\"] requestId = block[0] dData = block[1] # Obtain the title and redirect", "self._mNED[\"ned_dictionary\"] # {_id:str, m:{\"e_1\":int, \"e_2\":int,..., \"e_n\":int}}. -- m stands for 'mapping.' self._mNed_Linking =", "for matchTuple in P.Parser._LinkPattern.findall( line ): entity = html.unescape( unquote( matchTuple[0] ) ).strip()", "# For non disambiguation pages, anchor text is the surface form. if len(", "and links from Wikilinks and Disambiguation pages -------\" ) startTotalTime = time.time() directories", "None: nDoc[title][eId] = 0 nDoc[title][eId] += 1 # Entity is referred to by", "startTime = time.time() seekByte = newSeekByte # Add the last seek byte with", "..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments: fId = \"f.\" +", "sf in sfDoc: # Iterate over surface forms in current dict. requests.append( pymongo.UpdateOne(", "requests in this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0]", "form {id:int, title:str, lines:[str]}. \"\"\" startTime = time.time() pool = Pool() rChunks =", "= -1 for lineNumber, line in enumerate( indexFile ): # Read index line", "0 for t in self._mEntity_ID.find(): # Surface forms are in lowercase. requests.append( pymongo.UpdateOne(", "checking for redirect until page ends in </page>. mClient.close() endTime = time.time() print(", "# Add the last seek byte with count = -1 to read all", "os.path.isdir( fullDir ): print( \"[*] Processing\", directory ) files = os.listdir( fullDir )", "\"\"\" # Static members. _TitlePattern = re.compile( r\"<title>\\s*(.+?)\\s*</title>\", re.I ) _RedirectTitlePattern = re.compile(", "= time.time() print( \"[**] Processed\", len( chunks ), \"chunks in\", endTime - startTime,", "Skip processing disambiguation pages, lists, and Wikipedia templates, files, etc. Use this method", "NEDParser._TitlePattern.search( line ) if m: title = m.group( 1 ).lower() # Now reading", "parseSFFromRedirectPages( self, msIndexFilePath, msDumpFilePath ): \"\"\" Extract surface form from redirect pages. We", "= [] linkDocuments = [] for chunk in rChunks: for doc in chunk:", "\"\"\" startTime = time.time() mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection", "in preparation for multiprocessing. chunks.append( documents ) if len( chunks ) == MAX_CHUNK_SIZE:", "relationships from wikilinks in valid entity pages. Skip processing disambiguation pages, lists, and", ") # Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\" ) def", "rChunks' lists of tuples into surface form dicts and linking dicts. sfDocuments =", "to: set{int, int, ..., int}}. \"\"\" print( \"[*] Updating ned_linking collection... \", end=\"\"", "record[\"_id\"] ) # Creating entry in output dict. if nDoc.get( surfaceForm ) is", "nDoc def initDBCollections( self ): \"\"\" Reset the DB collections to start afresh.", "to read all until EOF. requestId += 1 bz2File.seek( seekByte ) # Read", "os.listdir( fullDir ) # Get all files in current parsing directory, e.g. AA/wiki_00.bz2.", "have ALGOL and Algol... n = mEntity_ID.find( { \"e_l\": entity.lower() } ).count() if", "Wikilinks and update collections in DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks", "block of data. block = bz2File.read( -1 ) dData = bz2.decompress( block ).decode(", "# Iterate over surface forms in current dict. requests.append( pymongo.UpdateOne( { \"_id\": sf", "): \"\"\" Constructor. \"\"\" P.Parser.__init__( self ) # Defining connections to collections for", "documents ) if len( chunks ) == MAX_CHUNK_SIZE: self._extractAndProcessWikilinks( chunks ) # Extract", "pymongo from urllib.parse import unquote import html import sys from . import Parser", "chunks = [] MAX_CHUNK_SIZE = 20 for directory in directories: fullDir = extractedDir", "= pool.map( NEDParser._processMSBZ2Block, requests ) # Each block request tuple in its own", "len( requests ) == BATCH_SIZE: # Send lots of update requests. self._mNed_Dictionary.bulk_write( requests", "Treat disambiguation pages differently than regular valid pages. surfaceForm = \"\" isDisambiguation =", "file if os.path.isfile( fullFile ) and P.Parser._FilenamePattern.match( file ): # Read bz2 file", "and their corresponding entity mappings with a reference count. nSet = set() #", "\"processed\" ) requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining", "forms. if doc[1][\"to\"]: linkDocuments.append( doc[1] ) # Link information. # Update DB collections.", "entity name: case sensitive. record = mEntity_ID.find_one( { \"e\": entity }, projection={ \"_id\":", "invalid entity\", entity, file=sys.stderr ) # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" )", "line = line.strip() if not line: # Skip empty lines. continue if line", "= MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all requests in", "self._extractAndProcessWikilinks( chunks ) # Process remaining chunks of documents. endTotalTime = time.time() print(", "in \"/\". \"\"\" print( \"------- Creating surface forms and links from Wikilinks and", "redirect pages -------\" ) startTotalTime = time.time() startTime = time.time() blockRequests = []", "and another of the form {from:int, to: set{int, int, ..., int}}. \"\"\" mClient", ") as bz2File: with open( msIndexFilePath, \"r\", encoding=\"utf-8\" ) as indexFile: seekByte =", "with count = -1 to read all until EOF. requestId += 1 bz2File.seek(", "- startTime, \"secs\" ) blockRequests = [] startTime = time.time() seekByte = newSeekByte", "this block. mNED = mClient.ned mEntity_ID = mNED[\"entity_id\"] requestId = block[0] dData =", "current document points to, as long as current doc is a non-disambiguatio page.", "that current document points to, as long as current doc is a non-disambiguatio", "in lowercase. requests.append( pymongo.UpdateOne( { \"_id\": t[\"e_l\"] }, { \"$inc\": { \"m.\" +", "of document? skipLine = False title = None elif not skipLine: if not", "<reponame>imyoungmin/NED import importlib import bz2 import os import time import re from multiprocessing", "0 for sfDoc in sfDocuments: if not sfDoc: continue # Skip empty sf", "\"f.eId3\":True}, ..., \"eIdn\":{\"f.eId1\":True,...}} toFrom = {} for doc in linkDocuments: fId = \"f.\"", "external links to avoid false positives. for matchTuple in P.Parser._LinkPattern.findall( line ): entity", "block[1] # Obtain the title and redirect titles from read block. lines =", "modify the ned_linking collection in this function since redirect pages are only aliases", ") requests = [] if requests: self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests.", "multi-stream Wikipedia dump file. :param block: A tuple containing (requestId, string block of", "+= 1 bz2File.seek( seekByte ) # Read block of data. block = bz2File.read(", "= \"\" isDisambiguation = False m = P.Parser._DisambiguationPattern.match( doc[\"title\"] ) if m is", "if len( blockRequests ) == REQUESTS_BLOCK_COUNT: # Accumulate REQUESTS_BLOCK_COUNT requests for incremental parsing.", "and update collections in DB. chunks = [] if chunks: self._extractAndProcessWikilinks( chunks )", "from redirect pages. We don't modify the ned_linking collection in this function since", "\"requests sent!\" ) def _updateLinkingCollection( self, linkDocuments ): \"\"\" Add more link references", "import time import re from multiprocessing import Pool from pymongo import MongoClient import", "of extracted Wikipedia BZ2 files. :param extractedDir: Directory where the individual BZ2 files", ") # print( \"[***]\", doc[\"id\"], doc[\"title\"], \"... Done!\" ) result.append( ( nDoc, {", "m.group( 1 ).lower() # Now reading a <page>. Make title a lowercase surface", "doc in docs: nDoc = {} # This dict stores the surface forms", "print( \"[*]\", len( blockRequests ), \"request blocks starting at byte\", seekByte, \"parsed after\",", ") totalRequests += 1 if len( requests ) == BATCH_SIZE: # Send lots", "requests. print( \"[*]\", totalRequests, \"processed\" ) endTime = time.time() print( \"[!] Done after\",", "entities in DB. startTime = time.time() print( \"------- Creating surface forms from Wikipedia", "record: # Process only those entities existing in entity_id collection. eId = \"m.\"", "\"[*]\", totalRequests, \"processed\" ) endTime = time.time() print( \"[!] Done after\", endTime -", "\"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) # One single connection to rule all", "len( surfaceForm ) > 128: # Skip too long of a surface form.", "startTotalTime = time.time() startTime = time.time() blockRequests = [] # Accumulate blocks for", "for found entity in DB. # First check how many entities match the", "_parseMSBZ2BlockRequests( self, requests ): \"\"\" Read surface forms from blocks of Wikipedia documents", "{from:int, to: set{int, int, ..., int}}. \"\"\" mClient = MongoClient( \"mongodb://localhost:27017/\" ) #", "tuple containing (requestId, string block of data). :return: A dictionary of the form", "self._mNed_Dictionary.bulk_write( requests ) # Process remaining requests. print( \"Done with\", totalRequests, \"requests sent!\"", "self._mEntity_ID.count() # Retrieve number of entities in DB. startTime = time.time() print( \"-------", "surface forms from blocks of Wikipedia documents obtained from the BZ2 multi-stream dump", "collection. :param linkDocuments: A list of dicts of the form {from:int, to: set{int,", "\"secs.\" ) def parseSFsAndLsFromWikilinks( self, extractedDir ): \"\"\" Grab surface forms and link", "Detected\", nEntities, \"entities in entity_id collection\" ) requests = [] # We'll use", "0, 6 ) != -1: # Reached the body of the page? skipLine", "} ).count() if n == 1: # One match? Then retrieve entity ID.", "individual BZ2 files are located: must end in \"/\". \"\"\" print( \"------- Creating", "}, { \"$inc\": { \"m.\" + str( t[\"_id\"] ): +1 } }, upsert=True", "to ned_dictionary and ned_linking collections. :param chunks: A list of lists of extracted", "self._updateSurfaceFormsDictionary( sfDocuments ) @staticmethod def _processMSBZ2Block( block ): \"\"\" Read and process data", "{\"sf1\":{\"m.EID1\":int,..., \"m.EIDn\":int}, \"sf2\":{\"m.EID1\":int,..., \"m.EIDn\":int}, ...}. \"\"\" print( \"[*] Updating ned_dictionary collection... \", end=\"\"" ]
[]
[ "not os.path.exists(\"data\"): os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename", "full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in", "os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if", "os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename:", "os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\"", "if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\"", "if not os.path.exists(\"data\"): os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for", "= f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename:", "in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename: dest_file = f\"data/father/{filename}\" os.rename(full_filename,", "import os if not os.path.exists(\"data\"): os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"):", "if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename: dest_file =", "if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename", "f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename: dest_file", "os.path.exists(\"data\"): os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in", "filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename: dest_file = f\"data/father/{filename}\" os.rename(full_filename, dest_file)", "os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file", "not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename =", "\"About\" in filename: dest_file = f\"data/about/{filename}\" elif \"Father\" in filename: dest_file = f\"data/father/{filename}\"", "os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"):", "os if not os.path.exists(\"data\"): os.mkdir(\"data\") if not os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\")", "filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\"", "for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file =", "in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in filename: dest_file = f\"data/about/{filename}\" elif", "not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\" if \"About\" in", "os.path.exists(\"data/about\"): os.mkdir(\"data/about\") if not os.path.exists(\"data/father\"): os.mkdir(\"data/father\") for filename in os.listdir(\"raw_data\"): full_filename = f\"raw_data/{filename}\"" ]
[ "admin from shipment.models import Shipment # Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin):", "from django.contrib import admin from shipment.models import Shipment # Register your models here.", "shipment.models import Shipment # Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display =", "django.contrib import admin from shipment.models import Shipment # Register your models here. @admin.register(Shipment)", "# Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display = (\"name\", \"surname\", \"email\",", "from shipment.models import Shipment # Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display", "import Shipment # Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display = (\"name\",", "Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display = (\"name\", \"surname\", \"email\", \"phone\",\"city\",\"district\",\"neighborhood\",\"others\")", "import admin from shipment.models import Shipment # Register your models here. @admin.register(Shipment) class", "Shipment # Register your models here. @admin.register(Shipment) class ShipmentAdmin(admin.ModelAdmin): list_display = (\"name\", \"surname\"," ]
[ "KIND, either express or implied. # See the License for the specific language", "Unless required by applicable law or agreed to in writing, software # distributed", "18:59:53 +0200 (Fr, 18 Apr 2008) $\" import ho.pisa as pisa import os", "utf-8 -*- # Copyright 2010 <NAME>, h<EMAIL> # # Licensed under the Apache", "'\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{'", "def helloWorld(): filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf =", "in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\",", "getFileName if you like \"\"\" self.kw = kw self.tmpFileList = [] def __del__(self):", "'!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6'", "\\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d'", "they are not needed any more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw", "log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try: if \".\" in path: new_suffix", "\\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\", "self.tmpFileList = [] def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList = []", "# Copyright 2010 <NAME>, h<EMAIL> # # Licensed under the Apache License, Version", "this file except in compliance with the License. # You may obtain a", "(Fr, 18 Apr 2008) $\" import ho.pisa as pisa import os import logging", "'\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\", "+ path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath", "dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec'", "<p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not", "ANY KIND, either express or implied. # See the License for the specific", "'\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99", "\\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc", "None def helloWorld(): filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf", "'\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\", "lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img", "\\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\", "= new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here", "\\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\", "return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename =", "u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if", "%r\", path, relative, self.kw) try: if \".\" in path: new_suffix = \".\" +", "as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__ + \".pdf\" lc", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "\\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\", "\\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85'", "'\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\", "'\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\", "log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\",", "\\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\", "\\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5'", "18 Apr 2008) $\" import ho.pisa as pisa import os import logging log", "\\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`('", "' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "\".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\",", "'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\", "' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1'", "\\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5'", "specific language governing permissions and # limitations under the License. __version__ = \"$Revision:", "os import logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\", "'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\", "'\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1", "\\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\", "\".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p>", "OF ANY KIND, either express or implied. # See the License for the", "\\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\", "logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3'", "The self.kw could be used in getFileName if you like \"\"\" self.kw =", "track additional informations and handle temporary files after they are not needed any", "'\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96'", "'$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\", "the License. __version__ = \"$Revision: 194 $\" __author__ = \"$Author: holtwick $\" __date__", "= logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\", "handle temporary files after they are not needed any more. \"\"\" def __init__(self,", "suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: #", "'\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\", "'\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f '", "'\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11", "'\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\", "object is just a wrapper to track additional informations and handle temporary files", "' class myLinkLoader: \"\"\" This object is just a wrapper to track additional", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "self.tmpFileList = [] def getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r", "\\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{'", "temporary files after they are not needed any more. \"\"\" def __init__(self, **kw):", "__init__(self, **kw): \"\"\" The self.kw could be used in getFileName if you like", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "\\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\", "' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,'", "# limitations under the License. __version__ = \"$Revision: 194 $\" __author__ = \"$Author:", "\\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU '", "= [] def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def", "'\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 '", "\"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging() helloWorld()", "\\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD'", "\\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,'", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s('", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# -*- coding: utf-8 -*- # Copyright 2010 <NAME>, h<EMAIL> # # Licensed", "language governing permissions and # limitations under the License. __version__ = \"$Revision: 194", "'\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC'", "__del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None):", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try: if \".\" in", "governing permissions and # limitations under the License. __version__ = \"$Revision: 194 $\"", "import os import logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{'", "required by applicable law or agreed to in writing, software # distributed under", "'\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe'", "myLinkLoader: \"\"\" This object is just a wrapper to track additional informations and", "applicable law or agreed to in writing, software # distributed under the License", "logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\", "\\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88'", "and handle temporary files after they are not needed any more. \"\"\" def", "under the License. __version__ = \"$Revision: 194 $\" __author__ = \"$Author: holtwick $\"", "'\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\", "= myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\">", "or agreed to in writing, software # distributed under the License is distributed", "\\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17'", "try: if \".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in", "finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def", "as pisa import os import logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00'", "file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging()", "# Here you may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "\"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\" import ho.pisa as pisa", "\\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d('", "\\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU", "'\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6'", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "writing, software # distributed under the License is distributed on an \"AS IS\"", "def getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path,", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "are not needed any more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw could", "License. # You may obtain a copy of the License at # #", "'\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\", "'\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t'", "'>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class", "used in getFileName if you like \"\"\" self.kw = kw self.tmpFileList = []", "'\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\", "like \"\"\" self.kw = kw self.tmpFileList = [] def __del__(self): for path in", "\\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\", "'\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E'", "\\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\", "compliance with the License. # You may obtain a copy of the License", "holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\"", "own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\")", "\"wb\") try: # Here you may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close()", "\\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "after they are not needed any more. \"\"\" def __init__(self, **kw): \"\"\" The", "\"\"\" self.kw = kw self.tmpFileList = [] def __del__(self): for path in self.tmpFileList:", "filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\"", "helloWorld(): filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF(", "'\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\"", "\".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix", "new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here you", "'\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\", "2008) $\" import ho.pisa as pisa import os import logging log = logging.getLogger(__file__)", "def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\", "may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception", "tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None", "*\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R'", "not use this file except in compliance with the License. # You may", "\\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\", "2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\" import ho.pisa as pisa import", "'\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\", "the specific language governing permissions and # limitations under the License. __version__ =", "'\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7'", "def __init__(self, **kw): \"\"\" The self.kw could be used in getFileName if you", "\\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0'", "License, Version 2.0 (the \"License\"); # you may not use this file except", "'\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83'", "self.kw could be used in getFileName if you like \"\"\" self.kw = kw", "additional informations and handle temporary files after they are not needed any more.", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "'\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\", "'+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k'", "# you may not use this file except in compliance with the License.", "'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01('", "agreed to in writing, software # distributed under the License is distributed on", "'\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R('", "\\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\", "(the \"License\"); # you may not use this file except in compliance with", "\\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\", "\\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\", "\\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{'", "pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, )", "<NAME>, h<EMAIL> # # Licensed under the Apache License, Version 2.0 (the \"License\");", "\\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\", "# Unless required by applicable law or agreed to in writing, software #", "'\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\", "by applicable law or agreed to in writing, software # distributed under the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath =", "for the specific language governing permissions and # limitations under the License. __version__", "'\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\", "\\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\", "relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try:", "stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return", "pisa import os import logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\", "if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging() helloWorld() # print repr(open(\"img/denker.png\",", "'\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU '", "'\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6['", "'\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\", "\\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\", "%r %r\", path, relative, self.kw) try: if \".\" in path: new_suffix = \".\"", "file except in compliance with the License. # You may obtain a copy", "\\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\", "' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is just", "\\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\", "= \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\" import ho.pisa as", "'\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\", "C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\", "\\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E'", "License for the specific language governing permissions and # limitations under the License.", "'\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5'", "permissions and # limitations under the License. __version__ = \"$Revision: 194 $\" __author__", "'\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde('", "to in writing, software # distributed under the License is distributed on an", "'\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU", "\\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d'", "\\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\", "add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as", "'\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7'", "implied. # See the License for the specific language governing permissions and #", "= kw self.tmpFileList = [] def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList", "\"License\"); # you may not use this file except in compliance with the", "\\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f'", "'\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf'", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__", "not needed any more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw could be", "\\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\", "return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\", "path, relative, self.kw) try: if \".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower()", "\\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z['", "= \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix =", "path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw)", "self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename", "src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__ ==", "or implied. # See the License for the specific language governing permissions and", "'\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({'", "\\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87'", "\"\"\" This object is just a wrapper to track additional informations and handle", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "\\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4'", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "import ho.pisa as pisa import os import logging log = logging.getLogger(__file__) def dummyLoader(name):", "+0200 (Fr, 18 Apr 2008) $\" import ho.pisa as pisa import os import", "'\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18('", "import logging log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00'", "return None def helloWorld(): filename = __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName", "\"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008)", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "'\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1'", "tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try: if \".\" in path:", "\\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f", "getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative,", "\"\"\" def __init__(self, **kw): \"\"\" The self.kw could be used in getFileName if", "\\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01'", "path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None): import os", "[] def getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\",", "\\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15'", "needed any more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw could be used", "you may not use this file except in compliance with the License. #", "\\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12('", "except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__ +", "you like \"\"\" self.kw = kw self.tmpFileList = [] def __del__(self): for path", "'\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\", "'\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\", "use this file except in compliance with the License. # You may obtain", "not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging() helloWorld() # print repr(open(\"img/denker.png\", \"rb\").read())", "class myLinkLoader: \"\"\" This object is just a wrapper to track additional informations", "\"\"\" The self.kw could be used in getFileName if you like \"\"\" self.kw", ") if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging() helloWorld() # print", "'\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8'", "<img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__", "\\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\", "'\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc", "'8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\", "__file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello", "Here you may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath", "e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__ + \".pdf\" lc =", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "\\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\", "'\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99'", "__author__ = \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18", "\".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath,", "\\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU'", "\".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try:", "'\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\", "\"$Revision: 194 $\" __author__ = \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53", "\\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89'", "\\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is just a", "\\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\", "\\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\", "tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld():", "2.0 (the \"License\"); # you may not use this file except in compliance", "'\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7'", "\".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\")", "\\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\", "\\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf'", "'\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\", "\"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\":", "\\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\", "\\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\", "'\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\", "in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None): import os import", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "'\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde(", "'\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB'", "<strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename)", "import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try: if", "'\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is just a wrapper to track", "\\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 '", "__date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\" import ho.pisa", "# # Unless required by applicable law or agreed to in writing, software", "os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName:", "express or implied. # See the License for the specific language governing permissions", "'\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i'", "\\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01('", "$\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr 2008) $\" import", "be used in getFileName if you like \"\"\" self.kw = kw self.tmpFileList =", "either express or implied. # See the License for the specific language governing", "194 $\" __author__ = \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200", "\\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 '", "\\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc '", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "-*- # Copyright 2010 <NAME>, h<EMAIL> # # Licensed under the Apache License,", "\\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\", "\\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\ 'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh('", "'\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\", "'\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8'", "\\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5'", "'X*\\xf5UQL-\\xf5>\\x18\\xce\\x8c$\\x99\\xc0\\x98\\x12\\xa4tJ\\xbd\\xac\\xeb<\\x1bX\\xcd\\x1d{w\\xf2\\xae\\x1d\\xfeI\\x94,' \\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\", "to track additional informations and handle temporary files after they are not needed", "'\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C['", "**kw): \"\"\" The self.kw could be used in getFileName if you like \"\"\"", "\\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader:", "if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\",", "\\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object", "\\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\", "file(tmpPath, \"wb\") try: # Here you may add your own stuff tmpFile.write(dummyLoader(path)) finally:", "the License. # You may obtain a copy of the License at #", "\\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2['", "suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here you may add your own", "'><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I('", "\\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88('", "coding: utf-8 -*- # Copyright 2010 <NAME>, h<EMAIL> # # Licensed under the", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "+ \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong>", "' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@", "\\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\", "\\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "self.kw) try: if \".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix", "myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\",", "\\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2'", "you may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except", "'\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\", "\\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\", "'\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7'", "for path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None): import", "%r %r %r\", path, relative, self.kw) try: if \".\" in path: new_suffix =", "' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1'", "$\" import ho.pisa as pisa import os import logging log = logging.getLogger(__file__) def", "in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile", "2010 <NAME>, h<EMAIL> # # Licensed under the Apache License, Version 2.0 (the", "\\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is just a wrapper to", "wrapper to track additional informations and handle temporary files after they are not", "with the License. # You may obtain a copy of the License at", "__version__ = \"$Revision: 194 $\" __author__ = \"$Author: holtwick $\" __date__ = \"$Date:", "log = logging.getLogger(__file__) def dummyLoader(name): return '\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR\\x00\\x00\\x00F\\x00\\x00\\x00\\x89\\x04\\x03\\x00\\x00\\x00c\\xbeS\\xd6\\x00\\x00' \\ '\\x000PLTE\\x00\\x00\\x00\\n\\x06\\x04\\x18\\x14\\x0f-&\\x1eLB6w`E\\x8f\\x80q\\xb2\\x9c\\x82\\xbe\\xa1{' \\ '\\xc7\\xb0\\x96\\xd1\\xbd\\xa9\\xd9\\xd0\\xc6\\xef\\xeb\\xe6\\xf8\\xf3\\xef\\xff\\xfb\\xf7\\xff\\xff\\xffZ\\x83\\x0b|\\x00\\x00' \\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8'", "\\ 'q\\xa6\\xa3\\x04\\n\\xebJ\\x00\\x97.\\xcc\\xeb\\xb4\\n\\xf0>2|d%\\x12\\xfbI\\xbe\\'\\x94\\xecp\\x9d@j]q\\x0f\\x8d\\xd3\\x9a?\\xa6' \\ '\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,'", "just a wrapper to track additional informations and handle temporary files after they", "\\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\", "# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you", "\\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\", "'\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\", "'\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\ '\\x1a?{\\x84[D\\xa4\\x01u\\x8a\\xbf\\xf6T\\x1e\\xb83\\xce\\x04\\xbd\\xa6\\xaa\\xcd\\xaf}\\x88\\xe7:?L\\xb5\\xfcM\\'\\x1b`(' \\", "\\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5'", "tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here you may add your", "if \".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\",", "\\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{'", "a wrapper to track additional informations and handle temporary files after they are", "law or agreed to in writing, software # distributed under the License is", "the License for the specific language governing permissions and # limitations under the", "self.kw = kw self.tmpFileList = [] def __del__(self): for path in self.tmpFileList: os.remove(path)", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "\\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95", "\\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\", "relative, self.kw) try: if \".\" in path: new_suffix = \".\" + path.split(\".\")[-1].lower() if", "[] def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self,", "'\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is", "\\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\", "and # limitations under the License. __version__ = \"$Revision: 194 $\" __author__ =", "'^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\", "'?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\", "\\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\", "\\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\", "(\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile =", "'\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88['", "'\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f(' \\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 '", "'\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb'", "!\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "= __file__ + \".pdf\" lc = myLinkLoader(database=\"some_name\", port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p>", "h<EMAIL> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #", "\\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\", "path: new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"):", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "'\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\ '\\xfe\\x98u\\x9e\\xf5\\xf3_\\x1eB\\xd2U\\x00\\x9a\\xf3\\xc9\\xc92\\xb9\\xbc\\xbc\\xec\\x93N?:\\xce\\xd59\\xect\\xdb\\xec_\\xbdC' \\ '\\xa4\\x1f\\x99\\xb9\\x81\\x97\\xddj\\xb9g\\x8c\\xf4\\xaf\\xe8\\x8f\\xba\\xc8\\x1cwy\\xbb\\xd3\\xb8\\xab.\\xfb\\x0bU\\xd03S\\xa2' \\ '\\xac\\x96\\x03k\\xe1\\x02\\xe4\\x19\\xbe\\x12N\\xcc|3<U\\xd8O\\x02\\xd4iQ\\x12\\\\j\\x81R\\x80\\xbd\\x14\\x16\\xed\\x88\\xc1' \\ '\\xfavw&\\x02isj\\xa2\\xa9\\xd1\\x12\\x91\\xc4\\xfe$\\xa5\\xe1\\xbc\\xf2f\\xbbs\\xcc ' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\", "\\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e'", "= \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr, 18 Apr", "\\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,'", "Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err:", "tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here you may", "\\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08'", "See the License for the specific language governing permissions and # limitations under", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "'\\x1b\\x00\\xef\\x11I\\xe0\\xbb\\x91\\xb8\\xa6wj\\xd3\\xc1 \\xcf\\xf5sY\\xcdM\\x11\\x12(' \\ '\\x94\\x88\\\\\\xb1>K\\xbf\\xe7\\x91\\x88\\xc8\\xb5\\xdc\\xc9\\xd0\\xb5\\xec\\x99\\xb78\\xf3\\xebS\\xaa\\x8a\\x03\\x88\\x8c\\x87' \\ '\\\\\\xf8\\xf4\\xfe\\xcc5\\xb4\\x83\\x86\\x029\\xf7\\xd4\\xe9\\x9b\\xa1\\xa5/\\xb9\\x9f\\xff\\x15#jbh(' \\ '\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\", "'\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\", "\\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d'", "'\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,' \\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_'", "informations and handle temporary files after they are not needed any more. \"\"\"", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "'\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0'", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "\\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\", "'\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\", "'\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\", "self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path, relative=None): import os import tempfile", "try: # Here you may add your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath)", "'\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\ '\\x7fscD\\x92\\x17&W\\x1e\\xde\\xd3J\\xaf\\xd8\\x0c\\xad\\xd8\\x14\\xbe\\x03C_T\\xf3\\xf9\\\\\\xe2eB\\xdc\\xb1\\x84F\\xf5\\xf0' \\", "\\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\ 'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82", "any more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw could be used in", "'\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85'", "\\ '>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 '", "'\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,' \\ '\\xe4\\x16]Q\\xd08s\\xd8\\xde\\xc5=\\xd0\\x040\\xa0\\x01e\\x1f\\x8e\\xab\\xcd\\x90Hr\\xdd\\xf4yS\\xb0\\xc5\\x99\\xc71\\x04@\\xdf' \\ '\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8", "\\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\", "'J4\\xb5\\x7f\\xab\\x85D\\x8b\\xffr\\xf6<{\\xb8\\x1d\\x0e\\xf9\\xa9\\x13\\xb0GnZ\\xd6/Z\\xfc%\\xb3\\x99\\xae\\xcd0f\\xe1c\\x1e' \\ '\\x9f\\r\\r\\x05\\xad\\x16{&\\x10\\xc0\\xf8?Z\\n\\xf1+\\xfb\\x81\\xd5F\\x00\\x00\\x00\\x00IEND\\xaeB`\\x82 ' class myLinkLoader: \"\"\" This object is just a wrapper", "more. \"\"\" def __init__(self, **kw): \"\"\" The self.kw could be used in getFileName", "\\ 'kiKFF\\xc1\\x91\\xc5m\\x88\\xcc!{2\\x08\\xb4\\xe4\\x11\\'\\x00sU\\xeb\\xc5\\xd9fx\\xa6&\\xd3r\\x02\\'Q|\\xb3c3\\x87\\xed\\xbbP_' \\ '#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\", "= tempfile.mktemp(prefix=\"pisa-\", suffix=suffix) tmpFile = file(tmpPath, \"wb\") try: # Here you may add", "tmpFile = file(tmpPath, \"wb\") try: # Here you may add your own stuff", "if you like \"\"\" self.kw = kw self.tmpFileList = [] def __del__(self): for", "$\" __author__ = \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18 18:59:53 +0200 (Fr,", "\\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\ '\\x84\\xf7g\\xfcP\\xc7L\\x8c\\xdf\\xa9\\xf0\\xa2\\xffUQ\\x08\\xa4\\xce\\xe6|$\\x91\\x95U5\\xf8\\x08\\x99\\xae\\xc3`\\x8f\\x99' \\ '\\x94*\\x828\\x91\\x11p\\x80\\x06}\\xe2)\\xf5\\xd2@^M\\x7f\\x88\\x9e\\x9f\\xea\\xd4)\\x9d#\\xe2BV\\x10\\x02\\xd9~\\\\\\x18\\xd7' \\ '\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea'", "\\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\", "\\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\", "Version 2.0 (the \"License\"); # you may not use this file except in", "except in compliance with the License. # You may obtain a copy of", "Exception as e: log.exception(\"myLinkLoader.getFileName\") return None def helloWorld(): filename = __file__ + \".pdf\"", "'\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\", "'\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2'", "is just a wrapper to track additional informations and handle temporary files after", "could be used in getFileName if you like \"\"\" self.kw = kw self.tmpFileList", "'\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\ '\\x04\\x9a\\xed\\xd9\\xc8j\\xb0\\x1f\\xa6\\xd4X\"\\xeei0\\xd6\\n\\xea\\x01g\\xday\\x8dB=~\\x06\\x1d\\x95zV\\xb7\\xab`\\xea\\x1aB' \\ '\\xba\\xc9\\x1d\\x06\\xdf\\xb6\\xeb\\xf3\\x9b\\n4\\xf9N\\xd8\\xc6c(Y\\xb3\\x02{\\xf3\\x0f\\n\\x15@\\xc3\\x18\\xfeN\\xd7f('", "-*- coding: utf-8 -*- # Copyright 2010 <NAME>, h<EMAIL> # # Licensed under", "\\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01' \\ '\\xd6\\xf0H\\xd8\\xc7DNfM:\\xd7sF\\x9d\\x12\\xe5\\x1f?\\xcb\\x8c\\xa2K\\x91\\xb8\\xe6DI\\x94\\xd3\\xa3Z\\x9ex\\x83\\x81\\xb1' \\", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "'\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{'", "files after they are not needed any more. \"\"\" def __init__(self, **kw): \"\"\"", "\\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3' \\", "os import tempfile log.info(\"myLinkLoader.getFileName: %r %r %r\", path, relative, self.kw) try: if \".\"", "\\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\" *\\xca\\xc6\\x80Ik\\xbe\\xf0\\x02\\xd4s\\x8f\\xb8\\x9fo|\\xbd\\x83\\xda\\x80+\\xc7\\xdbPD' \\ '\\x10\\x8f\\xf8\\xc2B?\\xadlD\\x8b\\x00\\x943]\\xf6?\\xa9\\xfe\\x1e\\xdc\\xd6\\x83\\x08\\t\\xbc\\x00\\xc3\\x8aH\\xd2\\xfd\\x85' \\ '\\x8a_\\x1b?a~\\xb4\\xb0\\x99\\xf1-g\\xfc\\x86\\x11\\x1a\\x1a:\\xd7G\\x00\\xce\\x8b\\xbd\\xef\\x176a\\xed\\xb5f\\xb3\\x9e{' \\ '\\x9b\\xe7\\xda\\xbde\\xc1^h\\x1cj\\x97s*\\xc69\\x80]B2\\x05]\\xcb.\\x00\\xd4\\xcb\\xafs\\x9d\\xfb\\xef\\xe0\\x90\\xefG\\r\\x8d' \\ '\\xaa\\xe10\\x9aA\\x8eH\\xee\\x02-\\xab^\\x00\\xd3f\\xba\\xbb\\xc6\\xa7V\\xb3\\xa9Uu]\\xcf\\x86\\xb1\\xda\\xf6\\x8c\\xbe\\x90,'", "<p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"), link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if", "'\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89('", "your own stuff tmpFile.write(dummyLoader(path)) finally: tmpFile.close() self.tmpFileList.append(tmpPath) return tmpPath except Exception as e:", "= [] def getFileName(self, path, relative=None): import os import tempfile log.info(\"myLinkLoader.getFileName: %r %r", "\\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9 ' \\ '\\x13\\x9e1\\xc2\\x13\\xb5\\xfeN\\rn\\xa5\\xd5a\\xc5+\\xe7\\xb7\\xf5\\xa2\\xcbC\\xde>a\\x9c\\xd2\\xb5\\xad\\x07\\xdbS\\x0b\\xb0' \\ '\\xa5z\\xeb\\x94\\xd2y\\x80kD\\xee<e\\x10h\\x7fs]\\xf4g\\xa7\\x01\\xb6\\x12\\x91z\\xa9P\\x8a\\\\\\xcfg\\xfdQ\\xf6\\x0c\\x83' \\ '\\xb1CD?\\x05\\x80\\xf2\\xa4;z)\\xb8\\x11\\xf1\\x11\\xf7\\xe5\\x8b\\x9d\\xff\\xcf\\\\\\x92H\\x846\\x80f\\x91Ys/\\x11\\xe2r\\x85' \\", "\\ '\\x0c\\xedIDATx^u\\x97]l\\x1bWv\\xc7g\\xe2`\\x81\\xbe\\xcd%Gr\\xd3\\xa7P\\x12e\\xb7\\x01\\x8a\\xd0\")E\\x01\\x02\\x8f\\xf8' \\ '!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\", "'\\x92\\xc6\\x06\\t6\\xe6.\\xfb\\xb1\\xc4\\xfdb\\x8fV\\xf2\\x89\\xa2\\x1c\\xb9\\xd2\\xe6\\xcc\\x93\\xc9\\x80\\x8a\\x81\\xf5\\xc5d' \\ '\\xd5D\\xed\\x0f\\xefr\\xdd\\x0b\\xb4<\\x89\\xae\\xc8\\x15\\xc6\\x84\\x0e\\xeb~\\x16Bh\\x8a\\xa8\\xe5\\xb0+Y\\xd9\\xdc\\x9b\\xb5,' \\ 'S!7hi\\nG\\x92\\x1cp\\xe6\\xf0\\xb7\\x1fo\\xf7\\xf5\\xf5\\xbdL\\x06K\\x02\\xb9P\\x9d\\xd8\\xbbeY;\\xa4\\x07\\xef,' \\ '!\\x89\\xd2\\xe9N\\xf7\\x10\\x99v\\x13\\xee\\xa0K\\xd2[' \\ '\"nZ\\x81M\\xec\\xab;\\x9e42\\x93\\x82$\\xbe\\xd29\\xe4\\xcc\\x93\\x18lp\\xd5`\\x89\\x04\\x0bU\\x98Z\\xb1\\x9a\\xfex\\x9a\\x96' \\ '\\xf9\\xfa#\\xb79\\xc3\\xba\\xc8\\x94\\xf9|\\xde(' \\ '\\x91\\xe84@\\xb2a}\\x9c\\x0c\\xdb\\xa9\\x04\\xe1\\xd4#\\x9ba\\xc8`k\\x89\\xb2^\"\\x91\\n\\xec\\xa7,'", "in getFileName if you like \"\"\" self.kw = kw self.tmpFileList = [] def", "new_suffix = \".\" + path.split(\".\")[-1].lower() if new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix", "License. __version__ = \"$Revision: 194 $\" __author__ = \"$Author: holtwick $\" __date__ =", "kw self.tmpFileList = [] def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList =", "This object is just a wrapper to track additional informations and handle temporary", "\\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\ '\\xb1V\\x8b\\xbe\\xa2\\x06\\xc5\\x15(\\xf1\\x9b?\\xb4\\x99\\xaf\\x00\\x80\\xc6\\xdd)\\xc8\\x12B\\xfc\\xcd\\n\\xad\\x14s\\xbay\\x15' \\ '\\'|\\x98\\xb1\\x13\\x1d\\x03h$U\\x1b?\\'\\x86C\\xa4\\x01\\x94\\xee\\x8e\\xe8p\\x15\\x1b8\\x8c\\xd7\\xeax\\xfe\\xeaF\\xb5^\\xd1k' \\ '\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\", "'\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8 !\\xcf\\xe1\\x83\\x0b\\xc6\\x9d+\\\\\\x87u;\\xedl\\xdc{' \\ '^\\x12\\x05\\x89$\\x0b\\xd40\\xef\\x12\\tu\\xd2\\x99!\\xec\\xc4\\xab\\x17\\x8f\\x98\\xc7/\\xc6\\x07\\xc6$;\\xc1YZ\\xd1+\\n\\x11E' \\ '\\x12\\xa0\\xe0\\x1b\\x18G\\xd3\\x0e\\xf3\\xb57\\xeeN\\xbc,\\x89\\xa2@z\\xd0\\x12]\\xc34C\\x11d\\xbct\\x809\\x0c\\xfbU ' \\ 'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b'", "'1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,' \\ '8AjA\\x1d\\x1b-S\\x98Ly\\xe4\\xe4m\\xe7\\xec-\\xe6WU\\x82%\\x94\\x1cF\\xed\\xa1Uk/\\xa2\\xb9\\xb3\\xe4T\\xee\\r\\xf6[' \\ 'dZ-\\x16@F\\xc2{w\\x92\\x05C#\\xd4\\x1a\\x1f\\xae\\xcbe\\x8f\\xff\\\\\\xaf\\xe3\\xa7\\xfd\\xf5\\xd9\\xb2:\\x89wu\\x14\\xb2\\xe2' \\ '\\xbeqO_\\xa9\\x0f\\xaf\\xfb\\xfa\\x06\\xe7\\xae\\xb4m?\\xff\\xdc[\\x8a\\xa8\\xca1$\\x8a!\\xf2Zc\\x13\\xea\\x17\\xd6\\\\I(' \\ '\\xcd\\xb4\\x84\\xeea\\x9b}\\xe4\\xce\\x8f\\x85\\x13\\xce\\x8d\\x89\\xc8HR\\x10\\xb2P\\xa7\\x19w\\x0c\\xf6\\x93\\xbf\\xe4L\\xeb' \\ '\\x12\\x89\\x95\\\\\\x11\\xc5\\xbe1\"", "port=666).getFileName pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename,", "= \"$Revision: 194 $\" __author__ = \"$Author: holtwick $\" __date__ = \"$Date: 2008-04-18", "'#d\\xc6\\x98\\x93\\xd3\\xd5\\xd5\\xc0\\xec\\xc3\\x01(' \\ '\\xcbeu\\n\\x19r\\x91ul\\xa6\\xb3\\x07u\\xac\\xde\\xeeK\\x97\\x08\\xf6Vpv\\'\\x06\\xef\\x8e\\xe4T\\x85\\x88\\x92\\xcc\\x1c\\xa6' \\ '\\xcb\\x90YC\\xe6\\xb4B\\xc2!wa=\\x07\\xf5w\\xc7U,\\x0e\\x91\\xfe\\xa4\\xd5:a\\xcc\\xb2O\\xde\\xed%\\x18=t{' \\ '\\x06\\xb4w\\x83\\t\\x9f\\x84%\\xfbY\\xf7(\\x17\\xdbY\\x00\\xaa\\xc8\\xbbI>\\xea\\x11\\xdee\\x9a\\x12T\\xb0b\\xe2\\xf7\\x0eP\\xc7' \\ '\\xf1|\\x9f3$Q\\xe4\\xdb9J\\rd\\xce\\xe5}\\x9c\\xf9\\xb36;\\xd6\\xb9?\\x83\\x8c\\x18\\xbe\\x86\\x0c\\x19__\\x01s\\xcd\\xbd\\xf8' \\ '\\x02\\xf6*\\x16\\x87\\xb5\\x8f\\xfc\\xd8:b\\xe2\\x9a$H\\xaedy\\x01\\xccLOv@\\xb2\\xdb\\x82u\\x1d\\xa6\\xbd\\xb3b3s(' \\ '\\xe3N\\xa1\\x9fm_$\\x11\\x97D^c\\xac\\xa0\\xe3g\\x0f\\x00\\xeb<4\\x87\\x1f\\x95SK\\xbcX\\xc3XA\\xe9-4s\\xc4t\\x9f\\xf8\\x01'", "def __del__(self): for path in self.tmpFileList: os.remove(path) self.tmpFileList = [] def getFileName(self, path,", "= file(tmpPath, \"wb\") try: # Here you may add your own stuff tmpFile.write(dummyLoader(path))", "\\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\ '\\xffT\\x9a\\x99\\xc8\\x0co\\xf5\\xf5\\x05g\\xad\\xda\\x0fX\\xeb\\xa4\\xceqQ\\x10$\\xb1\\xb7\\xd2@\\xa86x\\x7f8>h._\\x9dh4\\x8d' \\ '\\xa7:\\x8f#X\\x13At\\xdb3nF\\xee\\xc8\\x19wV^\\xf4\\x1b\\xd6\\xdc\\xed\\x13\\xe6w\\x01I\\x90\\x90\\xa1F\\x05\\x99\\xdc}B\\x88(' \\ '\\x87}\\xb7\\xac\\xda\\x99\\x13\\xe6\\xa7\\xa1\\xf3\\x02fs\\xa5)\\xbd\\xd70\\r\\xceH\"\\x91\\xc2\\x15\\xc8\\x1e\\x9f\\xbd\\xbd\\x17' \\ '\\xf7\\x8b\\x04m\\x07\\xd2\\xb4\\x02\\xc8", "'>\\xc0\\x9e\\xbf3\\x0e\\x1a\\xda\\xd2\\xa1\\xe6\\xc9O\\xa0\\xa8\\x81H\\xeeb\\xdb\\xd6\\xf9G.\\x0c\\xb0zU\\x9e\\x81\\xcd\\xdf7' \\ '\\x00\\x96<\\xde( \\xab\\xd1l\\xe0\\xc0\\xe9\\xc3\\x8f\\x90G\\xa9\\xf8\\xc6\\xbc\\x1fv\\xe5J\\xb5\\xba\\xd9#\\'\\x81K\\xaf\\xc5' \\ '>hu\\xed>\\xfc)\\xe5a\\x8cm\\xc2F\\xcc\\x1cZ\\xde\\xdc\\x9f\\x0ef\\xd1\\xf8:-\\xfd\\xd5\\x01;\\xea\\xc3S\\xd4\\x8e\\xdd\\xe5' \\ '\\x19\\x80\\x86\\x8fd\\xca\\x13\\xd1\\x1e\\xa3\\x9e\\x0fEX\\x1b\\x7f\\x1c\\x1dU-\\xd8\\xd9F5t\\x95 ' \\ '\\xa1\\xa5\\x89\\xa8:\\xddTg\\xf9N\\xc5\\xc9\\xb1\\x99\\xc7J\\xc4\\x16\\x9a\\xd6\\xd0\\x95\\x99 ' \\", "limitations under the License. __version__ = \"$Revision: 194 $\" __author__ = \"$Author: holtwick", "link_callback=lc, ) if not pdf.err: pisa.startViewer(filename) if __name__ == \"__main__\": pisa.showLogging() helloWorld() #", "\\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\", "' \\ '\\xc2\\xb2\\xc6\\xcd\\xec\\xe8\\xfe\\xa2\\x05\\xb4F$A\\x0c\\x94\\n\\xee\\x9b\\xc5\\xec_\\xb3\\xa7\\x0c\\xfb\\xf7q\\xad\\xb2\\xb6b5' \\ '?h\\xea\\xe6$\\x11\\t\\xe9\\xebs\\r\\xbdv\\xf5\\xf6\\t\\xd3a\\xec#5\\xb8\\x9c\\x08\\xdf\\xb4\\xc0J\\xc1\\x9a$\\x11\\x7f8\\x1c\\x01' \\ '\\xb8\\xf4\\x17\\xec\\xb0s\\xe29\\x93\\x18\\x08\\xa5\\xcc\\xa4eA\\xaep\\xd7#\\xca\\xa0\\xeb\\xd7o\\xd5\\x8a\\xb7\\x19;a:.\\x1f' \\ '\\x11\\xdd7\\x1b8R\\xcb\\x83\\xf5\\xac<\\xbf\\x1e.,\\xce~<\\xff\\xe3N\\x9b\\x1d3m\\x0f\\xea\\x8b\\x85{' \\ '\\xd6\\xa7\\xd6\\xc3\\xf8e}\\xd9\\xdc C\\xd1\\xd9f\\xfe\\x9d\\x16;f\\xba\\x7f/\\x12A\\x10\\xce\\xe2\\x88[' \\", "'!\\x8bI\\x17\\x10\\xc5!))5`\\xf1C\\xb4\\xb25`S\\xb2l\\xb95\\x90H\\xa4.\\xb9/u$K3\\xe3\\xa2\\x80W\\x12\\xc59L\\xf6a\\xb3' \\ '\\x8dcN\\xd6@\\xb7\\x1f\\x01\\x8a\\x85\\x16\\x9b-\\xfa\\x81M\\xb8@\\x83l\\xd1\\xd8\\xbc|)\\xd0\\x97\\x82\\xea\\xb93\\x92\\xec' \\ '\"\\xce\\x11 \\t3?\\xfe\\xcf\\xff\\x9e{\\xce\\x01(' \\ '\\x1c>7\\x18\\xfb\\xc2\\xfaE\\xffk_\\xb6\\x18\\xeb\\x1e>\\x8f\\xe92d\\xfe%T\\xa8\\x98\\xfa\\x07\\x1f ' \\ '$<\\x0f\\xe1\\x91\\xabT\\xc1\\xacT\\xf2\\xbfd\\xec\\xbb\\x98\\xdfM\\xeb\\x86aYP\\xfa\\xd3\\xd6\\xf3\\x98C[' \\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98'", "Copyright 2010 <NAME>, h<EMAIL> # # Licensed under the Apache License, Version 2.0", "'\\xc7\\x92TM\\xbf\\xdd:a\\x0e\\xbf\\x18EfU ' \\ '+\\x8b\\xc8d\\xb0\\xbe\\xc1\\xa4/J\\xf37^G\\xe4X\\xe7q\\xcc\\x04Z&\\xc2K\\x0eC\\\\Y\\x1a\\xb8`,' \\ '\\x9a\\xb7Z\\xad\\xa7\\xb9Fu\\x13u\\xa4\\x97\\xb26#}\\xcfK#\\xd4\\xd85W\\xdb\\xec\\x19\\xc6\\x00\\r\\xeb\\xfaR\\xc9a\\xc6F\\xea' \\ '\\xab\\x9aQ\\x87U\\xf6\\x8cN\\x0c\\x1a\\xday\"\\xfe\\x9e\\xc3\\x90k#\\xf52gJWX\\x17\\xef\\xeb\\x98\\x01\\x9a\\xc7\\xfa\\x95\\x88' \\ '\\xcd\\xcc\\x05\\xa3U\\xce\\xd4\\xdf\\xc0+\\xed:3\\xf8x\\x14\\x99u\\t\\xbd\\x12\\x11\\x19W1\\xd0c\\xd8\\x8c\\xcaX\\x8b9\\xf3\\xf5' \\ '\\x1f1\\xa8\\xd3UIt\\xe1p\\xb8\\xb3~Z\\xf1\\x91\\r\\xcd\\xa85\\xcc\\xdc\\x01k\\x1f33\\x00\\xda\\xaa\\xe4\\x0e/\\x12\\x89\\xa4' \\", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "pdf = pisa.CreatePDF( u\"\"\" <p> Hello <strong>World</strong> <p> <img src=\"apath/some.png\"> \"\"\", file(filename, \"wb\"),", "\\ '\\xa6\\xaaU\\xa1a5\\xe9\\x1b\\xad\\xef\\xd0i}\\x91\\xccy+\\xc8X\\xf5E\\xf6]:\\xff0\\xd8\\x97\\xce7\\xb9P\\xf1\\xd1\\xb7\\x98' \\ '\\xaec\\xe7/\\xd3\\xa1\\xeb\\x81{\\x96e5\\xd7.\\xb6\\x85\\xe7\\x99aO\\x94\\xf1R(' \\ '\\xfeC\\xce\\xd4F\\xbf\\xc50\\x1b\\xfa\\xefS\\xa9\\xb2\\x12p\\x98({' \\ '\\x8eN\\x9b\\xb1\\xbf\\xf5O\\xa5\\xd7\\x0b\\xb4\\xc9\\x0f\\x96\\xec<G\\xa7\\xc5\\x1e\\xbf\\xfa\\xe2b\\x90\\x16\\xb2\\x00\\x96E' \\ '\\x93O\\x9e\\xe7\\xe77\\x8b\\xd2@ \\xa3\\xa7\\x96\\xe6\\r\\xab\\xb9\\x97\\xfc\\xf6\\xb90WV\\x0e\\x8d(' \\ '\\xa1\\xa5dd*\\x06PL\\xa2\\xe7g\\xdfw\\xba\\xe8\\xe6o\\x06\\xc6\\xd5\\x80\\xc7\\xe5s\\xbb|\\xbd\\x91\\xd2\\xb9", "'\\xe7z\\xb13\\xae\\xfb\\x1aVS\\xd39\\x13\\x03\\x9ayttv\\x16\\xa2\\x06\\x98EQ\\xec\\x15\"xo\\xb8\\xa1\\x00Ftc\\xaf\\x17\\x05\\xdf' \\ '\\xec:\\xf3\\xce\\xa2\\x94\\xc2&\\x1f?\\x92\\xa6\\xd5\\xcd3M\\x1d`\\xa62\\xbf\\x13Df\\x03\\r\\xd9~\\xc2i\\n\\x97H8\\xac\\x88i' \\ '\\xdd0\\x07,]\\xdfZ\\xd9^\\xd9\\xcf\\x1b\\x94\\x96n\\x1f1\\xf7\\xbdUXR)}\\xcf\\xfe\\xa27`\\x81V6\\xf6rZn\\x85\\xd2\\xf2\\xf7' \\ '\\x8f\\xcf%\\xc3\\x05\\n\\xf8@\\xec\\x1f1`\\xee\\x9df}j\\xc5\\xdc\\x18Voit\\xf5\\xfb-\\xc7\\xf3\\xcf\\'\\x8a\\x7f\\x00\\x1a\\xa5' \\ '\\xeb\\xc4C&\\xe0\\xfdY\\x0b&\\x0bK\\x99A\\xafQ\\xa7k\\x07-\\x9e\\xab\\xc3\\xc6\\xb6\\x94\\xd3\\x00uZ\\x96T%X\\xd9\\x8b!\\x93t' \\ '\\'\\x06\\xaf\\x83I\\xd7o\\xb7\\x9c\\\\\\x91\\xc5p\\xbfa\\xeat]I\\xff\\xc8O\\xf7\\x83M\\xc8\\x10w\\xc0\\xbb\\xb4b\\xd2\\xf2\\xa8' \\ '\\xc3\\xfc\\xe7|\\x94\\xc6\\xa7ML\\x86_m\\xb3\\x14\\x96\\x8cz9G\\xc8\\xd9\\xaca\\x96\\xe6C\\x1fr\\xa6\\xf5@+\\x18\\xa5A\\xd3'", "'\\x1c6\\x00\\xeeb\\x89$\\xde\\xb5\\xc4C\\xfa\\x01v\\x86\\xd2\\xb0\\x8f\\x9e\\xbb\\xffV\\x05\\x93\\x96\\t\\x99\\x9b\\x013DPG$R' \\ '\\xdf\\xa9bx\\x85\\x7f\\x12\\xac\\x07\\x9c\\xf9\\xa4\\n:\\x8d\\xe3h\\xcfC.\\xcb\\xcbH\\xdc\\x03j\\x90\\xa2]\\xdd\\xc0\\x9de\\xfe' \\ '\\x00\\x99T\\x15\\xa0\\xe6!\\x0159\\x9f\\xcf\\xc7\\t\"I\\x7f\\xb9@\\xab\\x1a\\xa5Z\\xf5SK{\\x13\\x99\\xf1*\\xd4\\xe7\\xc8 ' \\ '\\x8e\\xf0\\xe5\\x89p\\xde#{\\xe3\\xe9<\\xb5\\xa3R\\xbfgY\\x9a\\x1f=GQg{' \\ '\\xfe\\x06\\xc5X\\xd0\\xebD.\\xac\\xf3\\xff\\xcb\\xaa\\x9a\\xac\\\\\\xc0\\x9a\\x94\\\\\\x8e\\x0e\\x0f\\xcd\\xf9\\xa4G.P\\x8cuU' \\ '\\x8dxw\\x0b\\r0Koq\\x86\\x1aO!\\x9a\\x90\\xd3\\x1c\\xc9*\\x84\\x8c\\x16/7\\xabu\\xfa\\xe7\\xc8Di\\xc5fL\\x8a&\\xe9v8\\x89' \\", "'N\"\\x1eA\\x92\\xf0l\\x03\\xd8]\\xeb\\nq/\\xc9\\xb4\\xe6\\x91\\x13\\xf2\\x97\\xc8t\\x1dF\\xea#\\xa2\\xc0\\xebH\\x06)\\x98\\x8b' \\ '\\xc4\\xbd\\xd73\\x12\\x17e\\xe5\\x956g\\xb0C~\\x15P\\x89(' \\ '\\t<\\x08\\xe9\\xbda\\xc0]\\xcf\\x1f\\xed\\x91\\xbcBd\\xe5\\rv\\xc4\\xfc:\\xac\\xe2Qlf\\xc8G\\x82\\x95\\xc6\\'\\xf1\\x18(' \\ '><\\xa6\\xfb\\xc0\\xf6\\x83\\xcc\\xe7\\t\\xd5G\\x1c&\\x8d\\xc3E\\x1b\\x0fK\\x00\\x8a\"\\xc8\\xd9\\xde\\x93\\xfb\\xfa\\\\U\\xa7\\x08' \\ '\\xcf\\x85\\x96\\xd3\\xf9\\xb1\\xf4\\x0f\\x9b\\x9c\\x11\\xa4q_\\xf8\\xe0)3\\xa5\\x9e\\x97\\x1c;^\\xbaU\\xa8Z[' \\ '1x\\x9f\\xbcX$3_v9\\xd3\\xedt?W\\xe3^\\x14r\\xa04T\\xc0\\xfad\\x14\\xc6r\\x83\\xf7\\xa5\\xc4\\x91\\x1f\\xc6\\x90!r\\x9fs0\\xb1' \\ '\\xa76\\xdd\\xb0\\x1e\\xc66\\xcf\\\\\\x9ay\\xf5\\x85\\xc4\\xc1aW\\xb0\\x97\\xd355A\\x88,'", "ho.pisa as pisa import os import logging log = logging.getLogger(__file__) def dummyLoader(name): return", "new_suffix in (\".css\", \".gif\", \".jpg\", \".png\"): suffix = new_suffix tmpPath = tempfile.mktemp(prefix=\"pisa-\", suffix=suffix)", "Apr 2008) $\" import ho.pisa as pisa import os import logging log =" ]
[ "activation function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks model", "the predicted data. :return total_loss: Float containing the mean value of the binary", "function model = layers.LeakyReLU(alpha = 0.2)(model) return model # Define input layer inputs", "compute the discriminator loss as the mean value of the binary cross-entropy for", "(or filter) size for the convolutional operations :param strides: Integer containing the stride", "adding a small perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape)", "shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size,", "the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1)", "returned for its later use during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\"", ":param hr_predic: Tensorflow tensor containing the predicted high-resolution fields :param hr_target: Tensorflow tensor", "11:38:43 2021 @author: guemesturb \"\"\" import numpy as np import tensorflow as tf", ":param y_true: Tensorflow tensor containing the target high-resolution fields :param flag: Tensorflow tensor", "Tensorflow tensor \"\"\" # Copy model for skip-connection purposes gen = model #", "64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(inputs) # Apply", "of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data to", "list into tuple output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\" Function to", "high-resolution fields :param fl_target: Tensorflow tensor containing the information about which bins in", "Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size, strides =", "function of the bins in the target data that contain information content_loss =", "tensor size (batch x height x width x filters). \"\"\" # Compute new", "Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernel_size, strides =", "strides: Integer containing the stride value to ba applied in the convolutional operations.", "input and output layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator", "layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation function", "Integer containing the ratio to increase/decrease the heigth and width/number of filters. :return:", "of the bins in the target data that contain information content_loss = custom_mse_loss(", "the target high-resolution fields :param fl_target: Tensorflow tensor containing the information about which", "abd reduce tensor filters (last dimension) to upsample their height and width. :param", "return model # Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') #", ":param y_pred: Tensorflow tensor containing the predicted high-resolution fields :param y_true: Tensorflow tensor", "kernel_size: Integer containing the kernel (or filter) size for the convolutional operations. :param", "number of filters to apply in the convolution operation. :param kernel_size: Integer containing", "model state. :param kernel_size: Integer containing the kernel (or filter) size for the", "3, 2) # Flatten the tensor into a vector model = layers.Flatten()(model) #", "predicted labels. :param real_Y: Tensorflow vector of dimensions batch size x 1 containing", "channels. outputs = layers.Conv2D(filters = self.channels, kernel_size = 9, strides = 1, padding", "number of filter is equal to the desired number of channels. outputs =", "y_true, flag): \"\"\" Custom function to compute the mean-squared error between target and", "res_block = res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block, 3, 128, 1)", "function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator to cause", "return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function to generate the SRGAN", "Tensorflow tensor containing the target high-resolution fields :param flag: Tensorflow tensor containing boolean", "convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 =", "return model # Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') #", "x 1 containing the labels of the predicted data. :return total_loss: Float containing", "fl_target): \"\"\" Function to compute the generator loss as the mean-squared error between", "+ 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" # Define discriminator loss as", "layer conv_2 = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding", "information about which bins in the high-resolution target data contain information. :return loss:", "Compute new dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3]", "generate a residual block :param model: Tensorflow tensor containing the internal model state.", "resolution enhancement of PIV images through GANs. :param model_name: String containing the assigned", "points in the streamwise direction for the low-resolution data. :param ny: Integer containing", "3, 128, 1) # Apply a convolutional layer conv_2 = layers.Conv2D(filters = 64,", "layers.Flatten()(model) # Apply a fully-conncted layer model = layers.Dense(1024)(model) # Apply a convolutional", "error between the target and predicted data only as a function of the", "strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model", "model = layers.LeakyReLU(alpha = 0.2)(model) return model # Define input layer inputs =", "256, 3, 1) model = discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512,", "x filters). :param scale: Integer containing the ratio to increase/decrease the heigth and", "= discriminator_block(model, 512, 3, 2) # Flatten the tensor into a vector model", "= layers.Dense(1024)(model) # Apply a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) #", "Connect input and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model", "the discriminator to identify the target data as real, adding a small perturbation", "def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate a residual block :param", "output_shape def subpixel(x): \"\"\" Function to change tensor size. :return: Tensorflow tensor with", "128, 3, 2) model = discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256,", "= discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128, 3, 2) model =", "Apply a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) #", "fields :param flag: Tensorflow tensor containing boolean information regarding the bins in the", "predicted data. :param hr_predic: Tensorflow tensor containing the predicted high-resolution fields :param hr_target:", "generator loss as the mean-squared error between the target and the predicted high-resolution", "low- and high-resolution data. :param nx: Integer containing the grid points in the", "class to generate the Tensorflow models for resolution enhancement of PIV images through", "predicted data as fake, adding a small perturbation for stability issues fake_loss =", "the grid points in the streamwise direction for the low-resolution data. :param ny:", "strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function model =", "layers.Add()([prelu_1, conv_2]) # Upsample the data to the high-resolution dimensions for index in", "predicted high-resolution fields :param hr_target: Tensorflow tensor containing the target high-resolution fields :param", "= keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer model = layers.Conv2D(filters", "tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx,", "loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N )", "model, for storage purposes. :param us: Integer containing the upsampling ratio between the", "total_loss: Float containing the mean value of the binary cross-entropy for the target", "loss as the mean value of the binary cross-entropy for the target and", "name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to", "Add model with input model (skip connection operation) model = layers.Add()([gen, model]) return", "discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate) return", "Integer containing the kernel (or filter) size for the convolutional operations. :param filters:", "the model, for storage purposes. :param us: Integer containing the upsampling ratio between", "layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function model =", "layers.Activation('sigmoid')(model) # Connect input and output layers discriminator = keras.Model(inputs=inputs, outputs = model,", "generator_loss: Self-defined Python function containing the generator loss :return discriminator_loss: Self-defined Python function", "dims = [input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] / (scale **", "= self.channels, kernel_size = 9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) #", ":param kernel_size: Integer containing the kernel (or filter) size for the convolutional operations", "conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) )", "tensor containing the target high-resolution fields :param fl_target: Tensorflow tensor containing the information", "# Apply 7 discriminator blocks model = discriminator_block(model, 64, 3, 4) model =", "\"same\", data_format='channels_last')(res_block) # Apply one last skip connection between the input and output", "dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] / (scale", "= discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256, 3, 1) model =", "kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric", "a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer", "the mean-squared error \"\"\" # Compute the number of bins in the target", "model: Tensorflow tensor \"\"\" # Copy model for skip-connection purposes gen = model", "containing the tensor size (batch x height x width x filters). :param scale:", "\"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function model = layers.LeakyReLU(alpha =", "# Compute loss loss = content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss", "for the perdicted fields. :param fake_Y: Tensorflow vector of dimensions batch size x", "state :param filters: Integer containing the number of filters to apply in the", "convolutional operations. :return model: Tensorflow tensor \"\"\" # Apply convolutional operation model =", "the mean value of the binary cross-entropy for the target and predicted labels.", "# Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) return model", "# Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return", "their height and width. :param input_shape: Tensorflow object containing the tensor size (batch", "one by removing the batch normalization layers. :return generator: Tensorflow object containing the", "convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1,", "value total_loss = 0.5 * (real_loss + fake_loss) return total_loss return generator, discriminator,", "filters). \"\"\" # Compute new dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2]", "\"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply", "def subpixel_shape(input_shape): \"\"\" Function to compute the new tensor size after pixel shuffling.", "Compute the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred", "dimension) to upsample their height and width. :param input_shape: Tensorflow object containing the", "containing the number of velocity components present in the data. Default is 2.", "= kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU", "a sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect input and output layers", "model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer inputs", "target data as real, adding a small perturbation for stability issues real_loss =", "Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional", "be returned for its later use during the training def discriminator_loss(real_Y, fake_Y): \"\"\"", "Custom function to compute the mean-squared error between target and predicted data only", "PIV images through GANs. :param model_name: String containing the assigned name to the", "3, 64, 1) # res_block = res_block_gen(res_block, 3, 128, 1) # Apply a", ":return discriminator_loss: Self-defined Python function containing the discriminator loss. \"\"\" \"\"\" Generator model", "= custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss = content_loss", ":return: Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute", "def subpixel(x): \"\"\" Function to change tensor size. :return: Tensorflow tensor with rescaled", "= tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator to identify the target", "model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters", "fields :param hr_target: Tensorflow tensor containing the target high-resolution fields :param fl_target: Tensorflow", ":return: Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel,", "strides): \"\"\" Function to generate discriminator blocks. :param model: Tensorflow tensor containing the", "containing boolean information regarding the bins in the target data that have information", "strides = 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128,", "x width x filters). :return: Tuple containing the rescaled tensor size (batch x", "applied in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Copy model", "to change tensor size. :return: Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x,", "use during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator", "during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute the", "= layers.Conv2D(filters = self.channels, kernel_size = 9, strides = 1, padding = \"same\",", "and predicted labels. \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() #", "one last skip connection between the input and output of the residual-block loop", "import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd", "tensor containing the target high-resolution fields :param flag: Tensorflow tensor containing boolean information", "(batch x height x width x filters). :return: Tuple containing the rescaled tensor", "number of bins. :param y_pred: Tensorflow tensor containing the predicted high-resolution fields :param", "= n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'):", "channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name ==", "number residual blocks to be applied in the GAN generator. Default is 16.", "model. :return discriminator: Tensorflow object containing the discriminator model. :return generator_loss: Self-defined Python", "256, 3, 2) model = discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512,", ":param input_shape: Tensorflow object containing the tensor size (batch x height x width", "wight and height dimensions of the data. :param model: Tensorflow tensor containing the", "scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx, ny,", "fake_Y ) # Compute the mean-squared error between the target and predicted data", "function to be returned for its later use during the training def discriminator_loss(real_Y,", "training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator loss as the", "String containing the assigned name to the model, for storage purposes. :param us:", "the target and predicted labels. \"\"\" # Define binary cross-entropy function cross_entropy =", "containing the internal model state :param filters: Integer containing the number of filters", "information regarding the bins in the target data that have information :return loss:", "n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return", "Tensorflow tensor containing the target high-resolution fields :param fl_target: Tensorflow tensor containing the", "model # Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply", "of filters to apply in the convolution operation. :param kernel_size: Integer containing the", "# Apply a Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) #", "7 discriminator blocks model = discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128,", "in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Apply convolutional operation", "the data. :param model: Tensorflow tensor containing the internal model state. :param kernel_size:", "target and predicted data only as a function of the bins in the", "name='low-res-input') # Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last',", "self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01')", "low-resolution data. :param ny: Integer containing the grid points in the wall-normal direction", "import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers def", "\"\"\" Function to change tensor size. :return: Tensorflow tensor with rescaled dimensions \"\"\"", "layer to assert the number of filter is equal to the desired number", "cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator to", "cross-entropy for the target and predicted labels. :param real_Y: Tensorflow vector of dimensions", ":param model: Tensorflow tensor containing the internal model state :param filters: Integer containing", "inside the class self.us = us self.nx = nx self.ny = ny self.channels", "alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size =", "3, 1) model = discriminator_block(model, 512, 3, 2) # Flatten the tensor into", "hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss = content_loss + 1e-3*adversarial_loss", "* scale, input_shape[2] * scale, int(input_shape[3] / (scale ** 2))] # Transform list", "a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy", ":param strides: Integer containing the stride value to ba applied in the convolutional", "res_block_gen(res_block, 3, 128, 1) # Apply a convolutional layer conv_2 = layers.Conv2D(filters =", "ratio between the low- and high-resolution data. :param nx: Integer containing the grid", "for its later use during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom", "return loss \"\"\" Discriminator loss \"\"\" # Define discriminator loss as a function", ":param flag: Tensorflow tensor containing boolean information regarding the bins in the target", "high-resolution data that contains information N = tf.reduce_sum(flag) # Compute the conditional mean-squared", "removing the batch normalization layers. :return generator: Tensorflow object containing the generator model.", "function to be returned for its later use during the training def custom_mse_loss(y_pred,", "* scale, int(input_shape[3] / (scale ** 2))] # Transform list into tuple output_shape", "the class self.us = us self.nx = nx self.ny = ny self.channels =", "= res_block_gen(res_block, 3, 128, 1) # Apply a convolutional layer conv_2 = layers.Conv2D(filters", "height x width x filters). :param scale: Integer containing the ratio to increase/decrease", "= \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None,", "containing the tensor size (batch x height x width x filters). :return: Tuple", "fully-conncted layer model = layers.Dense(1)(model) # Apply a sigmoid connection function model =", "layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" #", "discriminator blocks model = discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128, 3,", "containing the mean value of the binary cross-entropy for the target and predicted", "coding: utf-8 -*- \"\"\" Created on Sat Apr 10 11:38:43 2021 @author: guemesturb", "labels. :param real_Y: Tensorflow vector of dimensions batch size x 1 containing the", "containing the upsampling ratio between the low- and high-resolution data. :param nx: Integer", "= 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and output layers generator", "0.2, fake_Y ) # Compute the mean-squared error between the target and predicted", "filters (last dimension) to upsample their height and width. :param input_shape: Tensorflow object", "padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha", "the discriminator model. :return generator_loss: Self-defined Python function containing the generator loss :return", "GAN generator. Default is 16. :return: \"\"\" # Declare variable inside the class", "high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) #", "and width. :param input_shape: Tensorflow object containing the tensor size (batch x height", "the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data to the", "tensor into a vector model = layers.Flatten()(model) # Apply a fully-conncted layer model", "into tuple output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\" Function to change", "to identify the target data as real, adding a small perturbation for stability", "x width x filters). :param scale: Integer containing the ratio to increase/decrease the", "a vector model = layers.Flatten()(model) # Apply a fully-conncted layer model = layers.Dense(1024)(model)", "increase/decrease the heigth and width/number of filters. :return: Tensorflow tensor with rescaled dimensions", "containing the grid points in the streamwise direction for the low-resolution data. :param", "(batch x height x width x filters). \"\"\" # Compute new dimensions dims", "mean value total_loss = 0.5 * (real_loss + fake_loss) return total_loss return generator,", "numpy as np import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers", "inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional layer conv_1 =", "strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape,", "in the target data that have information :return loss: Float containg the mean-squared", "tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator to cause the discriminator to", "function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer", "discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate discriminator blocks. :param model: Tensorflow", "Default is 2. :param n_residual_blocks : Integer containing the number residual blocks to", "-*- \"\"\" Created on Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import", "output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python", "bins in the target data that have information :return loss: Float containg the", "index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply the last", "the data to the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling,", "Function to upsample the wight and height dimensions of the data. :param model:", "# Compute the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true,", "1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and output layers generator =", "filters, kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Add", "layer model = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding", ":return loss: Float containing the generator loss \"\"\" # Define binary cross-entropy function", "high-resolution data. :param nx: Integer containing the grid points in the streamwise direction", "tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N ) return loss def", "equal to the desired number of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size", "binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator", "kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation function prelu_1", "tensor containing boolean information regarding the bins in the target data that have", "Custom layer to shuffle abd reduce tensor filters (last dimension) to upsample their", "ba applied in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Copy", "Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate discriminator", "data_format='channels_last')(model) # Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) return", "Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional", "outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator loss as", "the binary cross-entropy for the target and predicted labels. \"\"\" # Define binary", "= layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks model = discriminator_block(model, 64,", "skip-connection purposes gen = model # Apply convolutional operation model = layers.Conv2D(filters =", "issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the", "dimensions batch size x 1 containing the labels of the target data. :param", "Python class to generate the Tensorflow models for resolution enhancement of PIV images", "= cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss = 0.5 * (real_loss +", "= layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer model = layers.Dense(1)(model) #", "content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss =", "certain number of bins. :param y_pred: Tensorflow tensor containing the predicted high-resolution fields", "build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else: return", "us self.nx = nx self.ny = ny self.channels = channels self.model_name = model_name", "# Apply a fully-conncted layer model = layers.Dense(1)(model) # Apply a sigmoid connection", "error between target and predicted data only for a certain number of bins.", "with respect the original one by removing the batch normalization layers. :return generator:", "self.ny = ny self.channels = channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return", "size for the convolutional operations. :param filters: Integer containing the number of filters", "the convolution operation. :param kernel_size: Integer containing the kernel (or filter) size for", "issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss = 0.5 *", "containing the internal model state. :param kernel_size: Integer containing the kernel (or filter)", "stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) #", "the kernel (or filter) size for the convolutional operations. :param filters: Integer containing", "Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model", "name to the model, for storage purposes. :param us: Integer containing the upsampling", "tensor containing the predicted high-resolution fields :param hr_target: Tensorflow tensor containing the target", "Compute loss loss = content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\"", "of filter is equal to the desired number of channels. outputs = layers.Conv2D(filters", "Function to change tensor size. :return: Tensorflow tensor with rescaled dimensions \"\"\" return", "of velocity components present in the data. Default is 2. :param n_residual_blocks :", "3, 256, 1) # Apply the last convolutional layer to assert the number", "components present in the data. Default is 2. :param n_residual_blocks : Integer containing", "operation. :param strides: Integer containing the stride value to ba applied in the", "\"same\", data_format='channels_last')(model) # Add model with input model (skip connection operation) model =", "tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the new", "as np import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as", "high-resolution fields :param y_true: Tensorflow tensor containing the target high-resolution fields :param flag:", "data. :param channels: Integer containing the number of velocity components present in the", "the predicted data. :param hr_predic: Tensorflow tensor containing the predicted high-resolution fields :param", "Generator loss \"\"\" # Define generator loss as a function to be returned", "the rescaled tensor size (batch x height x width x filters). \"\"\" #", "layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample", "# Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) #", "the binary cross-entropy for the target and predicted labels. :param real_Y: Tensorflow vector", "== 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self):", "to compute the mean-squared error between target and predicted data only for a", "to generate the SRGAN architecture as Ledig et al. (2017). This version is", "Integer containing the number of filters to apply in the convolution operation. :param", "tensorflow.keras as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer", "and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def", "3, 4) model = discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128, 3,", "= 9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and", "= [input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] / (scale ** 2))]", "output of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data", "layers.Dense(1)(model) # Apply a sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect input", "+ fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer", "1, padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function model", "= 0.5 * (real_loss + fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss", "model = discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512, 3, 2) #", "layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters,", "y_pred: Tensorflow tensor containing the predicted high-resolution fields :param y_true: Tensorflow tensor containing", "Integer containing the kernel (or filter) size for the convolutional operations :param strides:", "layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional layer conv_1", "Connect input and output layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\"", ":return generator: Tensorflow object containing the generator model. :return discriminator: Tensorflow object containing", "Python function containing the discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model,", "the stride value to ba applied in the convolutional operations. :return model: Tensorflow", "name='high-res-input') # Apply a convolutional layer model = layers.Conv2D(filters = 64, kernel_size =", "for storage purposes. :param us: Integer containing the upsampling ratio between the low-", "target data that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target )", "misidentify the predicted data as real, adding a small perturbation for stability issues", "cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator to cause the", "= nx self.ny = ny self.channels = channels self.model_name = model_name self.n_residual_blocks =", "content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" # Define discriminator loss", "Compute the capability of the discriminator to identify the target data as real,", "the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute the mean-squared", "the convolutional operations :param strides: Integer containing the stride value to ba applied", "for resolution enhancement of PIV images through GANs. :param model_name: String containing the", "adversarial error for the perdicted fields. :param fake_Y: Tensorflow vector of dimensions batch", "model. :return generator_loss: Self-defined Python function containing the generator loss :return discriminator_loss: Self-defined", "= 3, strides = 1, padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky", "2) model = discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256, 3, 2)", "of bins. :param y_pred: Tensorflow tensor containing the predicted high-resolution fields :param y_true:", "generator to cause the discriminator to misidentify the predicted data as real, adding", "purposes gen = model # Apply convolutional operation model = layers.Conv2D(filters = filters,", "alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels),", "kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Add model", "the predicted high-resolution fields plus and adversarial error for the perdicted fields. :param", "\"same\", data_format='channels_last')(up_sampling) # Connect input and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator')", "custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss = content_loss +", "the high-resolution target data contain information. :return loss: Float containing the generator loss", "in the streamwise direction for the low-resolution data. :param ny: Integer containing the", "only for a certain number of bins. :param y_pred: Tensorflow tensor containing the", "discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define", ":return discriminator: Tensorflow object containing the discriminator model. :return generator_loss: Self-defined Python function", "as the mean-squared error between the target and the predicted high-resolution fields plus", "object containing the tensor size (batch x height x width x filters). :param", "Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape)", "= layers.Dense(1)(model) # Apply a sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect", "blocks to be applied in the GAN generator. Default is 16. :return: \"\"\"", "value of the binary cross-entropy for the target and predicted labels. \"\"\" #", "\"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None,", "Apply a Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply", "as real, adding a small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) -", "= model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01') or", "the Tensorflow models for resolution enhancement of PIV images through GANs. :param model_name:", "Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate a", ":param n_residual_blocks : Integer containing the number residual blocks to be applied in", "1) # Apply a convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size =", "al. (2017). This version is modified with respect the original one by removing", "to apply in the convolution operation. :param strides: Integer containing the stride value", "internal model state :param filters: Integer containing the number of filters to apply", "SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None,", "# Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs)", "size x 1 containing the labels of the predicted data. :param hr_predic: Tensorflow", "tensor containing the predicted high-resolution fields :param y_true: Tensorflow tensor containing the target", "the number of filters to apply in the convolution operation. :param kernel_size: Integer", "real_Y: Tensorflow vector of dimensions batch size x 1 containing the labels of", "containing the predicted high-resolution fields :param y_true: Tensorflow tensor containing the target high-resolution", "(last dimension) to upsample their height and width. :param input_shape: Tensorflow object containing", "return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16):", "Tensorflow tensor containing the predicted high-resolution fields :param y_true: Tensorflow tensor containing the", "height x width x filters). :return: Tuple containing the rescaled tensor size (batch", "to misidentify the predicted data as real, adding a small perturbation for stability", "def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate", "its use in a residual-block loop res_block = prelu_1 # Apply N residual", "blocks. :param model: Tensorflow tensor containing the internal model state :param filters: Integer", "of the discriminator to identify the target data as real, adding a small", "assigned name to the model, for storage purposes. :param us: Integer containing the", "= \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha =", "tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class", "containing the labels of the target data. :param fake_Y: Tensorflow vector of dimensions", "strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and output layers", "data. Default is 2. :param n_residual_blocks : Integer containing the number residual blocks", "applied in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Apply convolutional", "Tensorflow models for resolution enhancement of PIV images through GANs. :param model_name: String", "512, 3, 1) model = discriminator_block(model, 512, 3, 2) # Flatten the tensor", "tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N ) return loss def generator_loss(fake_Y,", "Integer containing the upsampling ratio between the low- and high-resolution data. :param nx:", "discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate) return generator_optimizer, discriminator_optimizer", "Integer containing the grid points in the streamwise direction for the low-resolution data.", "res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block, 3, 128, 1) # Apply", "data. :param model: Tensorflow tensor containing the internal model state. :param kernel_size: Integer", "filters to apply in the convolution operation. :param strides: Integer containing the stride", "perdicted fields. :param fake_Y: Tensorflow vector of dimensions batch size x 1 containing", "and height dimensions of the data. :param model: Tensorflow tensor containing the internal", "model (skip connection operation) model = layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size,", "padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and output layers generator = keras.Model(inputs,", "def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd reduce tensor filters (last", "model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros',", "operation. :param kernel_size: Integer containing the kernel (or filter) size for the convolutional", "a small perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) *", "in the target data that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target),", "models for resolution enhancement of PIV images through GANs. :param model_name: String containing", "a small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean", "loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute the generator loss", "the target and the predicted high-resolution fields plus and adversarial error for the", "to be returned for its later use during the training def custom_mse_loss(y_pred, y_true,", "keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle", "\"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate discriminator blocks. :param", "1) model = discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256, 3, 1)", "1, padding = \"same\", data_format='channels_last')(res_block) # Apply one last skip connection between the", "scale: Integer containing the ratio to increase/decrease the heigth and width/number of filters.", "model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate a residual", "layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use in a residual-block", "the mean-squared error between the target and predicted data only as a function", "discriminator_block(model, 512, 3, 2) # Flatten the tensor into a vector model =", "layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\"", "kernal_size, filters, strides): \"\"\" Function to generate a residual block :param model: Tensorflow", "= layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding = \"same\",", "high-resolution fields :param flag: Tensorflow tensor containing boolean information regarding the bins in", "0.2)(model) # Apply 7 discriminator blocks model = discriminator_block(model, 64, 3, 4) model", "# Compute the number of bins in the target high-resolution data that contains", "a residual block :param model: Tensorflow tensor containing the internal model state. :param", "new tensor size after pixel shuffling. :param input_shape: Tensorflow object containing the tensor", "apply in the convolution operation. :param kernel_size: Integer containing the kernel (or filter)", "\"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the new tensor size after pixel", "fields :param y_true: Tensorflow tensor containing the target high-resolution fields :param flag: Tensorflow", "# Compute the capability of the discriminator to identify the predicted data as", "for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply the", "tensor size. :return: Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC')", "function model = layers.Activation('sigmoid')(model) # Connect input and output layers discriminator = keras.Model(inputs=inputs,", "ny self.channels = channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self):", "custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute the mean-squared error between target", "a fully-conncted layer model = layers.Dense(1024)(model) # Apply a convolutional layer model =", "between the target and predicted data only as a function of the bins", ":param fl_target: Tensorflow tensor containing the information about which bins in the high-resolution", "ny: Integer containing the grid points in the wall-normal direction for the low-resolution", ":param kernel_size: Integer containing the kernel (or filter) size for the convolutional operations.", "activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its", "for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) # res_block =", "size (batch x height x width x filters). :param scale: Integer containing the", ":return loss: Float containg the mean-squared error \"\"\" # Compute the number of", "\"\"\" # Compute the number of bins in the target high-resolution data that", "'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function to generate the", "Tensorflow tensor containing the information about which bins in the high-resolution target data", "x width x filters). \"\"\" # Compute new dimensions dims = [input_shape[0], input_shape[1]", "discriminator loss as the mean value of the binary cross-entropy for the target", "self.channels, kernel_size = 9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect", "of the generator to cause the discriminator to misidentify the predicted data as", "# Connect input and output layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator')", "error between the target and the predicted high-resolution fields plus and adversarial error", "with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the new tensor", "padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a", "data that have information :return loss: Float containg the mean-squared error \"\"\" #", "capability of the generator to cause the discriminator to misidentify the predicted data", "tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator to identify the target data", "= layers.Flatten()(model) # Apply a fully-conncted layer model = layers.Dense(1024)(model) # Apply a", "residual-block loop res_block = prelu_1 # Apply N residual blocks for index in", "(self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function to", "ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow models for resolution", "model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name", "mean-squared error \"\"\" # Compute the number of bins in the target high-resolution", "fl_target), fl_target ) # Compute loss loss = content_loss + 1e-3*adversarial_loss return loss", "mean value of the binary cross-entropy for the target and predicted labels. \"\"\"", "tensor containing the internal model state. :param kernel_size: Integer containing the kernel (or", "Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation", "data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size = 3, strides = 1,", ":return total_loss: Float containing the mean value of the binary cross-entropy for the", "= keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator", ":param hr_target: Tensorflow tensor containing the target high-resolution fields :param fl_target: Tensorflow tensor", "low-resolution data. :param channels: Integer containing the number of velocity components present in", "model = discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256, 3, 2) model", "kernel_size, filters, strides): \"\"\" Function to upsample the wight and height dimensions of", "tuple output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\" Function to change tensor", "to assert the number of filter is equal to the desired number of", "# Compute new dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2] * scale,", "adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the", "flag): \"\"\" Custom function to compute the mean-squared error between target and predicted", "original one by removing the batch normalization layers. :return generator: Tensorflow object containing", "padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function model =", "convolution operation. :param kernel_size: Integer containing the kernel (or filter) size for the", "index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block,", "discriminator blocks. :param model: Tensorflow tensor containing the internal model state :param filters:", "= res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block, 3, 128, 1) #", "= tuple(dims) return output_shape def subpixel(x): \"\"\" Function to change tensor size. :return:", "perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y", "and predicted data only as a function of the bins in the target", "stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of", "(real_loss + fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate):", "layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128,", "and output of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the", "conv_2 = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding =", "value to ba applied in the convolutional operations. :return model: Tensorflow tensor \"\"\"", "architecture as Ledig et al. (2017). This version is modified with respect the", "vector model = layers.Flatten()(model) # Apply a fully-conncted layer model = layers.Dense(1024)(model) #", "the capability of the discriminator to identify the target data as real, adding", "loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function", "discriminator_loss: Self-defined Python function containing the discriminator loss. \"\"\" \"\"\" Generator model \"\"\"", "fl_target: Tensorflow tensor containing the information about which bins in the high-resolution target", "tf import tensorflow.keras as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\"", "predicted data. :return total_loss: Float containing the mean value of the binary cross-entropy", "only as a function of the bins in the target data that contain", "loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data to the high-resolution dimensions", "height and width. :param input_shape: Tensorflow object containing the tensor size (batch x", ":param channels: Integer containing the number of velocity components present in the data.", "size x 1 containing the labels of the target data. :param fake_Y: Tensorflow", "kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 =", "in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply the last convolutional", "Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function", "and predicted labels. :param real_Y: Tensorflow vector of dimensions batch size x 1", ":param nx: Integer containing the grid points in the streamwise direction for the", "generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate) return generator_optimizer,", "the ratio to increase/decrease the heigth and width/number of filters. :return: Tensorflow tensor", "height x width x filters). \"\"\" # Compute new dimensions dims = [input_shape[0],", "2. :param n_residual_blocks : Integer containing the number residual blocks to be applied", "ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for", "def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate discriminator blocks. :param model:", "= 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size", "x filters). :return: Tuple containing the rescaled tensor size (batch x height x", "containing the assigned name to the model, for storage purposes. :param us: Integer", "model for skip-connection purposes gen = model # Apply convolutional operation model =", "model # Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply", "last skip connection between the input and output of the residual-block loop up_sampling", "the tensor size (batch x height x width x filters). :return: Tuple containing", ") # Compute the mean-squared error between the target and predicted data only", "the data. Default is 2. :param n_residual_blocks : Integer containing the number residual", "Function to compute the discriminator loss as the mean value of the binary", "the internal model state :param filters: Integer containing the number of filters to", "predicted high-resolution fields plus and adversarial error for the perdicted fields. :param fake_Y:", "activation function model = layers.LeakyReLU(alpha = 0.2)(model) return model # Define input layer", "Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import numpy as np import", "of filters. :return: Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function", "Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply", "# Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernel_size, strides", "Integer containing the number residual blocks to be applied in the GAN generator.", "= keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides):", "width x filters). :return: Tuple containing the rescaled tensor size (batch x height", "loss \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the", "the discriminator to misidentify the predicted data as real, adding a small perturbation", "is modified with respect the original one by removing the batch normalization layers.", "residual blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) #", "is equal to the desired number of channels. outputs = layers.Conv2D(filters = self.channels,", "the heigth and width/number of filters. :return: Tensorflow tensor with rescaled dimensions \"\"\"", "# Copy model for skip-connection purposes gen = model # Apply convolutional operation", "discriminator loss as a function to be returned for its later use during", "the labels of the predicted data. :param hr_predic: Tensorflow tensor containing the predicted", "model = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding =", "rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def", "containing the grid points in the wall-normal direction for the low-resolution data. :param", "convolutional operations :param strides: Integer containing the stride value to ba applied in", "alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use in a residual-block loop res_block", "to compute the generator loss as the mean-squared error between the target and", "perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the", "use in a residual-block loop res_block = prelu_1 # Apply N residual blocks", "Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the", "Transform list into tuple output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\" Function", "model = layers.Activation('sigmoid')(model) # Connect input and output layers discriminator = keras.Model(inputs=inputs, outputs", "change tensor size. :return: Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale,", "keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer model = layers.Conv2D(filters =", "operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size, strides = strides, padding", "as Ledig et al. (2017). This version is modified with respect the original", "variable inside the class self.us = us self.nx = nx self.ny = ny", "\"\"\" # Compute new dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2] *", "block :param model: Tensorflow tensor containing the internal model state. :param kernel_size: Integer", "kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last',", "convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer model", "last convolutional layer to assert the number of filter is equal to the", "else: return self.architecture01() def architecture01(self): \"\"\" Function to generate the SRGAN architecture as", "the bins in the target data that have information :return loss: Float containg", "high-resolution fields :param hr_target: Tensorflow tensor containing the target high-resolution fields :param fl_target:", "apply in the convolution operation. :param strides: Integer containing the stride value to", "the low-resolution data. :param ny: Integer containing the grid points in the wall-normal", "as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd reduce tensor", "filters to apply in the convolution operation. :param kernel_size: Integer containing the kernel", "filter) size for the convolutional operations. :param filters: Integer containing the number of", "direction for the low-resolution data. :param ny: Integer containing the grid points in", "real, adding a small perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) -", "return def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01()", "1) # res_block = res_block_gen(res_block, 3, 128, 1) # Apply a convolutional layer", "\"\"\" Function to compute the discriminator loss as the mean value of the", "# Compute mean value total_loss = 0.5 * (real_loss + fake_loss) return total_loss", "mean-squared error between target and predicted data only for a certain number of", "to the desired number of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size =", "between the input and output of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2])", "be returned for its later use during the training def custom_mse_loss(y_pred, y_true, flag):", "cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the mean-squared error", "input_shape[2] * scale, int(input_shape[3] / (scale ** 2))] # Transform list into tuple", "0.5 * (real_loss + fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss def", "discriminator to identify the predicted data as fake, adding a small perturbation for", "res_block = res_block_gen(res_block, 3, 128, 1) # Apply a convolutional layer conv_2 =", "for its later use during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to", "normalization layers. :return generator: Tensorflow object containing the generator model. :return discriminator: Tensorflow", ":param model_name: String containing the assigned name to the model, for storage purposes.", "Integer containing the grid points in the wall-normal direction for the low-resolution data.", "model = discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128, 3, 2) model", "# Apply one last skip connection between the input and output of the", ":param real_Y: Tensorflow vector of dimensions batch size x 1 containing the labels", "fields :param fl_target: Tensorflow tensor containing the information about which bins in the", "\"\"\" Custom layer to shuffle abd reduce tensor filters (last dimension) to upsample", "the predicted data as fake, adding a small perturbation for stability issues fake_loss", "of dimensions batch size x 1 containing the labels of the target data.", "up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply the last convolutional layer to", "data only as a function of the bins in the target data that", "and predicted data only for a certain number of bins. :param y_pred: Tensorflow", "= cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the mean-squared", "the discriminator to identify the predicted data as fake, adding a small perturbation", "(skip connection operation) model = layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters,", "of PIV images through GANs. :param model_name: String containing the assigned name to", "width x filters). \"\"\" # Compute new dimensions dims = [input_shape[0], input_shape[1] *", ") # Compute loss loss = content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator", "\"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size = 3, strides =", "in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Copy model for", "as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to", "for the target and predicted labels. :param real_Y: Tensorflow vector of dimensions batch", "batch size x 1 containing the labels of the predicted data. :param hr_predic:", "loss \"\"\" # Define generator loss as a function to be returned for", "Copy model for skip-connection purposes gen = model # Apply convolutional operation model", "filters, kernel_size, strides): \"\"\" Function to generate discriminator blocks. :param model: Tensorflow tensor", "(2017). This version is modified with respect the original one by removing the", "a function to be returned for its later use during the training def", "Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model #", "cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss = 0.5 * (real_loss + fake_loss)", "hr_target: Tensorflow tensor containing the target high-resolution fields :param fl_target: Tensorflow tensor containing", "containing the generator loss :return discriminator_loss: Self-defined Python function containing the discriminator loss.", "model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks model = discriminator_block(model,", "= model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator loss as a", "self.channels), name='low-res-input') # Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear',", "channels: Integer containing the number of velocity components present in the data. Default", "x height x width x filters). :return: Tuple containing the rescaled tensor size", "Tensorflow tensor containing the internal model state. :param kernel_size: Integer containing the kernel", "predicted high-resolution fields :param y_true: Tensorflow tensor containing the target high-resolution fields :param", "2) # Flatten the tensor into a vector model = layers.Flatten()(model) # Apply", "bins. :param y_pred: Tensorflow tensor containing the predicted high-resolution fields :param y_true: Tensorflow", "\"\"\" Function to upsample the wight and height dimensions of the data. :param", "alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer inputs = keras.Input(shape=(self.ny, self.nx,", "tensor size after pixel shuffling. :param input_shape: Tensorflow object containing the tensor size", "), N ) return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to", "= kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle", "filters, strides): \"\"\" Function to upsample the wight and height dimensions of the", "tensor \"\"\" # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size =", "in the target high-resolution data that contains information N = tf.reduce_sum(flag) # Compute", "width. :param input_shape: Tensorflow object containing the tensor size (batch x height x", "data_format='channels_last')(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model)", "# conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric", "that contains information N = tf.reduce_sum(flag) # Compute the conditional mean-squared error loss", "= channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name", "# Apply a convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size = 3,", "up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data to the high-resolution dimensions for", "def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator loss as the mean", "width x filters). :param scale: Integer containing the ratio to increase/decrease the heigth", "in the data. Default is 2. :param n_residual_blocks : Integer containing the number", "layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters = filters,", "containing the information about which bins in the high-resolution target data contain information.", "ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define", "the convolutional operations. :param filters: Integer containing the number of filters to apply", "= strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function model", "data as real, adding a small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape)", "object containing the generator model. :return discriminator: Tensorflow object containing the discriminator model.", "cross-entropy for the target and predicted labels. \"\"\" # Define binary cross-entropy function", "data_format='channels_last')(res_block) # Apply one last skip connection between the input and output of", "present in the data. Default is 2. :param n_residual_blocks : Integer containing the", "N residual blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1)", "\"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name,", "model = layers.Conv2D(filters = filters, kernel_size = kernal_size, strides = strides, padding =", "Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) return model #", "Compute the capability of the discriminator to identify the predicted data as fake,", "the number residual blocks to be applied in the GAN generator. Default is", "plus and adversarial error for the perdicted fields. :param fake_Y: Tensorflow vector of", "the target data as real, adding a small perturbation for stability issues real_loss", "the target data that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target", "64, 3, 4) model = discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128,", "of the binary cross-entropy for the target and predicted labels. \"\"\" # Define", "predicted data only for a certain number of bins. :param y_pred: Tensorflow tensor", "# Upsample the data to the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling", "containing the target high-resolution fields :param fl_target: Tensorflow tensor containing the information about", "fake_Y) # Compute mean value total_loss = 0.5 * (real_loss + fake_loss) return", "dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self,", "kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation", "labels of the predicted data. :param hr_predic: Tensorflow tensor containing the predicted high-resolution", "# Flatten the tensor into a vector model = layers.Flatten()(model) # Apply a", "the wall-normal direction for the low-resolution data. :param channels: Integer containing the number", "y_pred ) ) ), N ) return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target):", "the target high-resolution fields :param flag: Tensorflow tensor containing boolean information regarding the", "in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block, 3,", "tensor size (batch x height x width x filters). :return: Tuple containing the", "data. :param nx: Integer containing the grid points in the streamwise direction for", "filter) size for the convolutional operations :param strides: Integer containing the stride value", "as a function of the bins in the target data that contain information", "Self-defined Python function containing the generator loss :return discriminator_loss: Self-defined Python function containing", "upsampling ratio between the low- and high-resolution data. :param nx: Integer containing the", "filters, kernel_size = kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply", "function containing the generator loss :return discriminator_loss: Self-defined Python function containing the discriminator", "strides): \"\"\" Function to generate a residual block :param model: Tensorflow tensor containing", "data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2,", "\"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to", "# Apply a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1)", "2) model = discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512, 3, 2)", "regarding the bins in the target data that have information :return loss: Float", "loss as the mean-squared error between the target and the predicted high-resolution fields", "information. :return loss: Float containing the generator loss \"\"\" # Define binary cross-entropy", "operation model = layers.Conv2D(filters = filters, kernel_size = kernel_size, strides = strides, padding", "\"\"\" # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernel_size,", "as a function to be returned for its later use during the training", "1 containing the labels of the target data. :param fake_Y: Tensorflow vector of", "model with input model (skip connection operation) model = layers.Add()([gen, model]) return model", "layers.Conv2D(filters = filters, kernel_size = kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model)", "# Apply a convolutional layer model = layers.Conv2D(filters = 64, kernel_size = 3,", "Apply the last convolutional layer to assert the number of filter is equal", "that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute", ") return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute the", "outputs = layers.Conv2D(filters = self.channels, kernel_size = 9, strides = 1, padding =", "# Apply a fully-conncted layer model = layers.Dense(1024)(model) # Apply a convolutional layer", "# Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of", "= 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters", "= layers.LeakyReLU(alpha = 0.2)(model) return model # Define input layer inputs = keras.Input(shape=(self.ny*self.us,", "bins in the target data that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic,", "a small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) #", ": Integer containing the number residual blocks to be applied in the GAN", "Tensorflow tensor containing boolean information regarding the bins in the target data that", "y_true, y_pred ) ) ), N ) return loss def generator_loss(fake_Y, hr_predic, hr_target,", "[input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] / (scale ** 2))] #", "(or filter) size for the convolutional operations. :param filters: Integer containing the number", "Apply a convolutional layer model = layers.Conv2D(filters = 64, kernel_size = 3, strides", "(batch x height x width x filters). :param scale: Integer containing the ratio", "about which bins in the high-resolution target data contain information. :return loss: Float", "or (self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function", "discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128, 3, 2) model = discriminator_block(model,", "the convolutional operations. :return model: Tensorflow tensor \"\"\" # Copy model for skip-connection", "strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function", "# Apply a sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect input and", "inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer model =", "error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N", "Function to generate discriminator blocks. :param model: Tensorflow tensor containing the internal model", "Self-defined Python function containing the discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def", "small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute", "and width/number of filters. :return: Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape):", "size (batch x height x width x filters). \"\"\" # Compute new dimensions", "fake_Y): \"\"\" Function to compute the discriminator loss as the mean value of", "Tensorflow object containing the tensor size (batch x height x width x filters).", "Float containg the mean-squared error \"\"\" # Compute the number of bins in", "for the convolutional operations :param strides: Integer containing the stride value to ba", "input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional layer", "= ny self.channels = channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def", "batch size x 1 containing the labels of the target data. :param fake_Y:", "Function to generate the SRGAN architecture as Ledig et al. (2017). This version", "loss = content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" # Define", "layers.Conv2D(filters = self.channels, kernel_size = 9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling)", "operation) model = layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\"", "compute the mean-squared error between target and predicted data only for a certain", "to generate discriminator blocks. :param model: Tensorflow tensor containing the internal model state", "= tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N ) return", "connection between the input and output of the residual-block loop up_sampling = layers.Add()([prelu_1,", "Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional", "Integer containing the number of velocity components present in the data. Default is", "the tensor size (batch x height x width x filters). :param scale: Integer", "name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator loss as a function to", "to identify the predicted data as fake, adding a small perturbation for stability", "cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator to identify the", "be applied in the GAN generator. Default is 16. :return: \"\"\" # Declare", "stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss = 0.5", "1) model = discriminator_block(model, 512, 3, 2) # Flatten the tensor into a", "tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss = content_loss + 1e-3*adversarial_loss return", "between target and predicted data only for a certain number of bins. :param", "output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model,", "Float containing the mean value of the binary cross-entropy for the target and", "convolutional layer model = layers.Conv2D(filters = 64, kernel_size = 3, strides = 1,", "loss \"\"\" # Define discriminator loss as a function to be returned for", "total_loss = 0.5 * (real_loss + fake_loss) return total_loss return generator, discriminator, generator_loss,", "1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size =", "object containing the discriminator model. :return generator_loss: Self-defined Python function containing the generator", "@author: guemesturb \"\"\" import numpy as np import tensorflow as tf import tensorflow.keras", "a fully-conncted layer model = layers.Dense(1)(model) # Apply a sigmoid connection function model", "points in the wall-normal direction for the low-resolution data. :param channels: Integer containing", "= \"same\", data_format='channels_last')(res_block) # Apply one last skip connection between the input and", "containing the number of filters to apply in the convolution operation. :param kernel_size:", "self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer model = layers.Conv2D(filters = 64,", "velocity components present in the data. Default is 2. :param n_residual_blocks : Integer", "the target data that have information :return loss: Float containg the mean-squared error", "connection function model = layers.Activation('sigmoid')(model) # Connect input and output layers discriminator =", "the tensor into a vector model = layers.Flatten()(model) # Apply a fully-conncted layer", "for the low-resolution data. :param channels: Integer containing the number of velocity components", "later use during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to", "model = discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256, 3, 1) model", "1 containing the labels of the predicted data. :return total_loss: Float containing the", "loss loss = content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" #", "data. :return total_loss: Float containing the mean value of the binary cross-entropy for", "filters, strides): \"\"\" Function to generate a residual block :param model: Tensorflow tensor", "the discriminator loss as the mean value of the binary cross-entropy for the", "model]) return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample the", "128, 3, 1) model = discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256,", "layers.LeakyReLU(alpha = 0.2)(model) return model # Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us,", "the convolution operation. :param strides: Integer containing the stride value to ba applied", "information :return loss: Float containg the mean-squared error \"\"\" # Compute the number", "3, 2) model = discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512, 3,", "res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate a residual block :param model:", "* (real_loss + fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self,", "and output layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss", "internal model state. :param kernel_size: Integer containing the kernel (or filter) size for", "input model (skip connection operation) model = layers.Add()([gen, model]) return model def up_sampling_block(model,", "for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y )", "of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size = 9, strides = 1,", "the low-resolution data. :param channels: Integer containing the number of velocity components present", "issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute", "for its use in a residual-block loop res_block = prelu_1 # Apply N", "the generator loss \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() #", "2021 @author: guemesturb \"\"\" import numpy as np import tensorflow as tf import", "size after pixel shuffling. :param input_shape: Tensorflow object containing the tensor size (batch", "data_format='channels_last')(up_sampling) # Connect input and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\"", "class self.us = us self.nx = nx self.ny = ny self.channels = channels", "of the predicted data. :return total_loss: Float containing the mean value of the", "during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator loss", "containing the discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters,", "64, 1) # res_block = res_block_gen(res_block, 3, 128, 1) # Apply a convolutional", "4) model = discriminator_block(model, 128, 3, 1) model = discriminator_block(model, 128, 3, 2)", "the input and output of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) #", "\"\"\" # Define discriminator loss as a function to be returned for its", "target high-resolution fields :param flag: Tensorflow tensor containing boolean information regarding the bins", "Compute mean value total_loss = 0.5 * (real_loss + fake_loss) return total_loss return", "GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to", "# Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a", "strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function model =", "tensor \"\"\" # Copy model for skip-connection purposes gen = model # Apply", "scale=4): \"\"\" Custom layer to shuffle abd reduce tensor filters (last dimension) to", "prelu_1 # Apply N residual blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block,", "width/number of filters. :return: Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\"", "conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU", "blocks model = discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128, 3, 1)", "3, 2) model = discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256, 3,", "for a certain number of bins. :param y_pred: Tensorflow tensor containing the predicted", "later use during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the", "Tensorflow tensor \"\"\" # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size", "tensor containing the internal model state :param filters: Integer containing the number of", "discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator loss as the mean value", "Ledig et al. (2017). This version is modified with respect the original one", "/ (scale ** 2))] # Transform list into tuple output_shape = tuple(dims) return", "Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model", "SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd reduce tensor filters (last dimension)", "ratio to increase/decrease the heigth and width/number of filters. :return: Tensorflow tensor with", "= layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use in a", "class GANPIV(object): def __init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class", "Apply N residual blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64,", "direction for the low-resolution data. :param channels: Integer containing the number of velocity", "convolution operation. :param strides: Integer containing the stride value to ba applied in", "hr_target, fl_target): \"\"\" Function to compute the generator loss as the mean-squared error", "size. :return: Tensorflow tensor with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return", "upsample the wight and height dimensions of the data. :param model: Tensorflow tensor", "alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use in a residual-block loop", "information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss loss", "predicted labels. \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute", "discriminator to identify the target data as real, adding a small perturbation for", "Define generator loss as a function to be returned for its later use", "res_block = prelu_1 # Apply N residual blocks for index in range(self.n_residual_blocks): res_block", "# Define discriminator loss as a function to be returned for its later", "# Compute the capability of the discriminator to identify the target data as", "a Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7", "model = discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512, 3, 1) model", "the generator loss as the mean-squared error between the target and the predicted", "data_format='channels_last')(model) # Add model with input model (skip connection operation) model = layers.Add()([gen,", "** 2))] # Transform list into tuple output_shape = tuple(dims) return output_shape def", "This version is modified with respect the original one by removing the batch", "the upsampling ratio between the low- and high-resolution data. :param nx: Integer containing", "the internal model state. :param kernel_size: Integer containing the kernel (or filter) size", "the target and predicted data only as a function of the bins in", "number of filters to apply in the convolution operation. :param strides: Integer containing", "target data contain information. :return loss: Float containing the generator loss \"\"\" #", "target high-resolution data that contains information N = tf.reduce_sum(flag) # Compute the conditional", "predicted data only as a function of the bins in the target data", "into a vector model = layers.Flatten()(model) # Apply a fully-conncted layer model =", "nx: Integer containing the grid points in the streamwise direction for the low-resolution", "between the target and the predicted high-resolution fields plus and adversarial error for", "to generate a residual block :param model: Tensorflow tensor containing the internal model", "\"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate a residual block", "(self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01() def", "dimensions of the data. :param model: Tensorflow tensor containing the internal model state.", "function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model =", "discriminator model. :return generator_loss: Self-defined Python function containing the generator loss :return discriminator_loss:", "of the data. :param model: Tensorflow tensor containing the internal model state. :param", "up_sampling_block(up_sampling, 3, 256, 1) # Apply the last convolutional layer to assert the", "upsample their height and width. :param input_shape: Tensorflow object containing the tensor size", "in the high-resolution target data contain information. :return loss: Float containing the generator", "Tensorflow tensor containing the internal model state :param filters: Integer containing the number", "guemesturb \"\"\" import numpy as np import tensorflow as tf import tensorflow.keras as", "discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256, 3, 1) model = discriminator_block(model,", "conv_2]) # Upsample the data to the high-resolution dimensions for index in range(int(np.log2(self.us))):", "loss as a function to be returned for its later use during the", "target and predicted data only for a certain number of bins. :param y_pred:", "of bins in the target high-resolution data that contains information N = tf.reduce_sum(flag)", "the labels of the predicted data. :return total_loss: Float containing the mean value", "residual blocks to be applied in the GAN generator. Default is 16. :return:", "return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer =", "= us self.nx = nx self.ny = ny self.channels = channels self.model_name =", "__init__(self, model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate the", "the batch normalization layers. :return generator: Tensorflow object containing the generator model. :return", "= layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1,", "discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128, 3, 1) model = discriminator_block(model,", "0.2)(model) # Apply a fully-conncted layer model = layers.Dense(1)(model) # Apply a sigmoid", "\"\"\" Python class to generate the Tensorflow models for resolution enhancement of PIV", "the mean-squared error between target and predicted data only for a certain number", "size x 1 containing the labels of the predicted data. :return total_loss: Float", "strides = strides, padding = \"same\", data_format='channels_last')(model) # Add model with input model", "# Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU", "generator loss as a function to be returned for its later use during", "model # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size,", "128, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # Apply", "10 11:38:43 2021 @author: guemesturb \"\"\" import numpy as np import tensorflow as", "a residual-block loop res_block = prelu_1 # Apply N residual blocks for index", "# Copy model for its use in a residual-block loop res_block = prelu_1", "layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer inputs = keras.Input(shape=(self.ny,", "filter is equal to the desired number of channels. outputs = layers.Conv2D(filters =", "the grid points in the wall-normal direction for the low-resolution data. :param channels:", "blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) # res_block", "to compute the discriminator loss as the mean value of the binary cross-entropy", "x height x width x filters). \"\"\" # Compute new dimensions dims =", "== 'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function to generate", "Python function containing the generator loss :return discriminator_loss: Self-defined Python function containing the", "generate the Tensorflow models for resolution enhancement of PIV images through GANs. :param", "connection operation) model = layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters, strides):", "= 64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) #", "model: Tensorflow tensor containing the internal model state :param filters: Integer containing the", "state. :param kernel_size: Integer containing the kernel (or filter) size for the convolutional", "use during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute", "the mean-squared error between the target and the predicted high-resolution fields plus and", "model: Tensorflow tensor containing the internal model state. :param kernel_size: Integer containing the", "3, 1) model = discriminator_block(model, 128, 3, 2) model = discriminator_block(model, 256, 3,", "- np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the mean-squared error between the", "\"\"\" Function to generate discriminator blocks. :param model: Tensorflow tensor containing the internal", "total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer", "return output_shape def subpixel(x): \"\"\" Function to change tensor size. :return: Tensorflow tensor", "ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks", "64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2", "cause the discriminator to misidentify the predicted data as real, adding a small", "reduce tensor filters (last dimension) to upsample their height and width. :param input_shape:", "bins in the target high-resolution data that contains information N = tf.reduce_sum(flag) #", "a function of the bins in the target data that contain information content_loss", "Upsample the data to the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling =", "of the binary cross-entropy for the target and predicted labels. :param real_Y: Tensorflow", "sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect input and output layers discriminator", "labels of the target data. :param fake_Y: Tensorflow vector of dimensions batch size", "\"\"\" # Copy model for skip-connection purposes gen = model # Apply convolutional", "object containing the tensor size (batch x height x width x filters). :return:", "filters). :param scale: Integer containing the ratio to increase/decrease the heigth and width/number", "output layers discriminator = keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\"", "error \"\"\" # Compute the number of bins in the target high-resolution data", "Tensorflow tensor containing the predicted high-resolution fields :param hr_target: Tensorflow tensor containing the", "flag: Tensorflow tensor containing boolean information regarding the bins in the target data", "Tensorflow object containing the generator model. :return discriminator: Tensorflow object containing the discriminator", "the number of filters to apply in the convolution operation. :param strides: Integer", "padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros',", "have information :return loss: Float containg the mean-squared error \"\"\" # Compute the", "the generator loss :return discriminator_loss: Self-defined Python function containing the discriminator loss. \"\"\"", "predicted data as real, adding a small perturbation for stability issues adversarial_loss =", "tuple(dims) return output_shape def subpixel(x): \"\"\" Function to change tensor size. :return: Tensorflow", "input and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\"", "number of velocity components present in the data. Default is 2. :param n_residual_blocks", "contain information. :return loss: Float containing the generator loss \"\"\" # Define binary", "by removing the batch normalization layers. :return generator: Tensorflow object containing the generator", "to apply in the convolution operation. :param kernel_size: Integer containing the kernel (or", "Apply a fully-conncted layer model = layers.Dense(1)(model) # Apply a sigmoid connection function", "after pixel shuffling. :param input_shape: Tensorflow object containing the tensor size (batch x", "loss: Float containing the generator loss \"\"\" # Define binary cross-entropy function cross_entropy", "to the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256,", "\"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability", "# Apply N residual blocks for index in range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3,", "model_name, us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow", "x 1 containing the labels of the target data. :param fake_Y: Tensorflow vector", "= model # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size =", ":return model: Tensorflow tensor \"\"\" # Apply convolutional operation model = layers.Conv2D(filters =", "bins in the high-resolution target data contain information. :return loss: Float containing the", "information N = tf.reduce_sum(flag) # Compute the conditional mean-squared error loss = tf.math.divide(", "layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd reduce tensor filters", "us: Integer containing the upsampling ratio between the low- and high-resolution data. :param", "strides = 1, padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation", "layer to shuffle abd reduce tensor filters (last dimension) to upsample their height", "= 0.2)(model) # Apply a fully-conncted layer model = layers.Dense(1)(model) # Apply a", "the assigned name to the model, for storage purposes. :param us: Integer containing", "assert the number of filter is equal to the desired number of channels.", "scale=2)(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model)", "containing the stride value to ba applied in the convolutional operations. :return model:", "model = layers.Flatten()(model) # Apply a fully-conncted layer model = layers.Dense(1024)(model) # Apply", "target data. :param fake_Y: Tensorflow vector of dimensions batch size x 1 containing", "fields plus and adversarial error for the perdicted fields. :param fake_Y: Tensorflow vector", "kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Add model with input", "layers.Conv2D(filters = 128, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block)", "= 0.2)(model) return model # Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels),", "Default is 16. :return: \"\"\" # Declare variable inside the class self.us =", "capability of the discriminator to identify the target data as real, adding a", "Apply a sigmoid connection function model = layers.Activation('sigmoid')(model) # Connect input and output", "convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size, strides = strides,", "data to the high-resolution dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3,", "\"\"\" Function to compute the new tensor size after pixel shuffling. :param input_shape:", "data that contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) #", "to upsample their height and width. :param input_shape: Tensorflow object containing the tensor", "discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512, 3, 2) # Flatten the", "strides = 1, padding = \"same\", data_format='channels_last')(res_block) # Apply one last skip connection", "as real, adding a small perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape)", "tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom layer to shuffle abd reduce", "generator: Tensorflow object containing the generator model. :return discriminator: Tensorflow object containing the", "import numpy as np import tensorflow as tf import tensorflow.keras as keras import", "model = discriminator_block(model, 512, 3, 2) # Flatten the tensor into a vector", "version is modified with respect the original one by removing the batch normalization", "model = discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128, 3, 1) model", "contain information content_loss = custom_mse_loss( hr_target, tf.math.multiply(hr_predic, fl_target), fl_target ) # Compute loss", "to shuffle abd reduce tensor filters (last dimension) to upsample their height and", "grid points in the wall-normal direction for the low-resolution data. :param channels: Integer", "and the predicted high-resolution fields plus and adversarial error for the perdicted fields.", "# -*- coding: utf-8 -*- \"\"\" Created on Sat Apr 10 11:38:43 2021", ":return generator_loss: Self-defined Python function containing the generator loss :return discriminator_loss: Self-defined Python", "range(self.n_residual_blocks): res_block = res_block_gen(res_block, 3, 64, 1) # res_block = res_block_gen(res_block, 3, 128,", "in the wall-normal direction for the low-resolution data. :param channels: Integer containing the", "mean value of the binary cross-entropy for the target and predicted labels. :param", "layers. :return generator: Tensorflow object containing the generator model. :return discriminator: Tensorflow object", "Function to compute the generator loss as the mean-squared error between the target", "tf.reduce_sum(flag) # Compute the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract(", "input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] / (scale ** 2))] # Transform", "the predicted high-resolution fields :param hr_target: Tensorflow tensor containing the target high-resolution fields", "3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters =", "fields. :param fake_Y: Tensorflow vector of dimensions batch size x 1 containing the", "input and output of the residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample", "# Define generator loss as a function to be returned for its later", "discriminator: Tensorflow object containing the discriminator model. :return generator_loss: Self-defined Python function containing", "model: Tensorflow tensor \"\"\" # Apply convolutional operation model = layers.Conv2D(filters = filters,", "of dimensions batch size x 1 containing the labels of the predicted data.", "self.channels = channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if", "the SRGAN architecture as Ledig et al. (2017). This version is modified with", "= layers.Conv2D(filters = filters, kernel_size = kernal_size, strides = strides, padding = \"same\",", "binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator", "containing the labels of the predicted data. :param hr_predic: Tensorflow tensor containing the", "contains information N = tf.reduce_sum(flag) # Compute the conditional mean-squared error loss =", "high-resolution target data contain information. :return loss: Float containing the generator loss \"\"\"", "128, 1) # Apply a convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size", "padding='same')(inputs) # Apply a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None,", "the kernel (or filter) size for the convolutional operations :param strides: Integer containing", "kernel_size, strides): \"\"\" Function to generate discriminator blocks. :param model: Tensorflow tensor containing", "\"\"\" import numpy as np import tensorflow as tf import tensorflow.keras as keras", "= strides, padding = \"same\", data_format='channels_last')(model) # Add model with input model (skip", "input_shape: Tensorflow object containing the tensor size (batch x height x width x", "= strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model =", "int(input_shape[3] / (scale ** 2))] # Transform list into tuple output_shape = tuple(dims)", "modified with respect the original one by removing the batch normalization layers. :return", "Integer containing the stride value to ba applied in the convolutional operations. :return", "its later use during the training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function", "hr_predic, hr_target, fl_target): \"\"\" Function to compute the generator loss as the mean-squared", "Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) #", "model = layers.Conv2D(filters = filters, kernel_size = kernel_size, strides = strides, padding =", "# Compute the mean-squared error between the target and predicted data only as", "dimensions batch size x 1 containing the labels of the predicted data. :param", "to be returned for its later use during the training def discriminator_loss(real_Y, fake_Y):", "filters: Integer containing the number of filters to apply in the convolution operation.", "kernel (or filter) size for the convolutional operations :param strides: Integer containing the", "the capability of the discriminator to identify the predicted data as fake, adding", "function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator to identify", "layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer model =", "x height x width x filters). :param scale: Integer containing the ratio to", "keras.Model(inputs=inputs, outputs = model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator loss", "tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ), N ) return loss", "us, nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow models", "data. :param hr_predic: Tensorflow tensor containing the predicted high-resolution fields :param hr_target: Tensorflow", "perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss", "fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss = 0.5 * (real_loss", "strides, padding = \"same\", data_format='channels_last')(model) # Add model with input model (skip connection", "adding a small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y)", "real, adding a small perturbation for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2,", "# Declare variable inside the class self.us = us self.nx = nx self.ny", "through GANs. :param model_name: String containing the assigned name to the model, for", "model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer model = layers.Dense(1)(model)", "operations. :param filters: Integer containing the number of filters to apply in the", "function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use", "channels=2, n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow models for resolution enhancement", "Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the", "wall-normal direction for the low-resolution data. :param channels: Integer containing the number of", "512, 3, 2) # Flatten the tensor into a vector model = layers.Flatten()(model)", "as fake, adding a small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y)", "strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function", "= layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters =", "the wight and height dimensions of the data. :param model: Tensorflow tensor containing", "conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9,", "batch normalization layers. :return generator: Tensorflow object containing the generator model. :return discriminator:", "activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input", "containing the kernel (or filter) size for the convolutional operations :param strides: Integer", "* 0.2, fake_Y ) # Compute the mean-squared error between the target and", "SRGAN architecture as Ledig et al. (2017). This version is modified with respect", "tensor containing the information about which bins in the high-resolution target data contain", "data only for a certain number of bins. :param y_pred: Tensorflow tensor containing", "scale, input_shape[2] * scale, int(input_shape[3] / (scale ** 2))] # Transform list into", "architecture01(self): \"\"\" Function to generate the SRGAN architecture as Ledig et al. (2017).", "training def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute the mean-squared error", "Tuple containing the rescaled tensor size (batch x height x width x filters).", "return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object): def __init__(self, model_name, us,", "to upsample the wight and height dimensions of the data. :param model: Tensorflow", "a convolutional layer model = layers.Conv2D(filters = 64, kernel_size = 3, strides =", "padding = \"same\", data_format='channels_last')(model) # Add model with input model (skip connection operation)", "= 1, padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function", "size for the convolutional operations :param strides: Integer containing the stride value to", "def architecture01(self): \"\"\" Function to generate the SRGAN architecture as Ledig et al.", "= up_sampling_block(up_sampling, 3, 256, 1) # Apply the last convolutional layer to assert", "-*- coding: utf-8 -*- \"\"\" Created on Sat Apr 10 11:38:43 2021 @author:", "- np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the discriminator to identify the", "et al. (2017). This version is modified with respect the original one by", "kernel_size: Integer containing the kernel (or filter) size for the convolutional operations :param", "= 1, padding = \"same\", data_format='channels_last')(res_block) # Apply one last skip connection between", "loss \"\"\" Discriminator loss \"\"\" # Define discriminator loss as a function to", "1) # Apply the last convolutional layer to assert the number of filter", "= \"same\", data_format='channels_last')(up_sampling) # Connect input and output layers generator = keras.Model(inputs, outputs,", ") ), N ) return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function", "tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape,", "kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(inputs) # Apply a", "= 0.2)(model) # Apply 7 discriminator blocks model = discriminator_block(model, 64, 3, 4)", "kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation", "data contain information. :return loss: Float containing the generator loss \"\"\" # Define", ":param filters: Integer containing the number of filters to apply in the convolution", "containing the generator loss \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy()", "boolean information regarding the bins in the target data that have information :return", "16. :return: \"\"\" # Declare variable inside the class self.us = us self.nx", "self.nx = nx self.ny = ny self.channels = channels self.model_name = model_name self.n_residual_blocks", "that have information :return loss: Float containg the mean-squared error \"\"\" # Compute", "Compute the mean-squared error between the target and predicted data only as a", "discriminator to misidentify the predicted data as real, adding a small perturbation for", "np import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers", "pixel shuffling. :param input_shape: Tensorflow object containing the tensor size (batch x height", "prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(conv_1) # Copy model for its use in", "model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate discriminator blocks.", "strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs)", "data. :param fake_Y: Tensorflow vector of dimensions batch size x 1 containing the", "the GAN generator. Default is 16. :return: \"\"\" # Declare variable inside the", "self.us = us self.nx = nx self.ny = ny self.channels = channels self.model_name", "layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted layer model = layers.Dense(1)(model) # Apply", "streamwise direction for the low-resolution data. :param ny: Integer containing the grid points", "1) model = discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512, 3, 1)", "Define discriminator loss as a function to be returned for its later use", "generator. Default is 16. :return: \"\"\" # Declare variable inside the class self.us", "the capability of the generator to cause the discriminator to misidentify the predicted", "the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute the discriminator loss as", "= \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function model = layers.LeakyReLU(alpha", "in a residual-block loop res_block = prelu_1 # Apply N residual blocks for", "generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute the generator loss as the", "containg the mean-squared error \"\"\" # Compute the number of bins in the", "mean-squared error between the target and the predicted high-resolution fields plus and adversarial", "np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the discriminator to identify the predicted", "\"\"\" Function to generate a residual block :param model: Tensorflow tensor containing the", "generate the SRGAN architecture as Ledig et al. (2017). This version is modified", "discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\"", "= tf.keras.losses.BinaryCrossentropy() # Compute the capability of the generator to cause the discriminator", "the low- and high-resolution data. :param nx: Integer containing the grid points in", "filters). :return: Tuple containing the rescaled tensor size (batch x height x width", ":param scale: Integer containing the ratio to increase/decrease the heigth and width/number of", "a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1", "Float containing the generator loss \"\"\" # Define binary cross-entropy function cross_entropy =", "enhancement of PIV images through GANs. :param model_name: String containing the assigned name", "a convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size = 3, strides =", "loop res_block = prelu_1 # Apply N residual blocks for index in range(self.n_residual_blocks):", "shuffle abd reduce tensor filters (last dimension) to upsample their height and width.", "= strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU activation function model", "to generate the Tensorflow models for resolution enhancement of PIV images through GANs.", ") ) ), N ) return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\"", "utf-8 -*- \"\"\" Created on Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\"", "= layers.Activation('sigmoid')(model) # Connect input and output layers discriminator = keras.Model(inputs=inputs, outputs =", "layer model = layers.Dense(1)(model) # Apply a sigmoid connection function model = layers.Activation('sigmoid')(model)", "<filename>libs/models.py # -*- coding: utf-8 -*- \"\"\" Created on Sat Apr 10 11:38:43", "identify the target data as real, adding a small perturbation for stability issues", "kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # Apply one", "compute the new tensor size after pixel shuffling. :param input_shape: Tensorflow object containing", "def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample the wight and height", "operations. :return model: Tensorflow tensor \"\"\" # Apply convolutional operation model = layers.Conv2D(filters", "labels. \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the", ":param us: Integer containing the upsampling ratio between the low- and high-resolution data.", "returned for its later use during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function", "high-resolution fields plus and adversarial error for the perdicted fields. :param fake_Y: Tensorflow", "data_format='channels_last')(model) # Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric", "# Compute the capability of the generator to cause the discriminator to misidentify", "the number of filter is equal to the desired number of channels. outputs", "Function to compute the new tensor size after pixel shuffling. :param input_shape: Tensorflow", "loss :return discriminator_loss: Self-defined Python function containing the discriminator loss. \"\"\" \"\"\" Generator", "on Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import numpy as np", "to be applied in the GAN generator. Default is 16. :return: \"\"\" #", "between the low- and high-resolution data. :param nx: Integer containing the grid points", "containing the predicted high-resolution fields :param hr_target: Tensorflow tensor containing the target high-resolution", "the generator model. :return discriminator: Tensorflow object containing the discriminator model. :return generator_loss:", "the convolutional operations. :return model: Tensorflow tensor \"\"\" # Apply convolutional operation model", "value of the binary cross-entropy for the target and predicted labels. :param real_Y:", "fl_target ) # Compute loss loss = content_loss + 1e-3*adversarial_loss return loss \"\"\"", "layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block)", "data that contains information N = tf.reduce_sum(flag) # Compute the conditional mean-squared error", "Tensorflow object containing the discriminator model. :return generator_loss: Self-defined Python function containing the", "the labels of the target data. :param fake_Y: Tensorflow vector of dimensions batch", "discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512, 3, 1) model = discriminator_block(model,", "the original one by removing the batch normalization layers. :return generator: Tensorflow object", "data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply", "the streamwise direction for the low-resolution data. :param ny: Integer containing the grid", "residual block :param model: Tensorflow tensor containing the internal model state. :param kernel_size:", "to cause the discriminator to misidentify the predicted data as real, adding a", "discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256, 3, 2) model = discriminator_block(model,", "the discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides):", "= 128, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) #", "error for the perdicted fields. :param fake_Y: Tensorflow vector of dimensions batch size", "for the convolutional operations. :param filters: Integer containing the number of filters to", "operations. :return model: Tensorflow tensor \"\"\" # Copy model for skip-connection purposes gen", "loss: Float containg the mean-squared error \"\"\" # Compute the number of bins", "= layers.Conv2D(filters = filters, kernel_size = kernel_size, strides = strides, padding = \"same\",", "as the mean value of the binary cross-entropy for the target and predicted", "Apply 7 discriminator blocks model = discriminator_block(model, 64, 3, 4) model = discriminator_block(model,", "def custom_mse_loss(y_pred, y_true, flag): \"\"\" Custom function to compute the mean-squared error between", "with rescaled dimensions \"\"\" return tf.nn.depth_to_space(x, scale, data_format='NHWC') return layers.Lambda(subpixel, output_shape=subpixel_shape) class GANPIV(object):", "Copy model for its use in a residual-block loop res_block = prelu_1 #", "containing the kernel (or filter) size for the convolutional operations. :param filters: Integer", "\"\"\" # Declare variable inside the class self.us = us self.nx = nx", "fake_loss) return total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer =", "the last convolutional layer to assert the number of filter is equal to", "import tensorflow.keras as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4): \"\"\" Custom", "vector of dimensions batch size x 1 containing the labels of the target", "subpixel(x): \"\"\" Function to change tensor size. :return: Tensorflow tensor with rescaled dimensions", "filters, kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply", "function to compute the mean-squared error between target and predicted data only for", "= prelu_1 # Apply N residual blocks for index in range(self.n_residual_blocks): res_block =", "self.nx, self.channels), name='low-res-input') # Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9, strides=1,", "gen = model # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size", "\"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size, filters, strides): \"\"\" Function to generate", "data as real, adding a small perturbation for stability issues adversarial_loss = cross_entropy(", "layers.Dense(1024)(model) # Apply a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply", "model for its use in a residual-block loop res_block = prelu_1 # Apply", "the perdicted fields. :param fake_Y: Tensorflow vector of dimensions batch size x 1", "self.channels), name='high-res-input') # Apply a convolutional layer model = layers.Conv2D(filters = 64, kernel_size", "= layers.Conv2D(filters = 128, kernel_size = 3, strides = 1, padding = \"same\",", "Apply a convolutional layer conv_2 = layers.Conv2D(filters = 64, kernel_size = 3, strides", "return total_loss return generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate)", "= keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional layer conv_1 = layers.Conv2D(filters=64,", "of the target data. :param fake_Y: Tensorflow vector of dimensions batch size x", "Flatten the tensor into a vector model = layers.Flatten()(model) # Apply a fully-conncted", "Apply a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a fully-conncted", "the target and predicted labels. :param real_Y: Tensorflow vector of dimensions batch size", "for stability issues real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability", "stride value to ba applied in the convolutional operations. :return model: Tensorflow tensor", "model state :param filters: Integer containing the number of filters to apply in", "real_loss = cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the discriminator", ":param model: Tensorflow tensor containing the internal model state. :param kernel_size: Integer containing", ":param ny: Integer containing the grid points in the wall-normal direction for the", "to increase/decrease the heigth and width/number of filters. :return: Tensorflow tensor with rescaled", "containing the discriminator model. :return generator_loss: Self-defined Python function containing the generator loss", "# Connect input and output layers generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator", "residual-block loop up_sampling = layers.Add()([prelu_1, conv_2]) # Upsample the data to the high-resolution", "data. :param ny: Integer containing the grid points in the wall-normal direction for", "N ) return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute", "Created on Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import numpy as", "padding = \"same\", data_format='channels_last')(res_block) # Apply one last skip connection between the input", "# Transform list into tuple output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\"", "Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function model", "keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input') # Apply a convolutional layer conv_1 = layers.Conv2D(filters=64, kernel_size=9,", "= discriminator_block(model, 64, 3, 4) model = discriminator_block(model, 128, 3, 1) model =", "Compute the number of bins in the target high-resolution data that contains information", "the desired number of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size = 9,", ":return: \"\"\" # Declare variable inside the class self.us = us self.nx =", "containing the rescaled tensor size (batch x height x width x filters). \"\"\"", "shared_axes=[1,2])(model) return model # Define input layer inputs = keras.Input(shape=(self.ny, self.nx, self.channels), name='low-res-input')", "self.architecture01() def architecture01(self): \"\"\" Function to generate the SRGAN architecture as Ledig et", "a certain number of bins. :param y_pred: Tensorflow tensor containing the predicted high-resolution", "\"\"\" Function to compute the generator loss as the mean-squared error between the", "data as fake, adding a small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2,", "up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample the wight and height dimensions", "= 3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # Apply one last", "activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros',", "= layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) return model # Define input layer inputs =", "padding = \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size = 3,", "= discriminator_block(model, 256, 3, 1) model = discriminator_block(model, 256, 3, 2) model =", "subpixel_shape(input_shape): \"\"\" Function to compute the new tensor size after pixel shuffling. :param", "shared_axes=[1,2])(conv_1) # Copy model for its use in a residual-block loop res_block =", "fake_Y: Tensorflow vector of dimensions batch size x 1 containing the labels of", "dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the new tensor size after", "grid points in the streamwise direction for the low-resolution data. :param ny: Integer", "real_Y) # Compute the capability of the discriminator to identify the predicted data", "y_true: Tensorflow tensor containing the target high-resolution fields :param flag: Tensorflow tensor containing", "np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the mean-squared error between the target", "(scale ** 2))] # Transform list into tuple output_shape = tuple(dims) return output_shape", "ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation", "self.n_residual_blocks = n_residual_blocks return def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name ==", "binary cross-entropy for the target and predicted labels. :param real_Y: Tensorflow vector of", "\"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function to generate", "ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) return model # Define input", "layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks model = discriminator_block(model, 64, 3,", "3, strides = 1, padding = \"same\", data_format='channels_last')(inputs) # Apply a Leaky ReLU", "adding a small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute", "np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2, fake_Y ) # Compute the mean-squared error between", "= 64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(inputs) #", "= kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Parametric ReLU", "model, name='SRGAN-Discriminator') \"\"\" Generator loss \"\"\" # Define generator loss as a function", "\"\"\" Discriminator loss \"\"\" # Define discriminator loss as a function to be", "skip connection between the input and output of the residual-block loop up_sampling =", "its later use during the training def discriminator_loss(real_Y, fake_Y): \"\"\" Function to compute", "# conv_2 = layers.Conv2D(filters = 128, kernel_size = 3, strides = 1, padding", "layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer model", "and adversarial error for the perdicted fields. :param fake_Y: Tensorflow vector of dimensions", "= SubpixelConv2D(model.shape, scale=2)(model) # Apply Parametric ReLU activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None,", "self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\" Function to generate the SRGAN architecture", "of the discriminator to identify the predicted data as fake, adding a small", "= layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to", "small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value", "to ba applied in the convolutional operations. :return model: Tensorflow tensor \"\"\" #", "x filters). \"\"\" # Compute new dimensions dims = [input_shape[0], input_shape[1] * scale,", "kernel_size = kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle", "cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the discriminator to identify", "the information about which bins in the high-resolution target data contain information. :return", "# Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a", "function containing the discriminator loss. \"\"\" \"\"\" Generator model \"\"\" def res_block_gen(model, kernal_size,", "target and predicted labels. :param real_Y: Tensorflow vector of dimensions batch size x", ":return: Tuple containing the rescaled tensor size (batch x height x width x", "\"\"\" Custom function to compute the mean-squared error between target and predicted data", "containing the ratio to increase/decrease the heigth and width/number of filters. :return: Tensorflow", "in the GAN generator. Default is 16. :return: \"\"\" # Declare variable inside", "256, 1) # Apply the last convolutional layer to assert the number of", "purposes. :param us: Integer containing the upsampling ratio between the low- and high-resolution", "model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample the wight and", "= discriminator_block(model, 512, 3, 1) model = discriminator_block(model, 512, 3, 2) # Flatten", "data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation function prelu_1 = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None,", "= discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512, 3, 1) model =", "kernel (or filter) size for the convolutional operations. :param filters: Integer containing the", "Apply one last skip connection between the input and output of the residual-block", "operations :param strides: Integer containing the stride value to ba applied in the", "return self.architecture01() def architecture01(self): \"\"\" Function to generate the SRGAN architecture as Ledig", "\"\"\" Generator loss \"\"\" # Define generator loss as a function to be", "= filters, kernel_size = kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) #", "kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer", "size (batch x height x width x filters). :return: Tuple containing the rescaled", "1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" # Define discriminator loss as a", "3, strides = 1, padding = \"same\", data_format='channels_last')(res_block) # Apply one last skip", "input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input') # Apply a convolutional layer", "layer model = layers.Dense(1024)(model) # Apply a convolutional layer model = layers.LeakyReLU(alpha =", "cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute the capability of the discriminator to", "containing the number of filters to apply in the convolution operation. :param strides:", "generator model. :return discriminator: Tensorflow object containing the discriminator model. :return generator_loss: Self-defined", "Tensorflow vector of dimensions batch size x 1 containing the labels of the", "which bins in the high-resolution target data contain information. :return loss: Float containing", "= \"same\", data_format='channels_last')(res_block) # conv_2 = layers.Conv2D(filters = 128, kernel_size = 3, strides", "1 containing the labels of the predicted data. :param hr_predic: Tensorflow tensor containing", "output_shape = tuple(dims) return output_shape def subpixel(x): \"\"\" Function to change tensor size.", "heigth and width/number of filters. :return: Tensorflow tensor with rescaled dimensions \"\"\" def", "shuffling. :param input_shape: Tensorflow object containing the tensor size (batch x height x", "= cross_entropy(np.ones(real_Y.shape) - np.random.random_sample(real_Y.shape)*0.2, real_Y) # Compute the capability of the discriminator to", "in the convolution operation. :param kernel_size: Integer containing the kernel (or filter) size", "for skip-connection purposes gen = model # Apply convolutional operation model = layers.Conv2D(filters", "the predicted data as real, adding a small perturbation for stability issues adversarial_loss", "respect the original one by removing the batch normalization layers. :return generator: Tensorflow", "= \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model) #", "layers.Conv2D(filters = filters, kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model)", "outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\" Function", "applied in the GAN generator. Default is 16. :return: \"\"\" # Declare variable", "conv_2 = layers.Conv2D(filters = 128, kernel_size = 3, strides = 1, padding =", "if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01()", "keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size, strides): \"\"\"", "return loss def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute the generator", "Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import numpy as np import tensorflow", "range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply the last convolutional layer", "small perturbation for stability issues adversarial_loss = cross_entropy( np.ones(fake_Y.shape) - np.random.random_sample(fake_Y.shape) * 0.2,", "generator = keras.Model(inputs, outputs, name='SRGAN-Generator') \"\"\" Discriminator model \"\"\" def discriminator_block(model, filters, kernel_size,", "target and predicted labels. \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy()", "containing the target high-resolution fields :param flag: Tensorflow tensor containing boolean information regarding", "binary cross-entropy for the target and predicted labels. \"\"\" # Define binary cross-entropy", "model = layers.Add()([gen, model]) return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function", "kernel_size = 9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input", "tensor size (batch x height x width x filters). :param scale: Integer containing", "Function to generate a residual block :param model: Tensorflow tensor containing the internal", "compute the generator loss as the mean-squared error between the target and the", "strides): \"\"\" Function to upsample the wight and height dimensions of the data.", "convolutional operations. :return model: Tensorflow tensor \"\"\" # Copy model for skip-connection purposes", "alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size", "def generator_loss(fake_Y, hr_predic, hr_target, fl_target): \"\"\" Function to compute the generator loss as", "in the convolution operation. :param strides: Integer containing the stride value to ba", "# Apply the last convolutional layer to assert the number of filter is", "mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred ) ) ),", "model_name: String containing the assigned name to the model, for storage purposes. :param", "rescaled tensor size (batch x height x width x filters). \"\"\" # Compute", "def build_architecture(self): if (self.model_name == 'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else:", "containing the generator model. :return discriminator: Tensorflow object containing the discriminator model. :return", "= layers.Add()([prelu_1, conv_2]) # Upsample the data to the high-resolution dimensions for index", "N = tf.reduce_sum(flag) # Compute the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum(", "rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to compute the new tensor size", "= kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Add model with", "x 1 containing the labels of the predicted data. :param hr_predic: Tensorflow tensor", "= \"same\", data_format='channels_last')(model) # Add model with input model (skip connection operation) model", "fully-conncted layer model = layers.Dense(1024)(model) # Apply a convolutional layer model = layers.LeakyReLU(alpha", "# res_block = res_block_gen(res_block, 3, 128, 1) # Apply a convolutional layer conv_2", "for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) # Compute mean value total_loss =", "the number of bins in the target high-resolution data that contains information N", "9, strides = 1, padding = \"same\", data_format='channels_last')(up_sampling) # Connect input and output", "images through GANs. :param model_name: String containing the assigned name to the model,", "= tf.reduce_sum(flag) # Compute the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square(", "with input model (skip connection operation) model = layers.Add()([gen, model]) return model def", "of the predicted data. :param hr_predic: Tensorflow tensor containing the predicted high-resolution fields", "scale, int(input_shape[3] / (scale ** 2))] # Transform list into tuple output_shape =", "is 16. :return: \"\"\" # Declare variable inside the class self.us = us", "dimensions batch size x 1 containing the labels of the predicted data. :return", "= layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation", "mean-squared error between the target and predicted data only as a function of", "\"same\", data_format='channels_last')(model) # Apply Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model)", "vector of dimensions batch size x 1 containing the labels of the predicted", "\"\"\" Created on Sat Apr 10 11:38:43 2021 @author: guemesturb \"\"\" import numpy", "nx self.ny = ny self.channels = channels self.model_name = model_name self.n_residual_blocks = n_residual_blocks", "layers.Conv2D(filters=64, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear',", "function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator blocks model =", "kernel_size = kernel_size, strides = strides, padding = \"same\", data_format='channels_last')(model) # Apply Leaky", "ba applied in the convolutional operations. :return model: Tensorflow tensor \"\"\" # Apply", "0.2)(model) return model # Define input layer inputs = keras.Input(shape=(self.ny*self.us, self.nx*self.us, self.channels), name='high-res-input')", "activation function model = layers.PReLU(alpha_initializer='zeros', alpha_regularizer=None, alpha_constraint=None, shared_axes=[1,2])(model) # Apply convolutional operation model", "the bins in the target data that contain information content_loss = custom_mse_loss( hr_target,", "Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) return model # Define", "target data that have information :return loss: Float containg the mean-squared error \"\"\"", "of filters to apply in the convolution operation. :param strides: Integer containing the", "height dimensions of the data. :param model: Tensorflow tensor containing the internal model", "n_residual_blocks : Integer containing the number residual blocks to be applied in the", "number of bins in the target high-resolution data that contains information N =", "dimensions for index in range(int(np.log2(self.us))): up_sampling = up_sampling_block(up_sampling, 3, 256, 1) # Apply", "identify the predicted data as fake, adding a small perturbation for stability issues", "storage purposes. :param us: Integer containing the upsampling ratio between the low- and", "generator loss \"\"\" # Define binary cross-entropy function cross_entropy = tf.keras.losses.BinaryCrossentropy() # Compute", "tensor filters (last dimension) to upsample their height and width. :param input_shape: Tensorflow", "the target high-resolution data that contains information N = tf.reduce_sum(flag) # Compute the", "new dimensions dims = [input_shape[0], input_shape[1] * scale, input_shape[2] * scale, int(input_shape[3] /", "as tf import tensorflow.keras as keras import tensorflow.keras.layers as layers def SubpixelConv2D(input_shape, scale=4):", "the number of velocity components present in the data. Default is 2. :param", "for the target and predicted labels. \"\"\" # Define binary cross-entropy function cross_entropy", "3, 1) model = discriminator_block(model, 256, 3, 2) model = discriminator_block(model, 512, 3,", "model = layers.Dense(1)(model) # Apply a sigmoid connection function model = layers.Activation('sigmoid')(model) #", "# Apply convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernal_size, strides", "'architecture-01') or (self.model_name == 'architecture01'): return self.architecture01() else: return self.architecture01() def architecture01(self): \"\"\"", "is 2. :param n_residual_blocks : Integer containing the number residual blocks to be", "2))] # Transform list into tuple output_shape = tuple(dims) return output_shape def subpixel(x):", "activation='linear', data_format='channels_last', padding='same')(inputs) # conv_1 = layers.Conv2D(filters=128, kernel_size=9, strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) #", "target high-resolution fields :param fl_target: Tensorflow tensor containing the information about which bins", "= content_loss + 1e-3*adversarial_loss return loss \"\"\" Discriminator loss \"\"\" # Define discriminator", "batch size x 1 containing the labels of the predicted data. :return total_loss:", "nx, ny, channels=2, n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow models for", "convolutional layer to assert the number of filter is equal to the desired", "the target data. :param fake_Y: Tensorflow vector of dimensions batch size x 1", "the conditional mean-squared error loss = tf.math.divide( tf.reduce_sum( tf.math.square( tf.math.subtract( y_true, y_pred )", "to the model, for storage purposes. :param us: Integer containing the upsampling ratio", "GANs. :param model_name: String containing the assigned name to the model, for storage", "return model def up_sampling_block(model, kernel_size, filters, strides): \"\"\" Function to upsample the wight", "# Apply a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model) # Apply a", "Apply a fully-conncted layer model = layers.Dense(1024)(model) # Apply a convolutional layer model", "labels of the predicted data. :return total_loss: Float containing the mean value of", "for the low-resolution data. :param ny: Integer containing the grid points in the", "the generator to cause the discriminator to misidentify the predicted data as real,", "= filters, kernel_size = kernal_size, strides = strides, padding = \"same\", data_format='channels_last')(model) #", "generate discriminator blocks. :param model: Tensorflow tensor containing the internal model state :param", "# Add model with input model (skip connection operation) model = layers.Add()([gen, model])", "Declare variable inside the class self.us = us self.nx = nx self.ny =", "\"\"\" Function to generate the SRGAN architecture as Ledig et al. (2017). This", "and high-resolution data. :param nx: Integer containing the grid points in the streamwise", "containing the number residual blocks to be applied in the GAN generator. Default", "padding = \"same\", data_format='channels_last')(model) # Apply Pixxle Shuffle layer model = SubpixelConv2D(model.shape, scale=2)(model)", "n_residual_blocks=16): \"\"\" Python class to generate the Tensorflow models for resolution enhancement of", "Compute the capability of the generator to cause the discriminator to misidentify the", "capability of the discriminator to identify the predicted data as fake, adding a", "fake, adding a small perturbation for stability issues fake_loss = cross_entropy(np.random.random_sample(fake_Y.shape)*0.2, fake_Y) #", "convolutional operations. :param filters: Integer containing the number of filters to apply in", "tf.math.subtract( y_true, y_pred ) ) ), N ) return loss def generator_loss(fake_Y, hr_predic,", "containing the labels of the predicted data. :return total_loss: Float containing the mean", "generator, discriminator, generator_loss, discriminator_loss def optimizer(self, learning_rate): generator_optimizer = tf.keras.optimizers.Adam(learning_rate) discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate)", "convolutional operation model = layers.Conv2D(filters = filters, kernel_size = kernel_size, strides = strides,", "desired number of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size = 9, strides", "layers.Conv2D(filters = 64, kernel_size = 3, strides = 1, padding = \"same\", data_format='channels_last')(inputs)", "Discriminator loss \"\"\" # Define discriminator loss as a function to be returned", "filters. :return: Tensorflow tensor with rescaled dimensions \"\"\" def subpixel_shape(input_shape): \"\"\" Function to", "Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model) # Apply 7 discriminator", ":param fake_Y: Tensorflow vector of dimensions batch size x 1 containing the labels", "the new tensor size after pixel shuffling. :param input_shape: Tensorflow object containing the", "hr_predic: Tensorflow tensor containing the predicted high-resolution fields :param hr_target: Tensorflow tensor containing", "target and the predicted high-resolution fields plus and adversarial error for the perdicted", ":return model: Tensorflow tensor \"\"\" # Copy model for skip-connection purposes gen =", "data_format='channels_last')(inputs) # Apply a Leaky ReLU activation function model = layers.LeakyReLU(alpha = 0.2)(model)", "generator loss :return discriminator_loss: Self-defined Python function containing the discriminator loss. \"\"\" \"\"\"", "strides=1, activation='linear', data_format='channels_last', padding='same')(inputs) # Apply a Parametric ReLU activation function prelu_1 =", "number of channels. outputs = layers.Conv2D(filters = self.channels, kernel_size = 9, strides =", "\"\"\" # Define generator loss as a function to be returned for its", "model = layers.Dense(1024)(model) # Apply a convolutional layer model = layers.LeakyReLU(alpha = 0.2)(model)", "to compute the new tensor size after pixel shuffling. :param input_shape: Tensorflow object", "the predicted high-resolution fields :param y_true: Tensorflow tensor containing the target high-resolution fields" ]
[ "import subprocess from quart import session from async_http import AsyncHTTP from config import", "creating a system user account. Args: self: an instance of the CreateTwilioAccount class", "params=params) user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception as e:", "sign up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method", "for assigning a sms-enabled number to a Twilio subaccount. Args: self: an instance", "params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params)", "config import auth_token from config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name", "'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri,", "auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number)", "user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception as e: print('Twilio", "string: the sms number to buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format(", "of available, sms-enabled phone numbers in a given area code. Calls private helper", "def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning a sms-enabled number to", "just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri", "private method for getting a list of available, sms-enabled phone numbers in a", "getting a list of available, sms-enabled phone numbers in a given area code.", "a given area code. Calls private helper methods to complete the process of", "} request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await self.async_http.post( base_uri=request_uri, params=params) return", "an instance of the CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token':", "twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri", "buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post(", "AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri", "numbers in a given area code. Calls private helper methods to complete the", "params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid,", "twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import auth_token from config import admin_sid", "async def _get_sms_user(self, user_sid): \"\"\"A private method for getting a list of available,", "auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await self.async_http.post(", "= AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating a system user account.", "config import twilio_assign_new_number_base_uri from config import auth_token from config import admin_sid class CreateTwilioAccount:", "e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A", "return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method for getting a list", "\"\"\"A private method for getting a list of available, sms-enabled phone numbers in", "await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user", "purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri =", "twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try:", "params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params)", "complete the process of purchasing a number from the list, and assigning it", "CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri)", "NOTE: the area code is set on the session. Args: self: an instance", "assigning it to the Twilio subaccount. NOTE: the area code is set on", "_purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing a given sms-enabled number. Args:", "return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning a", "private helper methods to complete the process of purchasing a number from the", "from config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http", "and assigning it to the Twilio subaccount. NOTE: the area code is set", "response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return", "import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import", "private method for purchasing a given sms-enabled number. Args: self: an instance of", "def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing a given sms-enabled number.", "twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number)", "instance of the CreateTwilioAccount class user_sid: string sms_number: string: the number that was", "self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating", "{ 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account =", "instance of the CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response", "\"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format(", "twilio_assign_new_number_base_uri from config import auth_token from config import admin_sid class CreateTwilioAccount: def __init__(self,", "number to buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response =", "= user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign", "self: an instance of the CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format(", "system user account. Args: self: an instance of the CreateTwilioAccount class \"\"\" params", "an instance of the CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token)", "\"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response", "import twilio_assign_new_number_base_uri from config import auth_token from config import admin_sid class CreateTwilioAccount: def", "private method for assigning a sms-enabled number to a Twilio subaccount. Args: self:", "config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import auth_token from config", "asyncio import subprocess from quart import session from async_http import AsyncHTTP from config", "user account. Args: self: an instance of the CreateTwilioAccount class \"\"\" params =", "area code is set on the session. Args: self: an instance of the", "{'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response =", "self: an instance of the CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name,", "sms_number): \"\"\"A private method for assigning a sms-enabled number to a Twilio subaccount.", "sms-enabled number. Args: self: an instance of the CreateTwilioAccount class user_sid: string sms_number:", "purchasing a number from the list, and assigning it to the Twilio subaccount.", "CreateTwilioAccount class user_sid: string sms_number: string: the sms number to buy \"\"\" params", "method for assigning a sms-enabled number to a Twilio subaccount. Args: self: an", "the CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri", "AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating a system user account. Args:", "the session. Args: self: an instance of the CreateTwilioAccount class user_sid: string \"\"\"", "the CreateTwilioAccount class user_sid: string sms_number: string: the number that was just purchased.", "config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config", "was just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid }", "{ 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response", "request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await self.async_http.post( base_uri=request_uri, params=params) return response", "response = await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A", "Args: self: an instance of the CreateTwilioAccount class user_sid: string sms_number: string: the", "self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for", "a sms-enabled number to a Twilio subaccount. Args: self: an instance of the", "class user_sid: string sms_number: string: the number that was just purchased. \"\"\" params", "auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params)", "async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config", "in a given area code. Calls private helper methods to complete the process", "create_user_account(self): \"\"\"A method for creating a system user account. Args: self: an instance", "params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number):", "method for getting a list of available, sms-enabled phone numbers in a given", "helper methods to complete the process of purchasing a number from the list,", "CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def create_user_account(self):", "print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private", "subaccount. Args: self: an instance of the CreateTwilioAccount class user_sid: string sms_number: string:", "signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method for getting a list of", "phone numbers in a given area code. Calls private helper methods to complete", "import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import", "subprocess from quart import session from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri", "= { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number)", "given sms-enabled number. Args: self: an instance of the CreateTwilioAccount class user_sid: string", "async def create_user_account(self): \"\"\"A method for creating a system user account. Args: self:", "process of purchasing a number from the list, and assigning it to the", "purchasing a given sms-enabled number. Args: self: an instance of the CreateTwilioAccount class", "sms_number: string: the number that was just purchased. \"\"\" params = { 'phone_number':sms_number,", "the list, and assigning it to the Twilio subaccount. NOTE: the area code", "to a Twilio subaccount. Args: self: an instance of the CreateTwilioAccount class user_sid:", "from the list, and assigning it to the Twilio subaccount. NOTE: the area", "'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await self.async_http.post( base_uri=request_uri,", "Args: self: an instance of the CreateTwilioAccount class \"\"\" params = { 'friendly_name':", "sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing", "a system user account. Args: self: an instance of the CreateTwilioAccount class \"\"\"", "string sms_number: string: the sms number to buy \"\"\" params = {'phone_number':sms_number} request_uri", "await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method", "\"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri)", "friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method for", "import auth_token from config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name =", "user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up", "user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user = await", "code. Calls private helper methods to complete the process of purchasing a number", "of purchasing a number from the list, and assigning it to the Twilio", "for getting a list of available, sms-enabled phone numbers in a given area", "return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing a", "an instance of the CreateTwilioAccount class user_sid: string sms_number: string: the sms number", "the CreateTwilioAccount class user_sid: string sms_number: string: the sms number to buy \"\"\"", "error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method for getting", "it to the Twilio subaccount. NOTE: the area code is set on the", "as e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid):", "response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A", "= friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating a", "string sms_number: string: the number that was just purchased. \"\"\" params = {", "sms-enabled number to a Twilio subaccount. Args: self: an instance of the CreateTwilioAccount", "the process of purchasing a number from the list, and assigning it to", "assigning a sms-enabled number to a Twilio subaccount. Args: self: an instance of", "from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from", "on the session. Args: self: an instance of the CreateTwilioAccount class user_sid: string", "sms_number): \"\"\"A private method for purchasing a given sms-enabled number. Args: self: an", "for purchasing a given sms-enabled number. Args: self: an instance of the CreateTwilioAccount", "self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async", "available, sms-enabled phone numbers in a given area code. Calls private helper methods", "number that was just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid':", "= {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response", "response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number):", "code is set on the session. Args: self: an instance of the CreateTwilioAccount", "friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating a system", "import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import", "user_sid): \"\"\"A private method for getting a list of available, sms-enabled phone numbers", "_get_sms_user(self, user_sid): \"\"\"A private method for getting a list of available, sms-enabled phone", "'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await", "print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user =", "response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing a given", "\"\"\"A private method for assigning a sms-enabled number to a Twilio subaccount. Args:", "string: the number that was just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token':", "that was just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid", "from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import auth_token from", "def _get_sms_user(self, user_sid): \"\"\"A private method for getting a list of available, sms-enabled", "Twilio subaccount. NOTE: the area code is set on the session. Args: self:", "Args: self: an instance of the CreateTwilioAccount class user_sid: string \"\"\" request_uri =", "instance of the CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token", "await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except", "of the CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response =", "= twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid,", "= await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private", "sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning", "a list of available, sms-enabled phone numbers in a given area code. Calls", "the CreateTwilioAccount class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await", "__init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method", "await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response async", "Exception as e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self,", "number from the list, and assigning it to the Twilio subaccount. NOTE: the", "string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name", "from config import auth_token from config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name):", "config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config", "user_sid, sms_number): \"\"\"A private method for purchasing a given sms-enabled number. Args: self:", "method for purchasing a given sms-enabled number. Args: self: an instance of the", "to complete the process of purchasing a number from the list, and assigning", "response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning a sms-enabled", "base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception as", "of the CreateTwilioAccount class user_sid: string sms_number: string: the number that was just", "from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from", "self: an instance of the CreateTwilioAccount class user_sid: string sms_number: string: the number", "class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri", "self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid) except Exception", "the number that was just purchased. \"\"\" params = { 'phone_number':sms_number, 'auth_token': auth_token,", "self: an instance of the CreateTwilioAccount class user_sid: string sms_number: string: the sms", "of the CreateTwilioAccount class user_sid: string sms_number: string: the sms number to buy", "sms number to buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response", "session from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri", "subaccount. NOTE: the area code is set on the session. Args: self: an", "the sms number to buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token)", "Twilio subaccount. Args: self: an instance of the CreateTwilioAccount class user_sid: string sms_number:", "user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await self.async_http.post( base_uri=request_uri, params=params)", "user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number =", "await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async def", "self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response async def", "list, and assigning it to the Twilio subaccount. NOTE: the area code is", "a given sms-enabled number. Args: self: an instance of the CreateTwilioAccount class user_sid:", "def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A", "\"\"\"A method for creating a system user account. Args: self: an instance of", "number to a Twilio subaccount. Args: self: an instance of the CreateTwilioAccount class", "class user_sid: string sms_number: string: the sms number to buy \"\"\" params =", "await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method", "twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import auth_token", "admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async", "sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self,", "{}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method for getting a", "class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP() async def", "request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response =", "self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for", "= await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async", "number. Args: self: an instance of the CreateTwilioAccount class user_sid: string sms_number: string:", "_assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning a sms-enabled number to a", "Calls private helper methods to complete the process of purchasing a number from", "base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self, user_sid,", "an instance of the CreateTwilioAccount class user_sid: string sms_number: string: the number that", "async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private method for purchasing a given sms-enabled", "'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response = await", "except Exception as e: print('Twilio sign up error: {}'.format(str(e))) return signed_up_user async def", "sms-enabled phone numbers in a given area code. Calls private helper methods to", "= twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid", "import session from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config import", "area code. Calls private helper methods to complete the process of purchasing a", "a Twilio subaccount. Args: self: an instance of the CreateTwilioAccount class user_sid: string", "for creating a system user account. Args: self: an instance of the CreateTwilioAccount", "= await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up error: {}'.format(str(e))) return", "import twilio_create_subaccount_base_uri from config import twilio_assign_new_number_base_uri from config import auth_token from config import", "self.async_http = AsyncHTTP() async def create_user_account(self): \"\"\"A method for creating a system user", "of the CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token }", "request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response = await", "class user_sid: string \"\"\" request_uri = twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number", "list of available, sms-enabled phone numbers in a given area code. Calls private", "self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post(", "quart import session from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from config", "request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid =", "user_sid: string sms_number: string: the number that was just purchased. \"\"\" params =", "auth_token from config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name", "import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http = AsyncHTTP()", "user_sid, sms_number): \"\"\"A private method for assigning a sms-enabled number to a Twilio", "} request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid", "= response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid,", "= await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid, sms_number) return response", "sms_number: string: the sms number to buy \"\"\" params = {'phone_number':sms_number} request_uri =", "from config import twilio_available_sms_numbers_base_uri from config import twilio_purchase_sms_number_base_uri from config import twilio_create_subaccount_base_uri from", "= await self._purchase_sms_number(user_sid, sms_number) return response async def _purchase_sms_number(self, user_sid, sms_number): \"\"\"A private", "is set on the session. Args: self: an instance of the CreateTwilioAccount class", "= { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri = twilio_create_subaccount_base_uri print(request_uri) print(params) user_account", "try: signed_up_user = await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up error:", "up error: {}'.format(str(e))) return signed_up_user async def _get_sms_user(self, user_sid): \"\"\"A private method for", "the area code is set on the session. Args: self: an instance of", "\"\"\"A private method for purchasing a given sms-enabled number. Args: self: an instance", "response = await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response", "'phone_number':sms_number, 'auth_token': auth_token, 'AddressSid': user_sid } request_uri = twilio_assign_new_number_base_uri.format( admin_sid=admin_sid, sms_number=sms_number) response =", "async def _assign_sms_number_to_user(self, user_sid, sms_number): \"\"\"A private method for assigning a sms-enabled number", "account. Args: self: an instance of the CreateTwilioAccount class \"\"\" params = {", "session. Args: self: an instance of the CreateTwilioAccount class user_sid: string \"\"\" request_uri", "print(request_uri) print(params) user_account = await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user", "user_sid: string sms_number: string: the sms number to buy \"\"\" params = {'phone_number':sms_number}", "auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return", "from quart import session from async_http import AsyncHTTP from config import twilio_available_sms_numbers_base_uri from", "= await self.async_http.post( base_uri=request_uri, params=params) user_sid = user_account.sid try: signed_up_user = await self._get_sms_user(user_sid)", "from config import twilio_assign_new_number_base_uri from config import auth_token from config import admin_sid class", "twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await self._purchase_sms_number(user_sid,", "\"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await self.async_http.post( base_uri=request_uri,", "to buy \"\"\" params = {'phone_number':sms_number} request_uri = twilio_purchase_sms_number_base_uri.format( auth_token=auth_token) response = await", "CreateTwilioAccount class \"\"\" params = { 'friendly_name': self.friendly_name, 'auth_token': auth_token } request_uri =", "a number from the list, and assigning it to the Twilio subaccount. NOTE:", "method for creating a system user account. Args: self: an instance of the", "def create_user_account(self): \"\"\"A method for creating a system user account. Args: self: an", "self.async_http.post( base_uri=request_uri, params=params) response = await self._assign_sms_number_to_user(user_sid, sms_number) return response async def _assign_sms_number_to_user(self,", "signed_up_user = await self._get_sms_user(user_sid) except Exception as e: print('Twilio sign up error: {}'.format(str(e)))", "methods to complete the process of purchasing a number from the list, and", "CreateTwilioAccount class user_sid: string sms_number: string: the number that was just purchased. \"\"\"", "import asyncio import subprocess from quart import session from async_http import AsyncHTTP from", "set on the session. Args: self: an instance of the CreateTwilioAccount class user_sid:", "the Twilio subaccount. NOTE: the area code is set on the session. Args:", "given area code. Calls private helper methods to complete the process of purchasing", "to the Twilio subaccount. NOTE: the area code is set on the session.", "config import admin_sid class CreateTwilioAccount: def __init__(self, friendly_name): self.friendly_name = friendly_name self.async_http =", "= twilio_available_sms_numbers_base_uri.format( auth_token=auth_token) response = await self.async_http.get(base_uri=request_uri) sms_number = response.available_phone_numbers[0].friendly_name response = await", "instance of the CreateTwilioAccount class user_sid: string sms_number: string: the sms number to" ]
[ "== '__main__': # Binary Tree Representation # of input array # 1 #", "6, 13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17 / \\", "= {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Output:", "17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17", "15 6 Heapify 5: Swap 13 and 5. 1 / \\ 3 13", "i + 1 # left = 2*i + 1 r = 2 *", "largest = l # If right child is larger than largest so far", "4 6 13 10 # / \\ / \\ # 9 8 15", "N) time complexity where N is the total number of Nodes. Therefore, building", "idea is to find the position of the last non-leaf node and perform", "of heap def heapify(arr, n, i): largest = i # Initialize largest as", "1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8,", "/ \\ # 9 8 15 17 arr = [1, 3, 5, 4,", "heapify the affected sub-tree heapify(arr, n, largest) # Function to build a Max-Heap", "/ \\ / \\ 4 8 3 1''' # Python3 program for building", "17, again swap 3 and 15. 1 / \\ 17 13 / \\", "is:\") for i in range(n): print(arr[i], end=\" \") print() # Driver Code if", "at (i-1)/2 index. Simple Approach: Suppose, we need to build a Max-Heap from", "/ \\ 9 6 5 10 / \\ / \\ 4 8 3", "and 17. 1 / \\ 3 5 / \\ / \\ 4 17", "\\ 4 8 3 6 Heapify 1: First Swap 1 and 17, again", "/ \\ / \\ # 9 6 5 10 # / \\ /", "child is larger than largest so far if r < n and arr[r]", "function to print the array # representation of Heap def printHeap(arr, n): print(\"Array", "/ \\ 4 17 13 10 / \\ / \\ 9 8 15", "index. or, Last non-leaf node = Node at index ((n-1) - 1)/2. =", "\\ / \\ 4 8 3 6 Heapify 1: First Swap 1 and", "6: Swap 6 and 17. 1 / \\ 3 5 / \\ /", "Time Complexity: Heapify a single node takes O(log N) time complexity where N", "17 13 10 / \\ / \\ 9 8 15 6 Heapify 4:", "13 and 5. 1 / \\ 3 13 / \\ / \\ 9", "arr[i] # Recursively heapify the affected sub-tree heapify(arr, n, largest) # Function to", "binary tree for this array of elements [4, 10, 3, 5, 1] will", "and 6. 17 / \\ 15 13 / \\ / \\ 9 6", "we need to build a Max-Heap from the above-given array elements. It can", "Representation # of input array # 1 # / \\ # 3 5", "top-down approach. That is first heapify, the last node in level order traversal", "complete binary tree formed does not follow the Heap property. So, the idea", "heapify operations and the total time complexity will be O(N*logN). In reality, building", "5, 1] will be: 4 / \\ 10 3 / \\ 5 1", "follow the Heap property. So, the idea is to heapify the complete binary", "a subtree rooted with node i # which is an index in arr[].", "of i-th node is at (2*i + 1)th index. Right child of i-th", "Non-leaf node index = (11/2) - 1 = 4. Therefore, last non-leaf node", "a Max-Heap from the given array def buildHeap(arr, n): # Index of last", "9. 1 / \\ 3 5 / \\ / \\ 9 17 13", "Input: arr[] = {4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10 /", "1 = 4. Therefore, last non-leaf node = 6. To build the heap,", "nodes need not to be heapified as they already follow the heap property.", "from the given array def buildHeap(arr, n): # Index of last non-leaf node", "array of elements [4, 10, 3, 5, 1] will be: 4 / \\", "is to build a Binary Heap from the given array. The heap can", "13 / \\ / \\ 9 6 5 10 / \\ / \\", "\\ 9 17 5 10 / \\ / \\ 4 8 15 6", "sub-tree heapify(arr, n, largest) # Function to build a Max-Heap from the given", "follow the heap property. Also, the array representation of the complete binary tree", "Perform reverse level order traversal # from last non-leaf node and heapify #", "at (n-1)th index. or, Last non-leaf node = Node at index ((n-1) -", "15, 17} Corresponding Complete Binary Tree is: 1 / \\ 3 5 /", "9 6 5 10 # / \\ / \\ # 4 8 3", "already follow the heap property. Also, the array representation of the complete binary", "representation of the complete binary tree contains the level order traversal of the", "= l # If right child is larger than largest so far if", "l < n and arr[l] > arr[largest]: largest = l # If right", "= arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr, n, largest) #", "can be either Max Heap or Min Heap. Example: Input: arr[] = {4,", "8 15 6 Heapify 3: First Swap 3 and 17, again swap 3", "Therefore, last non-leaf node = 6. To build the heap, heapify only the", "left = 2*i + 1 r = 2 * i + 2 #", "2 # right = 2*i + 2 # If left child is larger", "\\ 10 3 / \\ 5 1 Note: Root is at index 0", "Complete Binary Tree is: 1 / \\ 3 5 / \\ / \\", "1] will be: 4 / \\ 10 3 / \\ 5 1 Note:", "9 8 15 6 Heapify 4: Swap 4 and 9. 1 / \\", "In reality, building a heap takes O(n) time depending on the implementation which", "[1, 3, 5, 4, 6] in reverse order. Heapify 6: Swap 6 and", "# If right child is larger than largest so far if r <", "last non-leaf node = 6. To build the heap, heapify only the nodes:", "again swap 1 and 15, finally swap 1 and 6. 17 / \\", "is to heapify the complete binary tree formed from the array in reverse", "be optimized by observing the fact that the leaf nodes need not to", "operations and the total time complexity will be O(N*logN). In reality, building a", "2*i + 2 # If left child is larger than root if l", "/ \\ 4 8 15 6 Heapify 3: First Swap 3 and 17,", "4 8 15 6 Heapify 3: First Swap 3 and 17, again swap", "the level order traversal of the tree. So the idea is to find", "{4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10 / \\ 5 3", "n, largest) # Function to build a Max-Heap from the given array def", "here. Optimized Approach: The above approach can be optimized by observing the fact", "Output: Corresponding Max-Heap: 17 / \\ 15 13 / \\ / \\ 9", "9, 8, 15, 17} Output: Corresponding Max-Heap: 17 / \\ 15 13 /", "/ \\ / \\ 9 17 13 10 / \\ / \\ 4", "array # 1 # / \\ # 3 5 # / \\ /", "5: Swap 13 and 5. 1 / \\ 3 13 / \\ /", "Also, the array representation of the complete binary tree contains the level order", "1 and 15, finally swap 1 and 6. 17 / \\ 15 13", "than largest so far if r < n and arr[r] > arr[largest]: largest", "4 / \\ 10 3 / \\ 5 1 Note: Root is at", "larger than largest so far if r < n and arr[r] > arr[largest]:", "4 8 15 6 Heapify 5: Swap 13 and 5. 1 / \\", "far if r < n and arr[r] > arr[largest]: largest = r #", "Heap. Example: Input: arr[] = {4, 10, 3, 5, 1} Output: Corresponding Max-Heap:", "heapify the second last node and so on. Time Complexity: Heapify a single", "at index ((n-1) - 1)/2. = (n/2) - 1. Illustration: Array = {1,", "# each node for i in range(startIdx, -1, -1): heapify(arr, n, i) #", "# / \\ / \\ # 9 6 5 10 # / \\", "the tree, then heapify the second last node and so on. Time Complexity:", "\\ / \\ 4 6 13 10 / \\ / \\ 9 8", "\\ 5 3 / \\ 4 1 Input: arr[] = {1, 3, 5,", "heapify # each node for i in range(startIdx, -1, -1): heapify(arr, n, i)", "/ \\ 4 6 13 10 / \\ / \\ 9 8 15", "# To heapify a subtree rooted with node i # which is an", "15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: #", "Suppose the given input elements are: 4, 10, 3, 5, 1. The corresponding", "is first heapify, the last node in level order traversal of the tree,", "of last-node. or, Last non-leaf node = parent of node at (n-1)th index.", "2 - 1 # Perform reverse level order traversal # from last non-leaf", "heap can be either Max Heap or Min Heap. Example: Input: arr[] =", "on. Time Complexity: Heapify a single node takes O(log N) time complexity where", "17 13 10 / \\ / \\ 4 8 15 6 Heapify 5:", "is an index in arr[]. N is size of heap def heapify(arr, n,", "= 2 * i + 2 # right = 2*i + 2 #", "array def buildHeap(arr, n): # Index of last non-leaf node startIdx = n", "non-leaf node startIdx = n // 2 - 1 # Perform reverse level", "rooted with node i # which is an index in arr[]. N is", "heap, heapify only the nodes: [1, 3, 5, 4, 6] in reverse order.", "order traversal # from last non-leaf node and heapify # each node for", "of each non-leaf node in reverse level order. Last non-leaf node = parent", "10 # / \\ / \\ # 9 8 15 17 arr =", "the given array def buildHeap(arr, n): # Index of last non-leaf node startIdx", "\\ / \\ 4 8 15 6 Heapify 5: Swap 13 and 5.", "given array. The heap can be either Max Heap or Min Heap. Example:", "that the above complete binary tree formed does not follow the Heap property.", "\\ 3 5 / \\ / \\ 4 6 13 10 / \\", "1 # left = 2*i + 1 r = 2 * i +", "can be seen here. Optimized Approach: The above approach can be optimized by", "is larger than root if l < n and arr[l] > arr[largest]: largest", "1 / \\ 3 5 / \\ / \\ 4 6 13 10", "(11/2) - 1 = 4. Therefore, last non-leaf node = 6. To build", "Binary Tree Representation # of input array # 1 # / \\ #", "node = parent of last-node. or, Last non-leaf node = parent of node", "level order. Last non-leaf node = parent of last-node. or, Last non-leaf node", "6 and 17. 1 / \\ 3 5 / \\ / \\ 4", "Approach: The above approach can be optimized by observing the fact that the", "/ \\ / \\ 9 8 15 6 Heapify 4: Swap 4 and", "5. 1 / \\ 3 13 / \\ / \\ 9 17 5", "the complete binary tree formed from the array in reverse level order following", "array. The heap can be either Max Heap or Min Heap. Example: Input:", "Max-Heap from the given array def buildHeap(arr, n): # Index of last non-leaf", "arr[] = {4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10 / \\", "/ \\ / \\ # 4 6 13 10 # / \\ /", "// 2 - 1 # Perform reverse level order traversal # from last", "3, 5, 1] will be: 4 / \\ 10 3 / \\ 5", "/ \\ / \\ 4 8 15 6 Heapify 5: Swap 13 and", "formed from the array in reverse level order following a top-down approach. That", "program for building Heap from Array # To heapify a subtree rooted with", "Corresponding Max-Heap: 10 / \\ 5 3 / \\ 4 1 Input: arr[]", "an index in arr[]. N is size of heap def heapify(arr, n, i):", "node is at (2*i + 1)th index. Right child of i-th node is", "\\ / \\ 9 15 5 10 / \\ / \\ 4 8", "Heap property. So, the idea is to heapify the complete binary tree formed", "heapify the complete binary tree formed from the array in reverse level order", "- 1. Illustration: Array = {1, 3, 5, 4, 6, 13, 10, 9,", "5 10 / \\ / \\ 4 8 3 6 Heapify 1: First", "and 17, again swap 1 and 15, finally swap 1 and 6. 17", "elements are: 4, 10, 3, 5, 1. The corresponding complete binary tree for", "5 10 / \\ / \\ 4 8 3 1''' # Python3 program", "# Index of last non-leaf node startIdx = n // 2 - 1", "and heapify # each node for i in range(startIdx, -1, -1): heapify(arr, n,", "complexity where N is the total number of Nodes. Therefore, building the entire", "5, 1} Output: Corresponding Max-Heap: 10 / \\ 5 3 / \\ 4", "if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the", "first heapify, the last node in level order traversal of the tree, then", "print() # Driver Code if __name__ == '__main__': # Binary Tree Representation #", "Given an array of N elements. The task is to build a Binary", "take N heapify operations and the total time complexity will be O(N*logN). In", "6 13 10 / \\ / \\ 9 8 15 17 The task", "Heapify 3: First Swap 3 and 17, again swap 3 and 15. 1", "node for i in range(startIdx, -1, -1): heapify(arr, n, i) # A utility", "finally swap 1 and 6. 17 / \\ 15 13 / \\ /", "for i in range(startIdx, -1, -1): heapify(arr, n, i) # A utility function", "l = 2 * i + 1 # left = 2*i + 1", "1 and 6. 17 / \\ 15 13 / \\ / \\ 9", "The above approach can be optimized by observing the fact that the leaf", "/ \\ 3 5 / \\ / \\ 9 17 13 10 /", "Swap 13 and 5. 1 / \\ 3 13 / \\ / \\", "the affected sub-tree heapify(arr, n, largest) # Function to build a Max-Heap from", "nodes: [1, 3, 5, 4, 6] in reverse order. Heapify 6: Swap 6", "/ \\ 9 8 15 6 Heapify 4: Swap 4 and 9. 1", "and 17, again swap 3 and 15. 1 / \\ 17 13 /", "arr[]. N is size of heap def heapify(arr, n, i): largest = i", "/ \\ 9 15 5 10 / \\ / \\ 4 8 3", "\\ # 4 6 13 10 # / \\ / \\ # 9", "8 15 6 Heapify 4: Swap 4 and 9. 1 / \\ 3", "order traversal of the tree, then heapify the second last node and so", "given input elements are: 4, 10, 3, 5, 1. The corresponding complete binary", "clearly seen that the above complete binary tree formed does not follow the", "that the leaf nodes need not to be heapified as they already follow", "= (11/2) - 1 = 4. Therefore, last non-leaf node = 6. To", "# If largest is not root if largest != i: arr[i], arr[largest] =", "Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15,", "\\ 9 8 15 6 Heapify 4: Swap 4 and 9. 1 /", "/ \\ 10 3 / \\ 5 1 Note: Root is at index", "1. Illustration: Array = {1, 3, 5, 4, 6, 13, 10, 9, 8,", "node at (n-1)th index. or, Last non-leaf node = Node at index ((n-1)", "buildHeap(arr, n): # Index of last non-leaf node startIdx = n // 2", "to build a Max-Heap from the given array def buildHeap(arr, n): # Index", "be: 4 / \\ 10 3 / \\ 5 1 Note: Root is", "index. Simple Approach: Suppose, we need to build a Max-Heap from the above-given", "# 4 6 13 10 # / \\ / \\ # 9 8", "Corresponding Complete Binary Tree is: 1 / \\ 3 5 / \\ /", "printHeap(arr, n): print(\"Array representation of Heap is:\") for i in range(n): print(arr[i], end=\"", "non-leaf node = 6. To build the heap, heapify only the nodes: [1,", "13, 10, 9, 8, 15, 17} Corresponding Complete Binary Tree is: 1 /", "/ \\ / \\ 4 6 13 10 / \\ / \\ 9", "node and so on. Time Complexity: Heapify a single node takes O(log N)", "not to be heapified as they already follow the heap property. Also, the", "\\ / \\ # 4 6 13 10 # / \\ / \\", "13 # / \\ / \\ # 9 6 5 10 # /", "r < n and arr[r] > arr[largest]: largest = r # If largest", "= (n/2) - 1. Illustration: Array = {1, 3, 5, 4, 6, 13,", "So the idea is to find the position of the last non-leaf node", "= 2*i + 1 r = 2 * i + 2 # right", "\\ 9 6 5 10 / \\ / \\ 4 8 3 1", "of i-th node is at (2*i + 2)th index. Parent of i-th node", "= n // 2 - 1 # Perform reverse level order traversal #", "17 5 10 / \\ / \\ 4 8 15 6 Heapify 3:", "of the last non-leaf node and perform the heapify operation of each non-leaf", "10, 3, 5, 1. The corresponding complete binary tree for this array of", "seen here. Optimized Approach: The above approach can be optimized by observing the", "and 15. 1 / \\ 17 13 / \\ / \\ 9 15", "def buildHeap(arr, n): # Index of last non-leaf node startIdx = n //", "10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17 / \\ 15 13", "Note: Root is at index 0 in array. Left child of i-th node", "and so on. Time Complexity: Heapify a single node takes O(log N) time", "It can be clearly seen that the above complete binary tree formed does", "Array = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}", "above array. Total Nodes = 11. Last Non-leaf node index = (11/2) -", "as root l = 2 * i + 1 # left = 2*i", "= 2 * i + 1 # left = 2*i + 1 r", "# Recursively heapify the affected sub-tree heapify(arr, n, largest) # Function to build", "Swap 1 and 17, again swap 1 and 15, finally swap 1 and", "elements. The task is to build a Binary Heap from the given array.", "Complexity: Heapify a single node takes O(log N) time complexity where N is", "6 Heapify 5: Swap 13 and 5. 1 / \\ 3 13 /", "index in arr[]. N is size of heap def heapify(arr, n, i): largest", "3 / \\ 5 1 Note: Root is at index 0 in array.", "= {4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10 / \\ 5", "8 15 17 arr = [1, 3, 5, 4, 6, 13, 10, 9,", "\\ 3 5 / \\ / \\ 9 17 13 10 / \\", "heapify(arr, n, i) # A utility function to print the array # representation", "the second last node and so on. Time Complexity: Heapify a single node", "or Min Heap. Example: Input: arr[] = {4, 10, 3, 5, 1} Output:", "/ \\ 9 8 15 17 The task to build a Max-Heap from", "\") print() # Driver Code if __name__ == '__main__': # Binary Tree Representation", "representation of Heap is:\") for i in range(n): print(arr[i], end=\" \") print() #", "1 # / \\ # 3 5 # / \\ / \\ #", "traversal of the tree. So the idea is to find the position of", "at index 0 in array. Left child of i-th node is at (2*i", "from the array in reverse level order following a top-down approach. That is", "parent of node at (n-1)th index. or, Last non-leaf node = Node at", "If largest is not root if largest != i: arr[i], arr[largest] = arr[largest],", "is not root if largest != i: arr[i], arr[largest] = arr[largest], arr[i] #", "the array # representation of Heap def printHeap(arr, n): print(\"Array representation of Heap", "\\ / \\ # 9 6 5 10 # / \\ / \\", "\\ 4 1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10,", "in arr[]. N is size of heap def heapify(arr, n, i): largest =", "heapify(arr, n, i): largest = i # Initialize largest as root l =", "utility function to print the array # representation of Heap def printHeap(arr, n):", "arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr, n, largest) # Function", "order. Last non-leaf node = parent of last-node. or, Last non-leaf node =", "15, 17} Output: Corresponding Max-Heap: 17 / \\ 15 13 / \\ /", "i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr,", "in array. Left child of i-th node is at (2*i + 1)th index.", "need to build a Max-Heap from the above-given array elements. It can be", "Binary Tree is: 1 / \\ 3 5 / \\ / \\ 4", "10 / \\ / \\ 4 8 3 6 Heapify 1: First Swap", "takes O(n) time depending on the implementation which can be seen here. Optimized", "property. So, the idea is to heapify the complete binary tree formed from", "17} Corresponding Complete Binary Tree is: 1 / \\ 3 5 / \\", "be heapified as they already follow the heap property. Also, the array representation", "1 / \\ 3 5 / \\ / \\ 9 17 13 10", "node and perform the heapify operation of each non-leaf node in reverse level", "in range(n): print(arr[i], end=\" \") print() # Driver Code if __name__ == '__main__':", "/ \\ 3 5 / \\ / \\ 4 17 13 10 /", "6 13 10 # / \\ / \\ # 9 8 15 17", "Last Non-leaf node index = (11/2) - 1 = 4. Therefore, last non-leaf", "4 and 9. 1 / \\ 3 5 / \\ / \\ 9", "Heapify 1: First Swap 1 and 17, again swap 1 and 15, finally", "and 9. 1 / \\ 3 5 / \\ / \\ 9 17", "Heapify a single node takes O(log N) time complexity where N is the", "need not to be heapified as they already follow the heap property. Also,", "/ \\ / \\ 9 17 5 10 / \\ / \\ 4", "/ \\ 15 13 / \\ / \\ 9 6 5 10 /", "4 1 Input: arr[] = {1, 3, 5, 4, 6, 13, 10, 9,", "from the above-given array elements. It can be clearly seen that the above", "> arr[largest]: largest = r # If largest is not root if largest", "heapify(arr, n, largest) # Function to build a Max-Heap from the given array", "heapify, the last node in level order traversal of the tree, then heapify", "/ \\ 4 8 3 1 Suppose the given input elements are: 4,", "i # which is an index in arr[]. N is size of heap", "\\ / \\ 9 6 5 10 / \\ / \\ 4 8", "Left child of i-th node is at (2*i + 1)th index. Right child", "elements. It can be clearly seen that the above complete binary tree formed", "= parent of node at (n-1)th index. or, Last non-leaf node = Node", "Last non-leaf node = parent of node at (n-1)th index. or, Last non-leaf", "\\ / \\ 4 8 15 6 Heapify 3: First Swap 3 and", "= r # If largest is not root if largest != i: arr[i],", "15 6 Heapify 3: First Swap 3 and 17, again swap 3 and", "Last non-leaf node = parent of last-node. or, Last non-leaf node = parent", "\\ 9 8 15 17 The task to build a Max-Heap from above", "Max-Heap from above array. Total Nodes = 11. Last Non-leaf node index =", "3 5 / \\ / \\ 9 17 13 10 / \\ /", "(2*i + 1)th index. Right child of i-th node is at (2*i +", "# Perform reverse level order traversal # from last non-leaf node and heapify", "3, 5, 4, 6, 13, 10, 9, 8, 15, 17] n = len(arr)", "'''https://www.geeksforgeeks.org/building-heap-from-array/ Given an array of N elements. The task is to build a", "non-leaf node = parent of node at (n-1)th index. or, Last non-leaf node", "depending on the implementation which can be seen here. Optimized Approach: The above", "5 # / \\ / \\ # 4 6 13 10 # /", "+ 2 # If left child is larger than root if l <", "complete binary tree formed from the array in reverse level order following a", "time complexity will be O(N*logN). In reality, building a heap takes O(n) time", "/ \\ 9 17 13 10 / \\ / \\ 4 8 15", "3 / \\ 4 1 Input: arr[] = {1, 3, 5, 4, 6,", "!= i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the affected sub-tree", "< n and arr[r] > arr[largest]: largest = r # If largest is", "if l < n and arr[l] > arr[largest]: largest = l # If", "heapified as they already follow the heap property. Also, the array representation of", "6 Heapify 1: First Swap 1 and 17, again swap 1 and 15,", "node i # which is an index in arr[]. N is size of", "n): print(\"Array representation of Heap is:\") for i in range(n): print(arr[i], end=\" \")", "(2*i + 2)th index. Parent of i-th node is at (i-1)/2 index. Simple", "13 / \\ / \\ 9 15 5 10 / \\ / \\", "\\ 9 15 5 10 / \\ / \\ 4 8 3 6", "Last non-leaf node = Node at index ((n-1) - 1)/2. = (n/2) -", "node takes O(log N) time complexity where N is the total number of", "/ \\ / \\ 9 8 15 17 The task to build a", "n, i): largest = i # Initialize largest as root l = 2", "If right child is larger than largest so far if r < n", "build a Max-Heap from above array. Total Nodes = 11. Last Non-leaf node", "the implementation which can be seen here. Optimized Approach: The above approach can", "4 8 3 6 Heapify 1: First Swap 1 and 17, again swap", "17 # / \\ # 15 13 # / \\ / \\ #", "property. Also, the array representation of the complete binary tree contains the level", "node startIdx = n // 2 - 1 # Perform reverse level order", "traversal # from last non-leaf node and heapify # each node for i", "\\ 9 17 13 10 / \\ / \\ 4 8 15 6", "First Swap 1 and 17, again swap 1 and 15, finally swap 1", "1} Output: Corresponding Max-Heap: 10 / \\ 5 3 / \\ 4 1", "with node i # which is an index in arr[]. N is size", "n // 2 - 1 # Perform reverse level order traversal # from", "3 and 17, again swap 3 and 15. 1 / \\ 17 13", "10 / \\ 5 3 / \\ 4 1 Input: arr[] = {1,", "3, 5, 1} Output: Corresponding Max-Heap: 10 / \\ 5 3 / \\", "# / \\ # 15 13 # / \\ / \\ # 9", "heap takes O(n) time depending on the implementation which can be seen here.", "4 17 13 10 / \\ / \\ 9 8 15 6 Heapify", "i + 2 # right = 2*i + 2 # If left child", "is the total number of Nodes. Therefore, building the entire Heap will take", "for building Heap from Array # To heapify a subtree rooted with node", "= {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Corresponding", "N heapify operations and the total time complexity will be O(N*logN). In reality,", "contains the level order traversal of the tree. So the idea is to", "To build the heap, heapify only the nodes: [1, 3, 5, 4, 6]", "\\ 17 13 / \\ / \\ 9 15 5 10 / \\", "the position of the last non-leaf node and perform the heapify operation of", "2 * i + 2 # right = 2*i + 2 # If", "index 0 in array. Left child of i-th node is at (2*i +", "the array representation of the complete binary tree contains the level order traversal", "to build a Binary Heap from the given array. The heap can be", "The corresponding complete binary tree for this array of elements [4, 10, 3,", "3 6 Heapify 1: First Swap 1 and 17, again swap 1 and", "largest = i # Initialize largest as root l = 2 * i", "end=\" \") print() # Driver Code if __name__ == '__main__': # Binary Tree", "heapify only the nodes: [1, 3, 5, 4, 6] in reverse order. Heapify", "traversal of the tree, then heapify the second last node and so on.", "/ \\ 5 1 Note: Root is at index 0 in array. Left", "the fact that the leaf nodes need not to be heapified as they", "# Function to build a Max-Heap from the given array def buildHeap(arr, n):", "build a Max-Heap from the given array def buildHeap(arr, n): # Index of", "Max-Heap: 17 / \\ 15 13 / \\ / \\ 9 6 5", "6, 13, 10, 9, 8, 15, 17} Corresponding Complete Binary Tree is: 1", "heapify a subtree rooted with node i # which is an index in", "is: 1 / \\ 3 5 / \\ / \\ 4 6 13", "# which is an index in arr[]. N is size of heap def", "Heapify 6: Swap 6 and 17. 1 / \\ 3 5 / \\", "building a heap takes O(n) time depending on the implementation which can be", "Heap is:\") for i in range(n): print(arr[i], end=\" \") print() # Driver Code", "{1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Output: Corresponding", "as they already follow the heap property. Also, the array representation of the", "reverse level order. Last non-leaf node = parent of last-node. or, Last non-leaf", "Array # To heapify a subtree rooted with node i # which is", "/ \\ / \\ # 9 8 15 17 arr = [1, 3,", "only the nodes: [1, 3, 5, 4, 6] in reverse order. Heapify 6:", "17, again swap 1 and 15, finally swap 1 and 6. 17 /", "of the tree. So the idea is to find the position of the", "9 8 15 17 arr = [1, 3, 5, 4, 6, 13, 10,", "1 / \\ 3 5 / \\ / \\ 4 17 13 10", "or, Last non-leaf node = Node at index ((n-1) - 1)/2. = (n/2)", "single node takes O(log N) time complexity where N is the total number", "/ \\ 3 13 / \\ / \\ 9 17 5 10 /", "{1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Corresponding Complete", "10, 9, 8, 15, 17} Corresponding Complete Binary Tree is: 1 / \\", "1 / \\ 17 13 / \\ / \\ 9 15 5 10", "Function to build a Max-Heap from the given array def buildHeap(arr, n): #", "\\ 3 5 / \\ / \\ 4 17 13 10 / \\", "15 13 # / \\ / \\ # 9 6 5 10 #", "5 / \\ / \\ 4 6 13 10 / \\ / \\", "build a Max-Heap from the above-given array elements. It can be clearly seen", "tree, then heapify the second last node and so on. Time Complexity: Heapify", "13 10 / \\ / \\ 4 8 15 6 Heapify 5: Swap", "the total time complexity will be O(N*logN). In reality, building a heap takes", "index ((n-1) - 1)/2. = (n/2) - 1. Illustration: Array = {1, 3,", "array # representation of Heap def printHeap(arr, n): print(\"Array representation of Heap is:\")", "15 17 arr = [1, 3, 5, 4, 6, 13, 10, 9, 8,", "10 / \\ / \\ 4 8 15 6 Heapify 3: First Swap", "either Max Heap or Min Heap. Example: Input: arr[] = {4, 10, 3,", "array of N elements. The task is to build a Binary Heap from", "Max-Heap from the above-given array elements. It can be clearly seen that the", "affected sub-tree heapify(arr, n, largest) # Function to build a Max-Heap from the", "reality, building a heap takes O(n) time depending on the implementation which can", "Index of last non-leaf node startIdx = n // 2 - 1 #", "print(arr[i], end=\" \") print() # Driver Code if __name__ == '__main__': # Binary", "\\ 4 8 15 6 Heapify 5: Swap 13 and 5. 1 /", "2 # If left child is larger than root if l < n", "heapify operation of each non-leaf node in reverse level order. Last non-leaf node", "and the total time complexity will be O(N*logN). In reality, building a heap", "1 r = 2 * i + 2 # right = 2*i +", "building the entire Heap will take N heapify operations and the total time", "reverse order. Heapify 6: Swap 6 and 17. 1 / \\ 3 5", "Heap from Array # To heapify a subtree rooted with node i #", "A utility function to print the array # representation of Heap def printHeap(arr,", "/ \\ / \\ 9 15 5 10 / \\ / \\ 4", "last non-leaf node startIdx = n // 2 - 1 # Perform reverse", "Heap: # 17 # / \\ # 15 13 # / \\ /", "Simple Approach: Suppose, we need to build a Max-Heap from the above-given array", "so far if r < n and arr[r] > arr[largest]: largest = r", "largest is not root if largest != i: arr[i], arr[largest] = arr[largest], arr[i]", "can be clearly seen that the above complete binary tree formed does not", "to be heapified as they already follow the heap property. Also, the array", "4 8 3 1''' # Python3 program for building Heap from Array #", "formed does not follow the Heap property. So, the idea is to heapify", "- 1)/2. = (n/2) - 1. Illustration: Array = {1, 3, 5, 4,", "5, 4, 6, 13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17", "5, 1. The corresponding complete binary tree for this array of elements [4,", "be seen here. Optimized Approach: The above approach can be optimized by observing", "Final Heap: # 17 # / \\ # 15 13 # / \\", "if __name__ == '__main__': # Binary Tree Representation # of input array #", "the heap property. Also, the array representation of the complete binary tree contains", "an array of N elements. The task is to build a Binary Heap", "+ 2)th index. Parent of i-th node is at (i-1)/2 index. Simple Approach:", "/ \\ / \\ 4 8 3 6 Heapify 1: First Swap 1", "# Binary Tree Representation # of input array # 1 # / \\", "does not follow the Heap property. So, the idea is to heapify the", "/ \\ 4 8 3 6 Heapify 1: First Swap 1 and 17,", "8, 15, 17} Corresponding Complete Binary Tree is: 1 / \\ 3 5", "last node in level order traversal of the tree, then heapify the second", "last non-leaf node and perform the heapify operation of each non-leaf node in", "1 Note: Root is at index 0 in array. Left child of i-th", "number of Nodes. Therefore, building the entire Heap will take N heapify operations", "Therefore, building the entire Heap will take N heapify operations and the total", "fact that the leaf nodes need not to be heapified as they already", "given array def buildHeap(arr, n): # Index of last non-leaf node startIdx =", "3 13 / \\ / \\ 9 17 5 10 / \\ /", "array representation of the complete binary tree contains the level order traversal of", "8 3 6 Heapify 1: First Swap 1 and 17, again swap 1", "representation of Heap def printHeap(arr, n): print(\"Array representation of Heap is:\") for i", "\\ 4 8 15 6 Heapify 3: First Swap 3 and 17, again", "Suppose, we need to build a Max-Heap from the above-given array elements. It", "Driver Code if __name__ == '__main__': # Binary Tree Representation # of input", "To heapify a subtree rooted with node i # which is an index", "order following a top-down approach. That is first heapify, the last node in", "i-th node is at (2*i + 1)th index. Right child of i-th node", "non-leaf node = Node at index ((n-1) - 1)/2. = (n/2) - 1.", "a Max-Heap from the above-given array elements. It can be clearly seen that", "'__main__': # Binary Tree Representation # of input array # 1 # /", "((n-1) - 1)/2. = (n/2) - 1. Illustration: Array = {1, 3, 5,", "17. 1 / \\ 3 5 / \\ / \\ 4 17 13", "6 Heapify 3: First Swap 3 and 17, again swap 3 and 15.", "8 3 1''' # Python3 program for building Heap from Array # To", "# of input array # 1 # / \\ # 3 5 #", "and 5. 1 / \\ 3 13 / \\ / \\ 9 17", "\\ / \\ 9 8 15 6 Heapify 4: Swap 4 and 9.", "\\ / \\ 9 17 13 10 / \\ / \\ 4 8", "= 11. Last Non-leaf node index = (11/2) - 1 = 4. Therefore,", "Optimized Approach: The above approach can be optimized by observing the fact that", "# If left child is larger than root if l < n and", "# 9 8 15 17 arr = [1, 3, 5, 4, 6, 13,", "operation of each non-leaf node in reverse level order. Last non-leaf node =", "from the given array. The heap can be either Max Heap or Min", "above approach can be optimized by observing the fact that the leaf nodes", "4, 6, 13, 10, 9, 8, 15, 17} Corresponding Complete Binary Tree is:", "1. The corresponding complete binary tree for this array of elements [4, 10,", "Swap 4 and 9. 1 / \\ 3 5 / \\ / \\", "tree for this array of elements [4, 10, 3, 5, 1] will be:", "of the tree, then heapify the second last node and so on. Time", "- 1 = 4. Therefore, last non-leaf node = 6. To build the", "Heapify 4: Swap 4 and 9. 1 / \\ 3 5 / \\", "right child is larger than largest so far if r < n and", "# Final Heap: # 17 # / \\ # 15 13 # /", "15. 1 / \\ 17 13 / \\ / \\ 9 15 5", "this array of elements [4, 10, 3, 5, 1] will be: 4 /", "10 / \\ / \\ 9 8 15 6 Heapify 4: Swap 4", "implementation which can be seen here. Optimized Approach: The above approach can be", "def heapify(arr, n, i): largest = i # Initialize largest as root l", "# Initialize largest as root l = 2 * i + 1 #", "1)th index. Right child of i-th node is at (2*i + 2)th index.", "be O(N*logN). In reality, building a heap takes O(n) time depending on the", "approach. That is first heapify, the last node in level order traversal of", "+ 1 r = 2 * i + 2 # right = 2*i", "takes O(log N) time complexity where N is the total number of Nodes.", "the total number of Nodes. Therefore, building the entire Heap will take N", "3 and 15. 1 / \\ 17 13 / \\ / \\ 9", "the tree. So the idea is to find the position of the last", "complete binary tree for this array of elements [4, 10, 3, 5, 1]", "array elements. It can be clearly seen that the above complete binary tree", "and perform the heapify operation of each non-leaf node in reverse level order.", "node and heapify # each node for i in range(startIdx, -1, -1): heapify(arr,", "/ \\ # 9 6 5 10 # / \\ / \\ #", "n and arr[r] > arr[largest]: largest = r # If largest is not", "index. Right child of i-th node is at (2*i + 2)th index. Parent", "The task is to build a Binary Heap from the given array. The", "1: First Swap 1 and 17, again swap 1 and 15, finally swap", "# right = 2*i + 2 # If left child is larger than", "and arr[r] > arr[largest]: largest = r # If largest is not root", "Root is at index 0 in array. Left child of i-th node is", "+ 1 # left = 2*i + 1 r = 2 * i", "# / \\ # 3 5 # / \\ / \\ # 4", "2)th index. Parent of i-th node is at (i-1)/2 index. Simple Approach: Suppose,", "\\ / \\ 4 8 3 1 Suppose the given input elements are:", "from last non-leaf node and heapify # each node for i in range(startIdx,", "the array in reverse level order following a top-down approach. That is first", "5 / \\ / \\ 9 17 13 10 / \\ / \\", "i-th node is at (i-1)/2 index. Simple Approach: Suppose, we need to build", "binary tree contains the level order traversal of the tree. So the idea", "largest so far if r < n and arr[r] > arr[largest]: largest =", "build the heap, heapify only the nodes: [1, 3, 5, 4, 6] in", "binary tree formed from the array in reverse level order following a top-down", "13, 10, 9, 8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n)", "find the position of the last non-leaf node and perform the heapify operation", "1 and 17, again swap 1 and 15, finally swap 1 and 6.", "9 17 5 10 / \\ / \\ 4 8 15 6 Heapify", "range(startIdx, -1, -1): heapify(arr, n, i) # A utility function to print the", "10, 9, 8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) #", "6] in reverse order. Heapify 6: Swap 6 and 17. 1 / \\", "= i # Initialize largest as root l = 2 * i +", "10 / \\ / \\ 4 8 3 1 Suppose the given input", "input elements are: 4, 10, 3, 5, 1. The corresponding complete binary tree", "Max Heap or Min Heap. Example: Input: arr[] = {4, 10, 3, 5,", "/ \\ # 15 13 # / \\ / \\ # 9 6", "of the complete binary tree contains the level order traversal of the tree.", "arr[largest]: largest = r # If largest is not root if largest !=", "right = 2*i + 2 # If left child is larger than root", "the Heap property. So, the idea is to heapify the complete binary tree", "\\ # 9 8 15 17 arr = [1, 3, 5, 4, 6,", "index = (11/2) - 1 = 4. Therefore, last non-leaf node = 6.", "10 / \\ / \\ 4 8 15 6 Heapify 5: Swap 13", "3: First Swap 3 and 17, again swap 3 and 15. 1 /", "# / \\ / \\ # 9 8 15 17 arr = [1,", "array in reverse level order following a top-down approach. That is first heapify,", "\\ # 15 13 # / \\ / \\ # 9 6 5", "/ \\ 17 13 / \\ / \\ 9 15 5 10 /", "10, 3, 5, 1] will be: 4 / \\ 10 3 / \\", "17} Output: Corresponding Max-Heap: 17 / \\ 15 13 / \\ / \\", "or, Last non-leaf node = parent of node at (n-1)th index. or, Last", "10 / \\ / \\ 4 8 3 1''' # Python3 program for", "15 5 10 / \\ / \\ 4 8 3 6 Heapify 1:", "at (2*i + 2)th index. Parent of i-th node is at (i-1)/2 index.", "3, 5, 4, 6] in reverse order. Heapify 6: Swap 6 and 17.", "reverse level order traversal # from last non-leaf node and heapify # each", "1 Suppose the given input elements are: 4, 10, 3, 5, 1. The", "corresponding complete binary tree for this array of elements [4, 10, 3, 5,", "n, i) # A utility function to print the array # representation of", "(n-1)th index. or, Last non-leaf node = Node at index ((n-1) - 1)/2.", "tree formed from the array in reverse level order following a top-down approach.", "Output: Corresponding Max-Heap: 10 / \\ 5 3 / \\ 4 1 Input:", "build a Binary Heap from the given array. The heap can be either", "each node for i in range(startIdx, -1, -1): heapify(arr, n, i) # A", "of Heap def printHeap(arr, n): print(\"Array representation of Heap is:\") for i in", "Heap from the given array. The heap can be either Max Heap or", "reverse level order following a top-down approach. That is first heapify, the last", "len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17 # / \\", "last-node. or, Last non-leaf node = parent of node at (n-1)th index. or,", "of node at (n-1)th index. or, Last non-leaf node = Node at index", "13 10 / \\ / \\ 9 8 15 17 The task to", "So, the idea is to heapify the complete binary tree formed from the", "Illustration: Array = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15,", "0 in array. Left child of i-th node is at (2*i + 1)th", "5, 4, 6] in reverse order. Heapify 6: Swap 6 and 17. 1", "9 17 13 10 / \\ / \\ 4 8 15 6 Heapify", "arr[largest]: largest = l # If right child is larger than largest so", "is at (i-1)/2 index. Simple Approach: Suppose, we need to build a Max-Heap", "root l = 2 * i + 1 # left = 2*i +", "the given input elements are: 4, 10, 3, 5, 1. The corresponding complete", "largest as root l = 2 * i + 1 # left =", "4 8 3 1 Suppose the given input elements are: 4, 10, 3,", "\\ / \\ 9 17 5 10 / \\ / \\ 4 8", "\\ 15 13 / \\ / \\ 9 6 5 10 / \\", "5, 4, 6, 13, 10, 9, 8, 15, 17} Corresponding Complete Binary Tree", "4 6 13 10 / \\ / \\ 9 8 15 17 The", "larger than root if l < n and arr[l] > arr[largest]: largest =", "3 5 / \\ / \\ 4 17 13 10 / \\ /", "Nodes = 11. Last Non-leaf node index = (11/2) - 1 = 4.", "binary tree formed does not follow the Heap property. So, the idea is", "If left child is larger than root if l < n and arr[l]", "3 1''' # Python3 program for building Heap from Array # To heapify", "4, 6, 13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17 /", "__name__ == '__main__': # Binary Tree Representation # of input array # 1", "4. Therefore, last non-leaf node = 6. To build the heap, heapify only", "entire Heap will take N heapify operations and the total time complexity will", "array. Total Nodes = 11. Last Non-leaf node index = (11/2) - 1", "Corresponding Max-Heap: 17 / \\ 15 13 / \\ / \\ 9 6", "9 15 5 10 / \\ / \\ 4 8 3 6 Heapify", "Nodes. Therefore, building the entire Heap will take N heapify operations and the", "8 15 17 The task to build a Max-Heap from above array. Total", "perform the heapify operation of each non-leaf node in reverse level order. Last", "= Node at index ((n-1) - 1)/2. = (n/2) - 1. Illustration: Array", "the heap, heapify only the nodes: [1, 3, 5, 4, 6] in reverse", "time complexity where N is the total number of Nodes. Therefore, building the", "# A utility function to print the array # representation of Heap def", "3 5 # / \\ / \\ # 4 6 13 10 #", "13 10 / \\ / \\ 9 8 15 6 Heapify 4: Swap", "\\ / \\ 9 8 15 17 The task to build a Max-Heap", "11. Last Non-leaf node index = (11/2) - 1 = 4. Therefore, last", "/ \\ / \\ 4 8 15 6 Heapify 3: First Swap 3", "following a top-down approach. That is first heapify, the last node in level", "/ \\ 4 8 15 6 Heapify 5: Swap 13 and 5. 1", "be either Max Heap or Min Heap. Example: Input: arr[] = {4, 10,", "10, 3, 5, 1} Output: Corresponding Max-Heap: 10 / \\ 5 3 /", "3, 5, 1. The corresponding complete binary tree for this array of elements", "2*i + 1 r = 2 * i + 2 # right =", "* i + 1 # left = 2*i + 1 r = 2", "\\ 5 1 Note: Root is at index 0 in array. Left child", "\\ / \\ # 9 8 15 17 arr = [1, 3, 5,", "last non-leaf node and heapify # each node for i in range(startIdx, -1,", "17 13 / \\ / \\ 9 15 5 10 / \\ /", "< n and arr[l] > arr[largest]: largest = l # If right child", "node in level order traversal of the tree, then heapify the second last", "N is size of heap def heapify(arr, n, i): largest = i #", "\\ 9 6 5 10 / \\ / \\ 4 8 3 1'''", "largest = r # If largest is not root if largest != i:", "= 4. Therefore, last non-leaf node = 6. To build the heap, heapify", "\\ 4 6 13 10 / \\ / \\ 9 8 15 17", "Heap will take N heapify operations and the total time complexity will be", "swap 1 and 15, finally swap 1 and 6. 17 / \\ 15", "1 # Perform reverse level order traversal # from last non-leaf node and", "a Max-Heap from above array. Total Nodes = 11. Last Non-leaf node index", "Heapify 5: Swap 13 and 5. 1 / \\ 3 13 / \\", "\\ 4 8 3 1 Suppose the given input elements are: 4, 10,", "and 15, finally swap 1 and 6. 17 / \\ 15 13 /", "task to build a Max-Heap from above array. Total Nodes = 11. Last", "in reverse level order following a top-down approach. That is first heapify, the", "complete binary tree contains the level order traversal of the tree. So the", "6, 13, 10, 9, 8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr,", "the idea is to heapify the complete binary tree formed from the array", "again swap 3 and 15. 1 / \\ 17 13 / \\ /", "Heap or Min Heap. Example: Input: arr[] = {4, 10, 3, 5, 1}", "of i-th node is at (i-1)/2 index. Simple Approach: Suppose, we need to", "13 10 # / \\ / \\ # 9 8 15 17 arr", "they already follow the heap property. Also, the array representation of the complete", "printHeap(arr, n) # Final Heap: # 17 # / \\ # 15 13", "of N elements. The task is to build a Binary Heap from the", "node is at (i-1)/2 index. Simple Approach: Suppose, we need to build a", "Heap def printHeap(arr, n): print(\"Array representation of Heap is:\") for i in range(n):", "15, finally swap 1 and 6. 17 / \\ 15 13 / \\", "heap property. Also, the array representation of the complete binary tree contains the", "# Python3 program for building Heap from Array # To heapify a subtree", "/ \\ # 3 5 # / \\ / \\ # 4 6", "non-leaf node and perform the heapify operation of each non-leaf node in reverse", "in reverse order. Heapify 6: Swap 6 and 17. 1 / \\ 3", "Parent of i-th node is at (i-1)/2 index. Simple Approach: Suppose, we need", "5, 4, 6, 13, 10, 9, 8, 15, 17] n = len(arr) buildHeap(arr,", "8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap:", "That is first heapify, the last node in level order traversal of the", "can be optimized by observing the fact that the leaf nodes need not", "/ \\ 4 8 3 1''' # Python3 program for building Heap from", "index. Parent of i-th node is at (i-1)/2 index. Simple Approach: Suppose, we", "/ \\ / \\ 4 8 3 1 Suppose the given input elements", "than root if l < n and arr[l] > arr[largest]: largest = l", "the heapify operation of each non-leaf node in reverse level order. Last non-leaf", "4, 6, 13, 10, 9, 8, 15, 17] n = len(arr) buildHeap(arr, n)", "4, 10, 3, 5, 1. The corresponding complete binary tree for this array", "/ \\ 5 3 / \\ 4 1 Input: arr[] = {1, 3,", "the above-given array elements. It can be clearly seen that the above complete", "so on. Time Complexity: Heapify a single node takes O(log N) time complexity", "to print the array # representation of Heap def printHeap(arr, n): print(\"Array representation", "at (2*i + 1)th index. Right child of i-th node is at (2*i", "/ \\ 3 5 / \\ / \\ 4 6 13 10 /", "# 3 5 # / \\ / \\ # 4 6 13 10", "10 3 / \\ 5 1 Note: Root is at index 0 in", "N elements. The task is to build a Binary Heap from the given", "3 5 / \\ / \\ 4 6 13 10 / \\ /", "6 5 10 # / \\ / \\ # 4 8 3 1", "2 * i + 1 # left = 2*i + 1 r =", "(n/2) - 1. Illustration: Array = {1, 3, 5, 4, 6, 13, 10,", "non-leaf node in reverse level order. Last non-leaf node = parent of last-node.", "l # If right child is larger than largest so far if r", "\\ / \\ 4 8 3 1''' # Python3 program for building Heap", "are: 4, 10, 3, 5, 1. The corresponding complete binary tree for this", "Right child of i-th node is at (2*i + 2)th index. Parent of", "tree. So the idea is to find the position of the last non-leaf", "4: Swap 4 and 9. 1 / \\ 3 5 / \\ /", "# 9 6 5 10 # / \\ / \\ # 4 8", "is size of heap def heapify(arr, n, i): largest = i # Initialize", "10 / \\ / \\ 9 8 15 17 The task to build", "\\ / \\ 4 17 13 10 / \\ / \\ 9 8", "Python3 program for building Heap from Array # To heapify a subtree rooted", "- 1 # Perform reverse level order traversal # from last non-leaf node", "6 5 10 / \\ / \\ 4 8 3 1 Suppose the", "arr[largest] = arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr, n, largest)", "of elements [4, 10, 3, 5, 1] will be: 4 / \\ 10", "elements [4, 10, 3, 5, 1] will be: 4 / \\ 10 3", "position of the last non-leaf node and perform the heapify operation of each", "3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap:", "print(\"Array representation of Heap is:\") for i in range(n): print(arr[i], end=\" \") print()", "8, 15, 17} Output: Corresponding Max-Heap: 17 / \\ 15 13 / \\", "= parent of last-node. or, Last non-leaf node = parent of node at", "[4, 10, 3, 5, 1] will be: 4 / \\ 10 3 /", "1)/2. = (n/2) - 1. Illustration: Array = {1, 3, 5, 4, 6,", "range(n): print(arr[i], end=\" \") print() # Driver Code if __name__ == '__main__': #", "# 1 # / \\ # 3 5 # / \\ / \\", "tree contains the level order traversal of the tree. So the idea is", "left child is larger than root if l < n and arr[l] >", "* i + 2 # right = 2*i + 2 # If left", "9, 8, 15, 17] n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final", "n) # Final Heap: # 17 # / \\ # 15 13 #", "parent of last-node. or, Last non-leaf node = parent of node at (n-1)th", "a heap takes O(n) time depending on the implementation which can be seen", "task is to build a Binary Heap from the given array. The heap", "a top-down approach. That is first heapify, the last node in level order", "/ \\ 9 17 5 10 / \\ / \\ 4 8 15", "by observing the fact that the leaf nodes need not to be heapified", "heap def heapify(arr, n, i): largest = i # Initialize largest as root", "second last node and so on. Time Complexity: Heapify a single node takes", "total number of Nodes. Therefore, building the entire Heap will take N heapify", "swap 1 and 6. 17 / \\ 15 13 / \\ / \\", "the given array. The heap can be either Max Heap or Min Heap.", "startIdx = n // 2 - 1 # Perform reverse level order traversal", "\\ 3 13 / \\ / \\ 9 17 5 10 / \\", "be clearly seen that the above complete binary tree formed does not follow", "Binary Heap from the given array. The heap can be either Max Heap", "building Heap from Array # To heapify a subtree rooted with node i", "the nodes: [1, 3, 5, 4, 6] in reverse order. Heapify 6: Swap", "1''' # Python3 program for building Heap from Array # To heapify a", "Approach: Suppose, we need to build a Max-Heap from the above-given array elements.", "O(log N) time complexity where N is the total number of Nodes. Therefore,", "n) printHeap(arr, n) # Final Heap: # 17 # / \\ # 15", "is at (2*i + 2)th index. Parent of i-th node is at (i-1)/2", "array. Left child of i-th node is at (2*i + 1)th index. Right", "each non-leaf node in reverse level order. Last non-leaf node = parent of", "Min Heap. Example: Input: arr[] = {4, 10, 3, 5, 1} Output: Corresponding", "Total Nodes = 11. Last Non-leaf node index = (11/2) - 1 =", "buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17 # / \\ #", "n and arr[l] > arr[largest]: largest = l # If right child is", "node = parent of node at (n-1)th index. or, Last non-leaf node =", "= 6. To build the heap, heapify only the nodes: [1, 3, 5,", "level order traversal # from last non-leaf node and heapify # each node", "4, 6] in reverse order. Heapify 6: Swap 6 and 17. 1 /", "15 6 Heapify 4: Swap 4 and 9. 1 / \\ 3 5", "non-leaf node = parent of last-node. or, Last non-leaf node = parent of", "= len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17 # /", "6 Heapify 4: Swap 4 and 9. 1 / \\ 3 5 /", "i): largest = i # Initialize largest as root l = 2 *", "arr[r] > arr[largest]: largest = r # If largest is not root if", "15 13 / \\ / \\ 9 6 5 10 / \\ /", "i-th node is at (2*i + 2)th index. Parent of i-th node is", "which can be seen here. Optimized Approach: The above approach can be optimized", "optimized by observing the fact that the leaf nodes need not to be", "to heapify the complete binary tree formed from the array in reverse level", "6. To build the heap, heapify only the nodes: [1, 3, 5, 4,", "to build a Max-Heap from the above-given array elements. It can be clearly", "9 6 5 10 / \\ / \\ 4 8 3 1''' #", "a Binary Heap from the given array. The heap can be either Max", "last node and so on. Time Complexity: Heapify a single node takes O(log", "# representation of Heap def printHeap(arr, n): print(\"Array representation of Heap is:\") for", "Swap 6 and 17. 1 / \\ 3 5 / \\ / \\", "for this array of elements [4, 10, 3, 5, 1] will be: 4", "i) # A utility function to print the array # representation of Heap", "input array # 1 # / \\ # 3 5 # / \\", "child is larger than root if l < n and arr[l] > arr[largest]:", "3 1 Suppose the given input elements are: 4, 10, 3, 5, 1.", "child of i-th node is at (2*i + 1)th index. Right child of", "N is the total number of Nodes. Therefore, building the entire Heap will", "# / \\ / \\ # 4 6 13 10 # / \\", "above-given array elements. It can be clearly seen that the above complete binary", "The task to build a Max-Heap from above array. Total Nodes = 11.", "6 5 10 / \\ / \\ 4 8 3 1''' # Python3", "level order traversal of the tree. So the idea is to find the", "non-leaf node and heapify # each node for i in range(startIdx, -1, -1):", "9 8 15 17 The task to build a Max-Heap from above array.", "1 / \\ 3 13 / \\ / \\ 9 17 5 10", "from above array. Total Nodes = 11. Last Non-leaf node index = (11/2)", "child of i-th node is at (2*i + 2)th index. Parent of i-th", "Node at index ((n-1) - 1)/2. = (n/2) - 1. Illustration: Array =", "8 15 6 Heapify 5: Swap 13 and 5. 1 / \\ 3", "total time complexity will be O(N*logN). In reality, building a heap takes O(n)", "arr[l] > arr[largest]: largest = l # If right child is larger than", "/ \\ 4 1 Input: arr[] = {1, 3, 5, 4, 6, 13,", "(i-1)/2 index. Simple Approach: Suppose, we need to build a Max-Heap from the", "Tree Representation # of input array # 1 # / \\ # 3", "is larger than largest so far if r < n and arr[r] >", "of last non-leaf node startIdx = n // 2 - 1 # Perform", "level order traversal of the tree, then heapify the second last node and", "# Driver Code if __name__ == '__main__': # Binary Tree Representation # of", "Example: Input: arr[] = {4, 10, 3, 5, 1} Output: Corresponding Max-Heap: 10", "arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17]", "level order following a top-down approach. That is first heapify, the last node", "\\ # 9 6 5 10 # / \\ / \\ # 4", "Swap 3 and 17, again swap 3 and 15. 1 / \\ 17", "+ 1)th index. Right child of i-th node is at (2*i + 2)th", "swap 3 and 15. 1 / \\ 17 13 / \\ / \\", "the entire Heap will take N heapify operations and the total time complexity", "5 10 / \\ / \\ 4 8 3 1 Suppose the given", "the complete binary tree contains the level order traversal of the tree. So", "of Nodes. Therefore, building the entire Heap will take N heapify operations and", "O(N*logN). In reality, building a heap takes O(n) time depending on the implementation", "order. Heapify 6: Swap 6 and 17. 1 / \\ 3 5 /", "will be O(N*logN). In reality, building a heap takes O(n) time depending on", "will take N heapify operations and the total time complexity will be O(N*logN).", "arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the affected sub-tree heapify(arr, n,", "approach can be optimized by observing the fact that the leaf nodes need", "order traversal of the tree. So the idea is to find the position", "subtree rooted with node i # which is an index in arr[]. N", "is to find the position of the last non-leaf node and perform the", "observing the fact that the leaf nodes need not to be heapified as", "leaf nodes need not to be heapified as they already follow the heap", "i # Initialize largest as root l = 2 * i + 1", "9, 8, 15, 17} Corresponding Complete Binary Tree is: 1 / \\ 3", "a single node takes O(log N) time complexity where N is the total", "size of heap def heapify(arr, n, i): largest = i # Initialize largest", "root if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify", "the leaf nodes need not to be heapified as they already follow the", "\\ 4 8 3 1''' # Python3 program for building Heap from Array", "5 10 / \\ / \\ 4 8 15 6 Heapify 3: First", "[1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17] n =", "the above complete binary tree formed does not follow the Heap property. So,", "where N is the total number of Nodes. Therefore, building the entire Heap", "Initialize largest as root l = 2 * i + 1 # left", "is at index 0 in array. Left child of i-th node is at", "r = 2 * i + 2 # right = 2*i + 2", "\\ # 3 5 # / \\ / \\ # 4 6 13", "8 3 1 Suppose the given input elements are: 4, 10, 3, 5,", "node index = (11/2) - 1 = 4. Therefore, last non-leaf node =", "to build a Max-Heap from above array. Total Nodes = 11. Last Non-leaf", "13, 10, 9, 8, 15, 17} Output: Corresponding Max-Heap: 17 / \\ 15", "not follow the Heap property. So, the idea is to heapify the complete", "on the implementation which can be seen here. Optimized Approach: The above approach", "\\ 4 17 13 10 / \\ / \\ 9 8 15 6", "then heapify the second last node and so on. Time Complexity: Heapify a", "node = Node at index ((n-1) - 1)/2. = (n/2) - 1. Illustration:", "node = 6. To build the heap, heapify only the nodes: [1, 3,", "First Swap 3 and 17, again swap 3 and 15. 1 / \\", "# left = 2*i + 1 r = 2 * i + 2", "n): # Index of last non-leaf node startIdx = n // 2 -", "def printHeap(arr, n): print(\"Array representation of Heap is:\") for i in range(n): print(arr[i],", "/ \\ # 4 6 13 10 # / \\ / \\ #", "5 3 / \\ 4 1 Input: arr[] = {1, 3, 5, 4,", "n = len(arr) buildHeap(arr, n) printHeap(arr, n) # Final Heap: # 17 #", "largest) # Function to build a Max-Heap from the given array def buildHeap(arr,", "seen that the above complete binary tree formed does not follow the Heap", "from Array # To heapify a subtree rooted with node i # which", "in range(startIdx, -1, -1): heapify(arr, n, i) # A utility function to print", "of Heap is:\") for i in range(n): print(arr[i], end=\" \") print() # Driver", "> arr[largest]: largest = l # If right child is larger than largest", "not root if largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively", "above complete binary tree formed does not follow the Heap property. So, the", "the last node in level order traversal of the tree, then heapify the", "= 2*i + 2 # If left child is larger than root if", "Max-Heap: 10 / \\ 5 3 / \\ 4 1 Input: arr[] =", "/ \\ / \\ 4 17 13 10 / \\ / \\ 9", "to find the position of the last non-leaf node and perform the heapify", "largest != i: arr[i], arr[largest] = arr[largest], arr[i] # Recursively heapify the affected", "i in range(n): print(arr[i], end=\" \") print() # Driver Code if __name__ ==", "node in reverse level order. Last non-leaf node = parent of last-node. or,", "6. 17 / \\ 15 13 / \\ / \\ 9 6 5", "17 The task to build a Max-Heap from above array. Total Nodes =", "the last non-leaf node and perform the heapify operation of each non-leaf node", "r # If largest is not root if largest != i: arr[i], arr[largest]", "# 15 13 # / \\ / \\ # 9 6 5 10", "tree formed does not follow the Heap property. So, the idea is to", "node is at (2*i + 2)th index. Parent of i-th node is at", "time depending on the implementation which can be seen here. Optimized Approach: The", "3, 5, 4, 6, 13, 10, 9, 8, 15, 17} Corresponding Complete Binary", "is at (2*i + 1)th index. Right child of i-th node is at", "Recursively heapify the affected sub-tree heapify(arr, n, largest) # Function to build a", "+ 2 # right = 2*i + 2 # If left child is", "/ \\ / \\ 9 6 5 10 / \\ / \\ 4", "Tree is: 1 / \\ 3 5 / \\ / \\ 4 6", "in level order traversal of the tree, then heapify the second last node", "-1, -1): heapify(arr, n, i) # A utility function to print the array", "arr[] = {1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17}", "in reverse level order. Last non-leaf node = parent of last-node. or, Last", "for i in range(n): print(arr[i], end=\" \") print() # Driver Code if __name__", "13 / \\ / \\ 9 17 5 10 / \\ / \\", "# 17 # / \\ # 15 13 # / \\ / \\", "the idea is to find the position of the last non-leaf node and", "root if l < n and arr[l] > arr[largest]: largest = l #", "of input array # 1 # / \\ # 3 5 # /", "i in range(startIdx, -1, -1): heapify(arr, n, i) # A utility function to", "will be: 4 / \\ 10 3 / \\ 5 1 Note: Root", "and arr[l] > arr[largest]: largest = l # If right child is larger", "complexity will be O(N*logN). In reality, building a heap takes O(n) time depending", "O(n) time depending on the implementation which can be seen here. Optimized Approach:", "print the array # representation of Heap def printHeap(arr, n): print(\"Array representation of", "idea is to heapify the complete binary tree formed from the array in", "which is an index in arr[]. N is size of heap def heapify(arr,", "Code if __name__ == '__main__': # Binary Tree Representation # of input array", "if r < n and arr[r] > arr[largest]: largest = r # If", "= [1, 3, 5, 4, 6, 13, 10, 9, 8, 15, 17] n", "9 6 5 10 / \\ / \\ 4 8 3 1 Suppose", "The heap can be either Max Heap or Min Heap. Example: Input: arr[]", "# from last non-leaf node and heapify # each node for i in", "15 17 The task to build a Max-Heap from above array. Total Nodes", "5 / \\ / \\ 4 17 13 10 / \\ / \\", "17 arr = [1, 3, 5, 4, 6, 13, 10, 9, 8, 15,", "-1): heapify(arr, n, i) # A utility function to print the array #", "17 / \\ 15 13 / \\ / \\ 9 6 5 10", "5 1 Note: Root is at index 0 in array. Left child of" ]
[ "def romanToInt(self, s): \"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000}", "s): \"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr =", "class Solution(object): def romanToInt(self, s): \"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map", "int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while current_ptr<len(s):", "= 0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2", "str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0", "= 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2 continue result+=roman_to_int_map[s[current_ptr]] current_ptr+=1", "{\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]:", "romanToInt(self, s): \"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr", ":rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while", ":type s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result", "\"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while current_ptr<len(s): if", "0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2 continue result+=roman_to_int_map[s[current_ptr]] current_ptr+=1 return", "result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2 continue result+=roman_to_int_map[s[current_ptr]]", "0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2 continue", "while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]]) current_ptr+=2 continue result+=roman_to_int_map[s[current_ptr]] current_ptr+=1 return result", "Solution(object): def romanToInt(self, s): \"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map =", "<reponame>salman-kgp/leetcode<filename>google/easy/roman_to_integer.py class Solution(object): def romanToInt(self, s): \"\"\" :type s: str :rtype: int \"\"\"", "roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s)", "\"\"\" :type s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0", "current_ptr = 0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and roman_to_int_map[s[current_ptr]]<roman_to_int_map[s[current_ptr+1]]: result+=(roman_to_int_map[s[current_ptr+1]]-roman_to_int_map[s[current_ptr]])", "s: str :rtype: int \"\"\" roman_to_int_map = {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result =", "= {\"I\":1,\"V\":5,\"X\":10,\"L\":50,\"C\":100,\"D\":500,\"M\":1000} current_ptr = 0 result = 0 while current_ptr<len(s): if current_ptr+1<len(s) and" ]
[ "keras.utils import plot_model import pandas as pd import numpy as np from ann_visualizer.visualize", "print(\"Loaded model from disk\") #try visualizing it #view = True will result in", "import ann_viz import glob import os #batch visualize: for model in glob.glob('./models/*.json'): #load", "#load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it #view = True", "ann_viz import glob import os #batch visualize: for model in glob.glob('./models/*.json'): #load json", "classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights:", "glob import os #batch visualize: for model in glob.glob('./models/*.json'): #load json model: classifier_name", "model from disk\") #try visualizing it #view = True will result in .pdf", "from ann_visualizer.visualize import ann_viz import glob import os #batch visualize: for model in", "= open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded", "will result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN')", "plot_model import pandas as pd import numpy as np from ann_visualizer.visualize import ann_viz", "as np from ann_visualizer.visualize import ann_viz import glob import os #batch visualize: for", "import plot_model import pandas as pd import numpy as np from ann_visualizer.visualize import", "glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json'", "= classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load", "import numpy as np from ann_visualizer.visualize import ann_viz import glob import os #batch", "import glob import os #batch visualize: for model in glob.glob('./models/*.json'): #load json model:", "model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r')", ".pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN') plot_model(classifier,to_file='VisualizeLayers_'+classifier_name+'.png',show_shapes=True,show_layer_names=True) print(\"Models have", "as pd import numpy as np from ann_visualizer.visualize import ann_viz import glob import", "classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close()", "disk\") #try visualizing it #view = True will result in .pdf files of", "numpy as np from ann_visualizer.visualize import ann_viz import glob import os #batch visualize:", "weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it #view = True will", "from disk\") #try visualizing it #view = True will result in .pdf files", "in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model =", "from keras.models import model_from_json from keras.utils import plot_model import pandas as pd import", "= model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it #view", "= os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json =", "classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier =", "classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it #view = True will result", "= True will result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier:", "import model_from_json from keras.utils import plot_model import pandas as pd import numpy as", "np from ann_visualizer.visualize import ann_viz import glob import os #batch visualize: for model", "visualize: for model in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights =", "files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN') plot_model(classifier,to_file='VisualizeLayers_'+classifier_name+'.png',show_shapes=True,show_layer_names=True) print(\"Models have been", "pandas as pd import numpy as np from ann_visualizer.visualize import ann_viz import glob", "#view = True will result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German", "#batch visualize: for model in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights", "#try visualizing it #view = True will result in .pdf files of visualization", "os #batch visualize: for model in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0]", "model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it #view =", "import pandas as pd import numpy as np from ann_visualizer.visualize import ann_viz import", "result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN') plot_model(classifier,to_file='VisualizeLayers_'+classifier_name+'.png',show_shapes=True,show_layer_names=True)", "pd import numpy as np from ann_visualizer.visualize import ann_viz import glob import os", "model = classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json)", "ann_visualizer.visualize import ann_viz import glob import os #batch visualize: for model in glob.glob('./models/*.json'):", "True will result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple", "keras from keras.models import model_from_json from keras.utils import plot_model import pandas as pd", "= classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier", "model in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model", "classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from", "json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing", "keras.models import model_from_json from keras.utils import plot_model import pandas as pd import numpy", "#load json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file", "it #view = True will result in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English", "in .pdf files of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN') plot_model(classifier,to_file='VisualizeLayers_'+classifier_name+'.png',show_shapes=True,show_layer_names=True) print(\"Models", "json_file = open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights)", "open(model,'r') classifier_json = json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model", "visualizing it #view = True will result in .pdf files of visualization ann_viz(classifier,view=True,", "model_from_json from keras.utils import plot_model import pandas as pd import numpy as np", "from keras.utils import plot_model import pandas as pd import numpy as np from", "classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json", "json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try", "import os #batch visualize: for model in glob.glob('./models/*.json'): #load json model: classifier_name =", "= json_file.read() json_file.close() classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\")", "of visualization ann_viz(classifier,view=True, filename='Visualize_'+classifier_name,title='English German Classifier: Simple ANN') plot_model(classifier,to_file='VisualizeLayers_'+classifier_name+'.png',show_shapes=True,show_layer_names=True) print(\"Models have been visualized\")", "classifier = model_from_json(classifier_json) #load weights: classifier.load_weights(classifier_weights) print(\"Loaded model from disk\") #try visualizing it", "import keras from keras.models import model_from_json from keras.utils import plot_model import pandas as", "os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file = open(model,'r') classifier_json = json_file.read()", "for model in glob.glob('./models/*.json'): #load json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5'", "json model: classifier_name = os.path.splitext(model)[0] classifier_weights = classifier_name+'.h5' model = classifier_name+'.json' json_file =" ]
[ "torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[", "python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\",", "about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with", "jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\",", "about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description = fh.read()", "version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\",", "youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\",", "setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(),", "License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\",", "= [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test", "classifiers=[ \"License :: OSI Approved :: Apache Software License\", \"Operating System :: OS", "with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description = fh.read() #", "packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\",", "\"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, },", "= [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\",", "setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about)", "\"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws,", "import find_packages, setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh:", "\"youtube\": youtube, \"all\": all, }, classifiers=[ \"License :: OSI Approved :: Apache Software", "youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch + jupyter +", "Software License\", \"Operating System :: OS Independent\", \"Programming Language :: Python :: 3\",", "/ \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\",", "\"Operating System :: OS Independent\", \"Programming Language :: Python :: 3\", \"Topic ::", "open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description = fh.read() # extras", "[\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs", "\"r\", ) as fh: long_description = fh.read() # extras test = [\"pytest\"] torch", "\"License :: OSI Approved :: Apache Software License\", \"Operating System :: OS Independent\",", "\"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License :: OSI", "\"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test,", "Approved :: Apache Software License\", \"Operating System :: OS Independent\", \"Programming Language ::", "Apache Software License\", \"Operating System :: OS Independent\", \"Programming Language :: Python ::", "\"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all", "\"youtube_dl\", \"ffmpeg-python\"] all = test + torch + jupyter + aws + docs", "docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License :: OSI Approved :: Apache", "\"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs,", "+ torch + jupyter + aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"],", "youtube, \"all\": all, }, classifiers=[ \"License :: OSI Approved :: Apache Software License\",", "extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube,", "aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License :: OSI Approved", "= [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch + jupyter + aws", "\"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={", "= [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch +", "Language :: Python :: 3\", \"Topic :: Software Development :: Libraries\", ], )", "\"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter,", "= [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"]", "open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\",", "test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all,", "extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws", "Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\",", "author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\",", "= fh.read() # extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter =", "\"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\":", "2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\",", "], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\":", "\"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License :: OSI Approved ::", "\"all\": all, }, classifiers=[ \"License :: OSI Approved :: Apache Software License\", \"Operating", "\"Programming Language :: Python :: 3\", \"Topic :: Software Development :: Libraries\", ],", "\"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\":", "all, }, classifiers=[ \"License :: OSI Approved :: Apache Software License\", \"Operating System", "+ youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\",", ":: OSI Approved :: Apache Software License\", \"Operating System :: OS Independent\", \"Programming", "OSI Approved :: Apache Software License\", \"Operating System :: OS Independent\", \"Programming Language", "install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ],", "license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[", "\"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License", "= {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open(", "as fh: long_description = fh.read() # extras test = [\"pytest\"] torch = [\"torch>=1.5.0\",", "jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\": all, }, classifiers=[ \"License ::", "setuptools import find_packages, setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as", "long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\",", "\"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as", "pathlib import re from setuptools import find_packages, setup about = {} with open(pathlib.Path(\"rikai\")", "with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent /", "+ docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\",", "\"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\":", "Independent\", \"Programming Language :: Python :: 3\", \"Topic :: Software Development :: Libraries\",", "import pathlib import re from setuptools import find_packages, setup about = {} with", "\"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube =", "fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description", "author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\",", ":: Apache Software License\", \"Operating System :: OS Independent\", \"Programming Language :: Python", "torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs =", "[\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"]", "[\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch + jupyter + aws +", "+ aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\",", "[\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch + jupyter", "as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh:", "\"README.md\", \"r\", ) as fh: long_description = fh.read() # extras test = [\"pytest\"]", "long_description = fh.read() # extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter", "name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True,", "re from setuptools import find_packages, setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\",", "test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws =", "[\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test +", "fh.read() # extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\",", "jupyter + aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version", "{} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent", "System :: OS Independent\", \"Programming Language :: Python :: 3\", \"Topic :: Software", "}, classifiers=[ \"License :: OSI Approved :: Apache Software License\", \"Operating System ::", "# extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"]", "License\", \"Operating System :: OS Independent\", \"Programming Language :: Python :: 3\", \"Topic", "\"ffmpeg-python\"] all = test + torch + jupyter + aws + docs +", "= [\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"]", "\"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\":", "docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all = test + torch", "aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\",", "fh: long_description = fh.read() # extras test = [\"pytest\"] torch = [\"torch>=1.5.0\", \"torchvision\"]", "docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License, Version 2.0\", author=\"<NAME>\", author_email=\"<EMAIL>\", long_description=long_description,", "\"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch,", "all = test + torch + jupyter + aws + docs + youtube", "aws = [\"boto\"] docs = [\"sphinx\"] youtube = [\"pafy\", \"youtube_dl\", \"ffmpeg-python\"] all =", "url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\",", "exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description =", "from setuptools import find_packages, setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\")", "[\"torch>=1.5.0\", \"torchvision\"] jupyter = [\"matplotlib\", \"jupyterlab\"] aws = [\"boto\"] docs = [\"sphinx\"] youtube", ") as fh: long_description = fh.read() # extras test = [\"pytest\"] torch =", "\"__version__.py\", \"r\") as fh: exec(fh.read(), about) with open( pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", )", "+ jupyter + aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache License,", "/ \"README.md\", \"r\", ) as fh: long_description = fh.read() # extras test =", "test + torch + jupyter + aws + docs + youtube setup( name=\"rikai\",", "pathlib.Path(__file__).absolute().parent.parent / \"README.md\", \"r\", ) as fh: long_description = fh.read() # extras test", "= test + torch + jupyter + aws + docs + youtube setup(", "OS Independent\", \"Programming Language :: Python :: 3\", \"Topic :: Software Development ::", "torch + jupyter + aws + docs + youtube setup( name=\"rikai\", version=about[\"version\"], license=\"Apache", "\"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\": aws, \"docs\": docs, \"youtube\": youtube, \"all\":", "import re from setuptools import find_packages, setup about = {} with open(pathlib.Path(\"rikai\") /", "\"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\", \"requests\", ], extras_require={ \"test\": test, \"pytorch\": torch, \"jupyter\": jupyter, \"aws\":", "long_description=long_description, long_description_content_type=\"text/markdown\", url=\"https://github.com/eto-ai/rikai\", packages=find_packages(), include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\",", "include_package_data=True, python_requires=\">=3.7\", install_requires=[ \"antlr4-python3-runtime\", \"ipython\", \"jsonschema\", \"numpy\", \"opencv-python\", \"pandas\", \"Pillow\", \"pyarrow>=2.0\", \"pyspark>=3.1,<3.2\", \"pyyaml\",", ":: OS Independent\", \"Programming Language :: Python :: 3\", \"Topic :: Software Development", "find_packages, setup about = {} with open(pathlib.Path(\"rikai\") / \"__version__.py\", \"r\") as fh: exec(fh.read()," ]
[ "depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param", "(auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears() self.nextsort +=", "== None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1)", "self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if", "not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\",", "buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy,", "quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need", "cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000,", "props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 =", "FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0,", "None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth)", "0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr =", "None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex", "textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\",", "cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity())", "ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None:", "if (textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\",", "fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param texgroup: :param", "overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param texgroup: :param depthbits: :param", "# Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens", "self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0))", "of the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if fbprops is", "\"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex =", "winy) = self.getScaledSize(1, 1, 1) if fbprops is not None: buffer = self.createBuffer(\"filter-base\",", "<reponame>takuya-ki/wrs<filename>visualization/panda/filtermanager.py from direct.filter import FilterManager as pfm from panda3d.core import Texture, CardMaker, NodePath,", "(auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable,", "fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param auxbits:", "(winx, winy) = self.getScaledSize(1, 1, 1) if fbprops is not None: buffer =", "auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex:", "1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion()", "= NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to turn on the Shader", "to turn on the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping", "0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to", "in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2,", "textures: :param fbprops: :param clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\", None)", "direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param texgroup: :param depthbits: :param fbprops:", "if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1)", "buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer)", "0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears()", "texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props", "quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we", "clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param auxbits: :param", "GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears() self.nextsort += 1 return buffer", "1)) return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload", "FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None,", "self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer ==", ":param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0)", "# Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1,", "if fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else:", "dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name, xsize, ysize, texgroup,", "auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 = None if (colortex", "ysize: :param texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize,", "if fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if", "Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class", "1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to turn on", "def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None,", "__init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None,", "we really need to turn on the Shader Generator? # cs.setShaderAuto() if (auxbits):", "Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables", "texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size of the offscreen", "OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer,", "= Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the", "props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0,", "overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param auxbits: :param textures: :param", "colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose", "# Do we really need to turn on the Shader Generator? # cs.setShaderAuto()", "really need to turn on the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits))", "the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2)", "dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def", "def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param", "props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1", "cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping in the", "(auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1,", "cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\"", "(depthtex, colortex, auxtex0, auxtex1) # Choose the size of the offscreen buffer. (winx,", ":param name: :param xsize: :param ysize: :param texgroup: :param depthbits: :param fbprops: :return:", "(colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0,", "2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears)", "props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return buffer", "depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param texgroup:", "self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None):", "textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param", "-1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return", "texgroup) if (buffer == None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad =", "None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) #", "turn on the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is", ":param colortex: :param auxtex: :param auxbits: :param textures: :param fbprops: :param clamping: :return:", "False: # Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\")", ":param texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize)", "self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1):", "None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex)", "None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1)", ":param depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props =", "quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really", "need to turn on the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if", "= self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup)", "from direct.filter import FilterManager as pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib,", "textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 = None if (colortex == None):", "dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name, xsize,", "= FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex,", "the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: #", ":param clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\",", "(textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None)", "colortex: :param auxtex: :param auxbits: :param textures: :param fbprops: :param clamping: :return: \"\"\"", "quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0,", "depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault())", "= buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self,", "None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5,", "props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow", "offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if fbprops is not None:", ":param ysize: :param texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops = WindowProperties()", "auxtex0 = auxtex auxtex1 = None if (colortex == None): colortex = Texture(\"filter-base-color\")", ":param fbprops: :param clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex", "1, 1) if fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup,", "cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs =", "direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param auxbits: :param textures: :param fbprops:", "textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 =", "depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1", "clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None)", "quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens)", "None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex)", "None) else: auxtex0 = auxtex auxtex1 = None if (colortex == None): colortex", "lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0,", "= textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0", "colortex, auxtex0, auxtex1) # Choose the size of the offscreen buffer. (winx, winy)", "textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\",", "not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0 != None):", "= auxtex auxtex1 = None if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp)", "ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize:", "NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to turn on the Shader Generator?", "buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name,", "buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if", "createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param", "self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1,", "GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears() self.nextsort += 1 return", "name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize:", "from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties,", "colortex, auxtex0, auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 !=", "if (buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex):", "None if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex,", "textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 = None", "NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def", "auxtex0, auxtex1) # Choose the size of the offscreen buffer. (winx, winy) =", "winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if", "GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort)", "the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if fbprops is not", "shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0,", "return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1,", "quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param", "WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self,", "import FilterManager as pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera,", "texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None):", "name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None):", "depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1", ":param xsize: :param ysize: :param texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops", "auxtex auxtex1 = None if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp)", "(colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy,", "= CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1)", "direct.filter import FilterManager as pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib,", "auxtex: :param auxbits: :param textures: :param fbprops: :param clamping: :return: \"\"\" if (textures):", "(buffer == None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0)", "quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0,", "texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param", "\"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo())", "auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1", "buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if fbprops is not None: buffer", "lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears,", "\\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam)", "auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 = None if", "1, 1)) return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\"", "winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return buffer if", "= WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops", "return quad def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer", "if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex,", "depthtex: :param colortex: :param auxtex: :param auxbits: :param textures: :param fbprops: :param clamping:", "cs.setState(self.camstate) # Do we really need to turn on the Shader Generator? #", "= (depthtex, colortex, auxtex0, auxtex1) # Choose the size of the offscreen buffer.", "0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to turn", "self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000)", "renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex:", "Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size", "FilterManager as pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens,", "!= None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props,", ":return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits)", "fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer", "name: :param xsize: :param ysize: :param texgroup: :param depthbits: :param fbprops: :return: \"\"\"", "= OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam)", "auxtex0, auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None):", "None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None)", "auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else:", "self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None): return None cm = CardMaker(\"filter-base-quad\")", ":param auxbits: :param textures: :param fbprops: :param clamping: :return: \"\"\" if (textures): colortex", "None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops,", "self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1,", "if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera)", "else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None): return None", "== None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0)", "(depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy,", "Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam =", "xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param", "1) if fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops)", "= textures.get(\"aux0\", auxtex) auxtex1 = textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 =", "if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears() self.nextsort", "buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None): return None cm", "is False: # Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode =", "= textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 =", "# cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping in", "1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()):", "auxtex1 = None if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup", "= textures.get(\"aux1\", None) else: auxtex0 = auxtex auxtex1 = None if (colortex ==", "GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears()", "if clamping is False: # Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState())", "buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1)", "Do we really need to turn on the Shader Generator? # cs.setShaderAuto() if", "on the Shader Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False:", "= textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0 = textures.get(\"aux0\", auxtex) auxtex1 =", "cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5,", "(buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex,", ":param auxtex: :param auxbits: :param textures: :param fbprops: :param clamping: :return: \"\"\" if", "quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5,", "if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1,", "class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None,", "fbprops: :return: \"\"\" winprops = WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1)", "size of the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if fbprops", "0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0):", "if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping in the shader", "if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1))", "(0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr", "None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win)", "colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size of the", "winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer ==", "dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad def createBuffer(self, name, xsize, ysize,", "fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0", "= texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput(", "self.win.getGsg(), self.win) if (buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor)", "= quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5,", "None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx,", "auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2)", "\"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param auxtex: :param auxbits: :param textures:", "texgroup if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(),", "winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not", "return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if", "def createBuffer(self, name, xsize, ysize, texgroup, depthbits=1, fbprops=None): \"\"\" overload direct.filters.FilterManager.createBuffer :param name:", "if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow |", "clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens()", "if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0,", "if (buffer == None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate())", "1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1,", "auxbits: :param textures: :param fbprops: :param clamping: :return: \"\"\" if (textures): colortex =", "is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0 !=", "pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput,", "fbprops: :param clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex =", "1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1)", "LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win,", "lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode) self.region.setCamera(quadcam) self.setStackedClears(buffer, self.rclears, self.wclears) if", "cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do we really need to turn on the", "lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam = quad.attachNewNode(quadcamnode)", "(auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears()", "OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win,", "self.wclears) if (auxtex0): buffer.setClearActive(GraphicsOutput.RTPAuxRgba0, 1) buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1,", "NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) #", "WindowProperties() winprops.setSize(xsize, ysize) props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is", "if (auxtex0 != None): props.setAuxRgba(1) if (auxtex1 != None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name,", "(self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return", "Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens =", "== None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy,", "xsize: :param ysize: :param texgroup: :param depthbits: :param fbprops: :return: \"\"\" winprops =", "\"\"\" overload direct.filters.FilterManager.createBuffer :param name: :param xsize: :param ysize: :param texgroup: :param depthbits:", "CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager):", "generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode = Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0)", "AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self,", "| GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex,", "props = FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops)", "winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer", "!= None): props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(),", "CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs", "fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None): return", "cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto", "winx, winy, texgroup) if (buffer == None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad()", "= None if (colortex == None): colortex = Texture(\"filter-base-color\") colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup =", "Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam):", "super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload", "FrameBufferProperties(FrameBufferProperties.getDefault()) props.setBackBuffers(0) props.setRgbColor(1) props.setDepthBits(depthbits) props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex, colortex,", "props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup if (auxtex0 != None): props.setAuxRgba(1) if", "= NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate)", "quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\") cs.setState(self.camstate) # Do", "self.getScaledSize(1, 1, 1) if fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx, winy,", "buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer", "clamping is False: # Disables clamping in the shader generator. cs.setAttrib(LightRampAttrib.make_identity()) self.camera.node().setInitialState(cs.getState()) quadcamnode", "GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None,", "self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1) self.buffers.append(buffer) self.sizes.append((1, 1, 1)) return quad", "import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe", "panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\ GraphicsOutput, WindowProperties, FrameBufferProperties,", "as pfm from panda3d.core import Texture, CardMaker, NodePath, AuxBitplaneAttrib, LightRampAttrib, Camera, OrthographicLens, \\", "buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0):", "(auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping in the shader generator.", "self.win) if (buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if", "buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0)", "buffer.setClearValue(GraphicsOutput.RTPAuxRgba0, (0.5, 0.5, 1.0, 0.0)) if (auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears()", "Generator? # cs.setShaderAuto() if (auxbits): cs.setAttrib(AuxBitplaneAttrib.make(auxbits)) if clamping is False: # Disables clamping", "the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1) if", ":param depthtex: :param colortex: :param auxtex: :param auxbits: :param textures: :param fbprops: :param", "winy, texgroup) if (buffer == None): return None cm = CardMaker(\"filter-base-quad\") cm.setFrameFullscreenQuad() quad", "auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex: :param", "is not None: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer =", "(auxtex1): buffer.setClearActive(GraphicsOutput.RTPAuxRgba1, 1) self.region.disableClears() if (self.isFullscreen()): self.win.disableClears() dr = buffer.makeDisplayRegion() dr.disableClears() dr.setCamera(self.camera) dr.setActive(1)", "GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1):", "Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1, 1, 1)", "quad = NodePath(cm.generate()) quad.setDepthTest(0) quad.setDepthWrite(0) quad.setTexture(colortex) quad.setColor(1, 0.5, 0.5, 1) cs = NodePath(\"dummy\")", ":return: \"\"\" if (textures): colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex", "props.setAuxRgba(2) buffer=base.graphicsEngine.makeOutput( self.win.getPipe(), name, -1, props, winprops, GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if", "self.createBuffer(\"filter-base\", winx, winy, texgroup, fbprops=fbprops) else: buffer = self.createBuffer(\"filter-base\", winx, winy, texgroup) if", "buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if (auxtex1): buffer.addRenderTexture(auxtex1, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba1) buffer.setSort(self.nextsort) buffer.disableClears() self.nextsort += 1", "colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None): \"\"\" overload direct.filters.FilterManager.renderSceneInto :param depthtex: :param colortex:", "GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPColor) if (depthtex): buffer.addRenderTexture(depthtex, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPDepth) if (auxtex0): buffer.addRenderTexture(auxtex0, GraphicsOutput.RTMBindOrCopy, GraphicsOutput.RTPAuxRgba0) if", "else: auxtex0 = auxtex auxtex1 = None if (colortex == None): colortex =", "= self.createBuffer(\"filter-base\", winx, winy, texgroup) if (buffer == None): return None cm =", "GraphicsOutput, WindowProperties, FrameBufferProperties, GraphicsPipe class FilterManager(pfm.FilterManager): def __init__(self, win, cam): super().__init__(win, cam) def", "colortex = textures.get(\"color\", None) depthtex = textures.get(\"depth\", None) auxtex = textures.get(\"aux\", None) auxtex0", "GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return buffer if (colortex): buffer.addRenderTexture(colortex, GraphicsOutput.RTMBindOrCopy,", "colortex.setWrapU(Texture.WMClamp) colortex.setWrapV(Texture.WMClamp) texgroup = (depthtex, colortex, auxtex0, auxtex1) # Choose the size of", ":param textures: :param fbprops: :param clamping: :return: \"\"\" if (textures): colortex = textures.get(\"color\",", "win, cam): super().__init__(win, cam) def renderSceneInto(self, depthtex=None, colortex=None, auxtex=None, auxbits=0, textures=None, fbprops=None, clamping=None):", "= Camera(\"filter-quad-cam\") lens = OrthographicLens() lens.setFilmSize(2, 2) lens.setFilmOffset(0, 0) lens.setNearFar(-1000, 1000) quadcamnode.setLens(lens) quadcam", "= self.getScaledSize(1, 1, 1) if fbprops is not None: buffer = self.createBuffer(\"filter-base\", winx,", "auxtex1) # Choose the size of the offscreen buffer. (winx, winy) = self.getScaledSize(1,", "props.setStereo(self.win.isStereo()) if fbprops is not None: props.addProperties(fbprops) depthtex, colortex, auxtex0, auxtex1 = texgroup", "GraphicsPipe.BFRefuseWindow | GraphicsPipe.BFResizeable, self.win.getGsg(), self.win) if (buffer == None): return buffer if (colortex):" ]
[ "= f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner) if __name__", "xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8')", "= prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test():", "PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f:", "test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt =", "as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4,", "docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path)", "import context, testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path", "coding: utf-8 import context, testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def", "def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt", "f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner) if __name__ ==", "open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult)", "txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner) if", "testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml'", "pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def", "class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as", "with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner =", "prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner", "= 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str,", "utf-8 import context, testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self):", "prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml')", "<gh_stars>1-10 # coding: utf-8 import context, testutils, unittest from docxperiments import prettify class", "self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner) if __name__ == '__main__':", "unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str", "txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner) if __name__ == '__main__': test()", "# coding: utf-8 import context, testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase):", "from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str =", "context, testutils, unittest from docxperiments import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path =", "'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with open('testdata/pretty.xml') as f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1])", "f: txt = f.read().decode('utf-8') self.assertEqual(pretty_xml_str, txt[:-1]) def test(): runner = unittest.TextTestRunner(resultclass=testutils.CustomResult) unittest.main(verbosity=4, testRunner=runner)", "import prettify class PrettifyTest(unittest.TestCase): def test_prettify_makes_xml_pretty(self): xml_file_path = 'testdata/ugly.xml' pretty_xml_str = prettify.prettify_xml(xml_file_path) with" ]
[ "'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner, BannerAdmin) xadmin.site.register(views.BaseAdminView,BaseSetting)", "enable_themes = True use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer =", "'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image',", "'2021/7/7 11:09' import xadmin from xadmin import views from .models import EmailVerifyRecord,Banner class", "\"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email',", "['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields", "'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title',", "'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter", "'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time']", "'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields", "class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index']", "EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch = True class GlobalSetting(object): site_title =", "class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object):", "from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch = True class", "11:09' import xadmin from xadmin import views from .models import EmailVerifyRecord,Banner class BaseSetting(object):", "= ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time']", "site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display =", "= ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter = ['title',", "import xadmin from xadmin import views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes", "BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter", "class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type',", "GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display", "= True use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网'", "'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url',", "search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display =", ".models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch = True class GlobalSetting(object):", "'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url',", "xadmin import views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch", "['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter = ['title', 'image',", "views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch = True", "_*_ encoding:utf-8 _*_ __author__ = 'wuqy' __date__ = '2021/7/7 11:09' import xadmin from", "menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter =", "= '2021/7/7 11:09' import xadmin from xadmin import views from .models import EmailVerifyRecord,Banner", "= 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type']", "BaseSetting(object): enable_themes = True use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer", "= ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title',", "list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class", "__date__ = '2021/7/7 11:09' import xadmin from xadmin import views from .models import", "True use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style", "list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image', 'url',", "search_fields =['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)", "import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch = True class GlobalSetting(object): site_title", "'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner, BannerAdmin) xadmin.site.register(views.BaseAdminView,BaseSetting) xadmin.site.register(views.CommAdminView,GlobalSetting)", "_*_ __author__ = 'wuqy' __date__ = '2021/7/7 11:09' import xadmin from xadmin import", "# _*_ encoding:utf-8 _*_ __author__ = 'wuqy' __date__ = '2021/7/7 11:09' import xadmin", "['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display = ['title', 'image',", "list_display = ['title', 'image', 'url', 'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter =", "True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class", "use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style =", "site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields =", "= ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object):", "__author__ = 'wuqy' __date__ = '2021/7/7 11:09' import xadmin from xadmin import views", "xadmin from xadmin import views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes =", "from xadmin import views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True", "= 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time']", "['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time'] class BannerAdmin(object): list_display", "'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner, BannerAdmin)", "EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code', 'email', 'send_type', 'send_time']", "<reponame>Airren/mxonline-python<filename>apps/users/adminx.py # _*_ encoding:utf-8 _*_ __author__ = 'wuqy' __date__ = '2021/7/7 11:09' import", "class BaseSetting(object): enable_themes = True use_bootswatch = True class GlobalSetting(object): site_title = 'wuqy的管理系统'", "import views from .models import EmailVerifyRecord,Banner class BaseSetting(object): enable_themes = True use_bootswatch =", "encoding:utf-8 _*_ __author__ = 'wuqy' __date__ = '2021/7/7 11:09' import xadmin from xadmin", "=['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner,", "'index','add_time'] search_fields =['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index','add_time'] xadmin.site.register(EmailVerifyRecord,", "= True class GlobalSetting(object): site_title = 'wuqy的管理系统' site_footer = 'wuqy的在线课程网' menu_style = \"accordion\"", "= \"accordion\" class EmailVerifyRecordAdmin(object): list_display = ['code','email','send_type','send_time'] search_fields = ['code','email','send_type'] list_filter = ['code',", "'wuqy' __date__ = '2021/7/7 11:09' import xadmin from xadmin import views from .models", "= 'wuqy' __date__ = '2021/7/7 11:09' import xadmin from xadmin import views from" ]
[ "MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create", "\"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises no", "check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Cannot", "check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output,", "import patch from path import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import", "lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not", "seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths =", "zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Cannot parse metadata: invalid\"] )", "logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\",", "mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create", "invalid subtitle file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value", "get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check duration", "song = BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation", "test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no exception but logs", "patch from path import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser,", "mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") #", "def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises no exception but", "representation = song.get_representation() # check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") #", "but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value =", "datetime import timedelta from unittest import TestCase from unittest.mock import patch from path", "parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse):", "@patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid", "file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\")", "logger: representation = song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) #", "# get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check", "BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test", "as logger: representation = song.get_representation() # check no lyrics has been found self.assertEqual(representation[\"lyrics\"],", "mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\"))", "get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check no", "self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"],", "@patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises", "duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Cannot parse", "from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong", "unittest.mock import patch from path import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata", "self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check no lyrics has been found", "import timedelta from unittest import TestCase from unittest.mock import patch from path import", "import TestCase from unittest.mock import patch from path import Path from dakara_feeder.directory import", "invalid video file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect", "subtitle file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value =", "defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Cannot parse metadata:", "BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation()", "representation = song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert", "\"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song", "dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from", "autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises no exception", "@patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid", "file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta(", "mocked_subtitle_parse): \"\"\"Test an invalid video file raises no exception but logs error.\"\"\" #", "= SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get", "dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong", "import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser,", "setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\")", "invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test", "exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\"", "video file raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect =", "import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\"", "song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check no lyrics", "# create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song =", "Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\",", "# check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output,", "song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check duration defaults", "song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual(", "1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create", "= BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation =", "timedelta from unittest import TestCase from unittest.mock import patch from path import Path", "create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\")", "test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises no exception but logs", "from path import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError", "with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check duration defaults to zero", "error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths", "SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True)", "# setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths", "song.get_representation() # check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs", "class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an", "no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value =", "= \"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance", "mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file raises no exception but logs error.\"\"\"", "raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value", "logger: representation = song.get_representation() # check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\")", "paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths)", "BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self,", "from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\",", "representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check no lyrics has", "BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as", "TestCase from unittest.mock import patch from path import Path from dakara_feeder.directory import SongPaths", "path import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from", "import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing", "# check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual(", "SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get song", "= 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) #", "found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] )", "MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test", "an invalid subtitle file raises no exception but logs error.\"\"\" # setup mocks", "mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths = SongPaths(Path(\"file.mp4\"),", "dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True)", "SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import", "import Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song", "# assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True)", "mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong", "SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song", "self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser,", "create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"),", "logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def", "= timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths", "autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video file", "error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect", "unittest import TestCase from unittest.mock import patch from path import Path from dakara_feeder.directory", "FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase):", "\"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid video", "subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get song representation", "mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no exception but logs error.\"\"\"", "instance song = BaseSong(Path(\"/base-dir\"), paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as logger:", "paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) #", "paths) # get song representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() #", "autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no exception", "setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths =", "\"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\",", "\"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse,", "raises no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1", "mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong", "logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create", "no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics", "def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no exception but", "@patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises", "exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value", "BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser,", "# setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect =", "from unittest.mock import patch from path import Path from dakara_feeder.directory import SongPaths from", "Path from dakara_feeder.directory import SongPaths from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import", "assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser,", "from dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser,", "[\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self,", "\"\"\"Test an invalid subtitle file raises no exception but logs error.\"\"\" # setup", "autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file", "to zero self.assertEqual(representation[\"duration\"], 0) # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Cannot parse metadata: invalid\"]", "not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse,", "from unittest import TestCase from unittest.mock import patch from path import Path from", "# create BaseSong instance song = BaseSong(Path(\"/base-dir\"), paths) # get song representation with", "= song.get_representation() # check no lyrics has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert", "no exception but logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 )", "mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\"))", "from datetime import timedelta from unittest import TestCase from unittest.mock import patch from", "dakara_feeder.metadata import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError", "been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"]", "as logger: representation = song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"], 0)", "has been found self.assertEqual(representation[\"lyrics\"], \"\") # assert logs self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed:", "= MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) #", "class BaseSongTestCase(TestCase): \"\"\"Test the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def", ") mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"),", "\"\"\"Test an invalid video file raises no exception but logs error.\"\"\" # setup", "but logs error.\"\"\" # setup mocks mocked_metadata_parse.side_effect = MediaParseError(\"invalid\") mocked_subtitle_parse.return_value.get_lyrics.return_value = \"\" #", "representation with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check duration defaults to", "= SubtitleParseError(\"invalid\") # create paths paths = SongPaths(Path(\"file.mp4\"), subtitle=Path(\"file.ass\")) # create BaseSong instance", "logs error.\"\"\" # setup mocks mocked_metadata_parse.return_value.get_duration.return_value = timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1", "with self.assertLogs(\"dakara_feeder.song\") as logger: representation = song.get_representation() # check no lyrics has been", "= song.get_representation() # check duration defaults to zero self.assertEqual(representation[\"duration\"], 0) # assert logs", "timedelta( seconds=1 ) mocked_metadata_parse.return_value.get_audio_tracks_count.return_value = 1 mocked_subtitle_parse.side_effect = SubtitleParseError(\"invalid\") # create paths paths", "\"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle", "mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no exception but logs error.\"\"\" #", "self.assertListEqual( logger.output, [\"ERROR:dakara_feeder.song:Lyrics not parsed: invalid\"] ) @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True)", "from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class BaseSongTestCase(TestCase): \"\"\"Test the", "import FFProbeMetadataParser, MediaParseError from dakara_feeder.song import BaseSong from dakara_feeder.subtitle.parsing import Pysubs2SubtitleParser, SubtitleParseError class", "\"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an invalid subtitle file raises no", ") @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_metadata_error(self, mocked_metadata_parse, mocked_subtitle_parse): \"\"\"Test an", "an invalid video file raises no exception but logs error.\"\"\" # setup mocks", "the BaseSong class.\"\"\" @patch.object(Pysubs2SubtitleParser, \"parse\", autoset=True) @patch.object(FFProbeMetadataParser, \"parse\", autoset=True) def test_subtitle_parser_error(self, mocked_metadata_parse, mocked_subtitle_parse):" ]
[ "net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net = net self.criterion =", "total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader,", "********\\n\" % (epoch + 1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train", "from tqdm import tqdm class Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader,", "t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self):", "labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) #", "torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted == labels).sum() accuracy = 100.", "= self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss", "%5d] loss: %3f' % (epoch + 1, i + 1, running_loss / 2000))", "# 打印训练信息 running_loss += loss.item() # if i % 2000 == 1999: #", "= Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward", "{} finish, loss: {}\\n'.format(epoch + 1, running_loss / (i + 1))) self.save_model(epoch) print('\\nFinish", "在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数 total = 0 # 总共的图片数", "% (epoch + 1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\",", "labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item()", "epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d / %d", "= data inputs, labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) #", "images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1)", "in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data images, labels = images.to(self.device),", "test_loader self.model_path = model_path self.args = args self.best_acc = 0.0 self.device = t.device(\"cuda:1\"", "'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs):", "= scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path = model_path self.args =", "# 梯度清零 self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs) loss = self.criterion(outputs,", "def save_model(self, epoch): accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' %", "Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward +", "desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels =", "print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch + 1, epochs)) running_loss =", "1) # torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted == labels).sum() accuracy", "2000)) # running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss", "tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data images, labels = images.to(self.device), labels.to(self.device)", "desc=\"Eval Iteration\", ncols=70): images, labels = data images, labels = images.to(self.device), labels.to(self.device) outputs", "'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train() #", "t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct =", "将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch", "i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs, labels =", "labels = data images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted", "# 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data", "-* import torch as t from torch.autograd import Variable from tqdm import tqdm", "accuracy = 100. * correct / total return accuracy def save_model(self, epoch): accuracy", "net self.criterion = criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader = train_loader", "= tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据 inputs,", "Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward", "correct = 0 # 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式", "self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward()", "inputs, labels = data inputs, labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device),", "train_loader self.test_loader = test_loader self.model_path = model_path self.args = args self.best_acc = 0.0", "tqdm class Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args):", "打印训练信息 running_loss += loss.item() # if i % 2000 == 1999: # print('[%d,", "finish, loss: {}\\n'.format(epoch + 1, running_loss / (i + 1))) self.save_model(epoch) print('\\nFinish training\\n')", "= self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step()", "%f' % accuracy) print('Saving model...') state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch':", "self.best_acc = accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs):", "model_path self.args = args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and", "(epoch + 1, i + 1, running_loss / 2000)) # running_loss = 0.0", "range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch + 1, epochs)) running_loss", "self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state = { 'net': self.net.state_dict(), 'acc':", "1, running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch", "labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() #", "predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted", "loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() #", "= self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state", "utf-8 -* import torch as t from torch.autograd import Variable from tqdm import", "enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs, labels = Variable(inputs), Variable(labels) inputs,", "epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据", "(predicted == labels).sum() accuracy = 100. * correct / total return accuracy def", "self.criterion = criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader", "梯度清零 self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device)", "data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data images, labels =", "labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward outputs =", "= images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values,", "# 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if", "state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc", "labels = data inputs, labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device)", "# 输入数据 inputs, labels = data inputs, labels = Variable(inputs), Variable(labels) inputs, labels", "print('[%d, %5d] loss: %3f' % (epoch + 1, i + 1, running_loss /", "= net self.criterion = criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader =", "+ 1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for", "model...') state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path)", "# if i % 2000 == 1999: # print('[%d, %5d] loss: %3f' %", "correct / total return accuracy def save_model(self, epoch): accuracy = self._evaluate() if accuracy", "args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数", "= 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval", "data inputs, labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零", "0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) #", "train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d /", "data in enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs, labels = Variable(inputs),", "self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels", "train_loader, test_loader, model_path, args): self.net = net self.criterion = criterion self.optimizer = optimizer", "if accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state = {", "accuracy) print('Saving model...') state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch }", "for i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs, labels", "self.scheduler = scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path = model_path self.args", "loss: %3f' % (epoch + 1, i + 1, running_loss / 2000)) #", "_, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0) correct +=", "criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net = net self.criterion = criterion", "t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted == labels).sum()", "= t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted ==", "% accuracy) print('Saving model...') state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch", "= accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n********", "and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0", "1, i + 1, running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch {}", "images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices)", "* correct / total return accuracy def save_model(self, epoch): accuracy = self._evaluate() if", "> self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state = { 'net': self.net.state_dict(),", "/ %d ********\\n\" % (epoch + 1, epochs)) running_loss = 0.0 epoch_iterator =", "test_loader, model_path, args): self.net = net self.criterion = criterion self.optimizer = optimizer self.scheduler", "def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net = net", "+ 1, i + 1, running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch", "self.args = args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not", "criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader = test_loader", "0 # 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for", "self.model_path = model_path self.args = args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if", "# 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数 total = 0 #", "accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...')", "labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs) loss =", "as t from torch.autograd import Variable from tqdm import tqdm class Trainer(): def", "0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): #", "torch.autograd import Variable from tqdm import tqdm class Trainer(): def __init__(self, net, criterion,", "= test_loader self.model_path = model_path self.args = args self.best_acc = 0.0 self.device =", "self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型", "accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train()", "self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state =", "# 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels =", "images, labels = data images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _,", "<gh_stars>0 # -*- coding: utf-8 -* import torch as t from torch.autograd import", "{ 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy", "+ 1, running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch {} finish, loss:", "self.optimizer = optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path", "accuracy def save_model(self, epoch): accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f'", "self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0) correct", "for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data images, labels", "# 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if i % 2000", "_evaluate(self): correct = 0 # 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() #", "accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving model...') state = { 'net':", "%3f' % (epoch + 1, i + 1, running_loss / 2000)) # running_loss", "tqdm import tqdm class Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader,", "self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy def train(self,", "(epoch + 1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70)", "indices) total += labels.size(0) correct += (predicted == labels).sum() accuracy = 100. *", "loss.item() # if i % 2000 == 1999: # print('[%d, %5d] loss: %3f'", "import torch as t from torch.autograd import Variable from tqdm import tqdm class", "optimizer, scheduler, train_loader, test_loader, model_path, args): self.net = net self.criterion = criterion self.optimizer", "return accuracy def save_model(self, epoch): accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy:", "labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total", "更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if i", "if i % 2000 == 1999: # print('[%d, %5d] loss: %3f' % (epoch", "running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch +", "# 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70):", "/ 2000)) # running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1,", "forward + backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数", "args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else", "self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if i %", "import Variable from tqdm import tqdm class Trainer(): def __init__(self, net, criterion, optimizer,", "+= loss.item() # if i % 2000 == 1999: # print('[%d, %5d] loss:", "= 100. * correct / total return accuracy def save_model(self, epoch): accuracy =", "tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels", "print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data images,", "not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 #", "# torch.max返回值为(values, indices) total += labels.size(0) correct += (predicted == labels).sum() accuracy =", "Iteration\", ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels = data", "Epoch %d / %d ********\\n\" % (epoch + 1, epochs)) running_loss = 0.0", "accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch", "= args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda", "2000 == 1999: # print('[%d, %5d] loss: %3f' % (epoch + 1, i", "self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in", "running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in", "running_loss += loss.item() # if i % 2000 == 1999: # print('[%d, %5d]", "# -*- coding: utf-8 -* import torch as t from torch.autograd import Variable", "ncols=70): images, labels = data images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images))", "optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path = model_path", "+ backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step()", "in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch + 1, epochs))", "% 2000 == 1999: # print('[%d, %5d] loss: %3f' % (epoch + 1,", "= criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader =", "labels.size(0) correct += (predicted == labels).sum() accuracy = 100. * correct / total", "loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息", "%d / %d ********\\n\" % (epoch + 1, epochs)) running_loss = 0.0 epoch_iterator", "class Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net", "} t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for", "= 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss / (i +", "epoch in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch + 1,", "ncols=70) for i, data in enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs,", "更新学习率 self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if i % 2000 ==", "def _evaluate(self): correct = 0 # 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval()", "= self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total += labels.size(0)", "0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\",", "scheduler, train_loader, test_loader, model_path, args): self.net = net self.criterion = criterion self.optimizer =", "self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\")", "= optimizer self.scheduler = scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path =", "= 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device)", "__init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net = net self.criterion", "inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward outputs", "Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path, args): self.net =", "print('Saving model...') state = { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state,", "= inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs)", "%d ********\\n\" % (epoch + 1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader,", "/ total return accuracy def save_model(self, epoch): accuracy = self._evaluate() if accuracy >", "i % 2000 == 1999: # print('[%d, %5d] loss: %3f' % (epoch +", "= t.device(\"cuda:1\" if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def", "outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data, 1) # torch.max返回值为(values, indices) total +=", "t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch", "Variable from tqdm import tqdm class Trainer(): def __init__(self, net, criterion, optimizer, scheduler,", "# print('[%d, %5d] loss: %3f' % (epoch + 1, i + 1, running_loss", "self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() #", "epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data", "labels).sum() accuracy = 100. * correct / total return accuracy def save_model(self, epoch):", "torch as t from torch.autograd import Variable from tqdm import tqdm class Trainer():", "# 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" %", "print('Accuracy: %f' % accuracy) print('Saving model...') state = { 'net': self.net.state_dict(), 'acc': accuracy,", "else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数 total", "'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc = accuracy def", "# running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss /", "model_path, args): self.net = net self.criterion = criterion self.optimizer = optimizer self.scheduler =", "total return accuracy def save_model(self, epoch): accuracy = self._evaluate() if accuracy > self.best_acc:", "Iteration\", ncols=70): images, labels = data images, labels = images.to(self.device), labels.to(self.device) outputs =", "= { 'net': self.net.state_dict(), 'acc': accuracy, 'epoch': epoch } t.save(state, self.model_path) self.best_acc =", "= 0 # 预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...')", "t from torch.autograd import Variable from tqdm import tqdm class Trainer(): def __init__(self,", "+= labels.size(0) correct += (predicted == labels).sum() accuracy = 100. * correct /", "== labels).sum() accuracy = 100. * correct / total return accuracy def save_model(self,", "\"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数 total =", "self.train_loader = train_loader self.test_loader = test_loader self.model_path = model_path self.args = args self.best_acc", "self.test_loader = test_loader self.model_path = model_path self.args = args self.best_acc = 0.0 self.device", "def train(self, epochs): self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d", "self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct = 0 # 预测正确的图片数 total = 0", "= train_loader self.test_loader = test_loader self.model_path = model_path self.args = args self.best_acc =", "1, epochs)) running_loss = 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i,", "in enumerate(epoch_iterator): # 输入数据 inputs, labels = data inputs, labels = Variable(inputs), Variable(labels)", "backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() #", "total += labels.size(0) correct += (predicted == labels).sum() accuracy = 100. * correct", "总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images,", "= 0.0 epoch_iterator = tqdm(self.train_loader, desc=\"Train Iteration\", ncols=70) for i, data in enumerate(epoch_iterator):", "epoch } t.save(state, self.model_path) self.best_acc = accuracy def train(self, epochs): self.net.train() # 将net设置成训练模式", "print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss / (i + 1))) self.save_model(epoch)", "self.net = net self.criterion = criterion self.optimizer = optimizer self.scheduler = scheduler self.train_loader", "+= (predicted == labels).sum() accuracy = 100. * correct / total return accuracy", "self.net.train() # 将net设置成训练模式 for epoch in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\"", "= model_path self.args = args self.best_acc = 0.0 self.device = t.device(\"cuda:1\" if t.cuda.is_available()", "0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss / (i + 1)))", "预测正确的图片数 total = 0 # 总共的图片数 self.net.eval() # 将net设置成eval模式 print('Evaluating...') for data in", "save_model(self, epoch): accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' % accuracy)", "inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad() # forward + backward outputs = self.net(inputs) loss", "self.scheduler.step() # 打印训练信息 running_loss += loss.item() # if i % 2000 == 1999:", "100. * correct / total return accuracy def save_model(self, epoch): accuracy = self._evaluate()", "# forward + backward outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() #", "data images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted = t.max(outputs.data,", "i + 1, running_loss / 2000)) # running_loss = 0.0 print('\\nEpoch {} finish,", "% (epoch + 1, i + 1, running_loss / 2000)) # running_loss =", "scheduler self.train_loader = train_loader self.test_loader = test_loader self.model_path = model_path self.args = args", "running_loss = 0.0 print('\\nEpoch {} finish, loss: {}\\n'.format(epoch + 1, running_loss / (i", "= data images, labels = images.to(self.device), labels.to(self.device) outputs = self.net(Variable(images)) _, predicted =", "1999: # print('[%d, %5d] loss: %3f' % (epoch + 1, i + 1,", "inputs, labels = Variable(inputs), Variable(labels) inputs, labels = inputs.to(self.device), labels.to(self.device) # 梯度清零 self.optimizer.zero_grad()", "correct += (predicted == labels).sum() accuracy = 100. * correct / total return", "输入数据 inputs, labels = data inputs, labels = Variable(inputs), Variable(labels) inputs, labels =", "if t.cuda.is_available() and not args.no_cuda else \"cpu\") self.net.to(self.device) # 在训练集上进行评估以此来确定是否保存模型 def _evaluate(self): correct", "outputs = self.net(inputs) loss = self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率", "import tqdm class Trainer(): def __init__(self, net, criterion, optimizer, scheduler, train_loader, test_loader, model_path,", "args): self.net = net self.criterion = criterion self.optimizer = optimizer self.scheduler = scheduler", "将net设置成eval模式 print('Evaluating...') for data in tqdm(self.test_loader, desc=\"Eval Iteration\", ncols=70): images, labels = data", "epoch): accuracy = self._evaluate() if accuracy > self.best_acc: print('Accuracy: %f' % accuracy) print('Saving", "== 1999: # print('[%d, %5d] loss: %3f' % (epoch + 1, i +", "from torch.autograd import Variable from tqdm import tqdm class Trainer(): def __init__(self, net,", "self.criterion(outputs, labels).to(self.device) loss.backward() # 更新参数 self.optimizer.step() # 更新学习率 self.scheduler.step() # 打印训练信息 running_loss +=", "-*- coding: utf-8 -* import torch as t from torch.autograd import Variable from", "for epoch in range(epochs): print(\"\\n******** Epoch %d / %d ********\\n\" % (epoch +", "coding: utf-8 -* import torch as t from torch.autograd import Variable from tqdm" ]
[ "as block_dao from interfaces.vsan import mon as mon_dao from interfaces.vsan import osd as", "mon_dao from interfaces.vsan import osd as osd_dao from interfaces.vsan import vsan as vsan_dao", "from interfaces.vsan import mon as mon_dao from interfaces.vsan import osd as osd_dao from", "as carrot_dao from interfaces.demo import carrot as corps_dao from interfaces import host as", "from db import init_db from interfaces.demo import rabbit as rabbit_dao from interfaces.demo import", "mon as mon_dao from interfaces.vsan import osd as osd_dao from interfaces.vsan import vsan", "rabbit as rabbit_dao from interfaces.demo import carrot as carrot_dao from interfaces.demo import carrot", "block_dao from interfaces.vsan import mon as mon_dao from interfaces.vsan import osd as osd_dao", "rabbit_dao from interfaces.demo import carrot as carrot_dao from interfaces.demo import carrot as corps_dao", "<filename>ics_demo/dao/__init__.py from db import init_db from interfaces.demo import rabbit as rabbit_dao from interfaces.demo", "as corps_dao from interfaces import host as host_dao from interfaces import blockdevice as", "from interfaces import host as host_dao from interfaces import blockdevice as block_dao from", "interfaces.vsan import mon as mon_dao from interfaces.vsan import osd as osd_dao from interfaces.vsan", "corps_dao from interfaces import host as host_dao from interfaces import blockdevice as block_dao", "as rabbit_dao from interfaces.demo import carrot as carrot_dao from interfaces.demo import carrot as", "as host_dao from interfaces import blockdevice as block_dao from interfaces.vsan import mon as", "host_dao from interfaces import blockdevice as block_dao from interfaces.vsan import mon as mon_dao", "interfaces import host as host_dao from interfaces import blockdevice as block_dao from interfaces.vsan", "import blockdevice as block_dao from interfaces.vsan import mon as mon_dao from interfaces.vsan import", "carrot as carrot_dao from interfaces.demo import carrot as corps_dao from interfaces import host", "interfaces.demo import carrot as corps_dao from interfaces import host as host_dao from interfaces", "from interfaces.demo import rabbit as rabbit_dao from interfaces.demo import carrot as carrot_dao from", "carrot as corps_dao from interfaces import host as host_dao from interfaces import blockdevice", "interfaces.demo import carrot as carrot_dao from interfaces.demo import carrot as corps_dao from interfaces", "import init_db from interfaces.demo import rabbit as rabbit_dao from interfaces.demo import carrot as", "from interfaces.demo import carrot as carrot_dao from interfaces.demo import carrot as corps_dao from", "carrot_dao from interfaces.demo import carrot as corps_dao from interfaces import host as host_dao", "import carrot as carrot_dao from interfaces.demo import carrot as corps_dao from interfaces import", "import carrot as corps_dao from interfaces import host as host_dao from interfaces import", "interfaces import blockdevice as block_dao from interfaces.vsan import mon as mon_dao from interfaces.vsan", "as mon_dao from interfaces.vsan import osd as osd_dao from interfaces.vsan import vsan as", "init_db from interfaces.demo import rabbit as rabbit_dao from interfaces.demo import carrot as carrot_dao", "host as host_dao from interfaces import blockdevice as block_dao from interfaces.vsan import mon", "interfaces.demo import rabbit as rabbit_dao from interfaces.demo import carrot as carrot_dao from interfaces.demo", "db import init_db from interfaces.demo import rabbit as rabbit_dao from interfaces.demo import carrot", "import host as host_dao from interfaces import blockdevice as block_dao from interfaces.vsan import", "from interfaces import blockdevice as block_dao from interfaces.vsan import mon as mon_dao from", "from interfaces.demo import carrot as corps_dao from interfaces import host as host_dao from", "import mon as mon_dao from interfaces.vsan import osd as osd_dao from interfaces.vsan import", "blockdevice as block_dao from interfaces.vsan import mon as mon_dao from interfaces.vsan import osd", "import rabbit as rabbit_dao from interfaces.demo import carrot as carrot_dao from interfaces.demo import" ]
[ "close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int:", "stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int)", "import REDIS_PREFIX from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex:", "int: key = MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if val is", "client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key)", "+ str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key = MEETING_KEY", "= { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key", "{ 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key =", "= MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key", "client.hget(key, 'sharing_user') if val is None: return -1 return int(val) def start_share(meeting_id: int,", "<reponame>ttppren-github/MeetingSample-Backend from meeting_sample.settings import REDIS_PREFIX from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def", "= client.hget(key, 'sharing_user') if val is None: return -1 return int(val) def start_share(meeting_id:", "+ str(meeting_id) value = { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def", "= MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if val is None: return", "return -1 return int(val) def start_share(meeting_id: int, user_id: int): key = MEETING_KEY +", "client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user',", "str(meeting_id) value = { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id:", "def start_share(meeting_id: int, user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id)", "int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key", "int(val) def start_share(meeting_id: int, user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user',", "client.delete(key) def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY + str(meeting_id) val =", "return int(val) def start_share(meeting_id: int, user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key,", "str(meeting_id) val = client.hget(key, 'sharing_user') if val is None: return -1 return int(val)", "-1 return int(val) def start_share(meeting_id: int, user_id: int): key = MEETING_KEY + str(meeting_id)", "open_meeting(meeting_id: int, ex: int): key = MEETING_KEY + str(meeting_id) value = { 'sharing_user':", "client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key = MEETING_KEY + str(meeting_id)", "'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key = MEETING_KEY + str(meeting_id) return", "utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key =", "REDIS_PREFIX from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int):", "0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY +", "client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id:", "0) def is_meeting_open(meeting_id: int) -> bool: key = MEETING_KEY + str(meeting_id) return bool(client.exists(key))", "def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY + str(meeting_id) val = client.hget(key,", "None: return -1 return int(val) def start_share(meeting_id: int, user_id: int): key = MEETING_KEY", "'sharing_user') if val is None: return -1 return int(val) def start_share(meeting_id: int, user_id:", "MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY +", "int): key = MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0, } client.hset(key,", "from meeting_sample.settings import REDIS_PREFIX from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id:", "key = MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0, } client.hset(key, mapping=value)", "key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key =", "f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY + str(meeting_id) value =", "MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex)", "str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key,", "from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key", "import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY", "user_id) def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def", "MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY + str(meeting_id)", "= MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key,", "+ str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY + str(meeting_id)", "+ str(meeting_id) val = client.hget(key, 'sharing_user') if val is None: return -1 return", "val is None: return -1 return int(val) def start_share(meeting_id: int, user_id: int): key", "ex: int): key = MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0, }", "ex) def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int)", "def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) ->", "meeting_sample.settings import REDIS_PREFIX from utils.cache.connection import client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int,", "int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) ->", "def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY + str(meeting_id) value = {", "value = { 'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int):", "'sharing_user': 0, } client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY", "= MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY", "str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY + str(meeting_id) val", "int): key = MEETING_KEY + str(meeting_id) client.delete(key) def get_sharing_user(meeting_id: int) -> int: key", "client MEETING_KEY = f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY +", "int) -> int: key = MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if", "= f'{REDIS_PREFIX}:meeting:' def open_meeting(meeting_id: int, ex: int): key = MEETING_KEY + str(meeting_id) value", "user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int):", "MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key =", "get_sharing_user(meeting_id: int) -> int: key = MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user')", "int, user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id:", "key = MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if val is None:", "val = client.hget(key, 'sharing_user') if val is None: return -1 return int(val) def", "def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id:", "= MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY", "int, ex: int): key = MEETING_KEY + str(meeting_id) value = { 'sharing_user': 0,", "+ str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id)", "MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if val is None: return -1", "-> int: key = MEETING_KEY + str(meeting_id) val = client.hget(key, 'sharing_user') if val", "key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key =", "str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool: key = MEETING_KEY +", "start_share(meeting_id: int, user_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def", "is None: return -1 return int(val) def start_share(meeting_id: int, user_id: int): key =", "MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY +", "} client.hset(key, mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id)", "mapping=value) client.expire(key, ex) def close_meeting(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.delete(key) def", "key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0) def is_meeting_open(meeting_id: int) -> bool:", "if val is None: return -1 return int(val) def start_share(meeting_id: int, user_id: int):", "'sharing_user', user_id) def stop_share(meeting_id: int): key = MEETING_KEY + str(meeting_id) client.hset(key, 'sharing_user', 0)" ]
[ "should really put in a title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input", "[] y = [] with open(fname, 'r') as f: for line in f:", "put in a title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o',", "help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x", "plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot if outFile != None: plt.savefig(outFile)", "info from each input file xs = [] ys = [] for fname", "+ .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y -", "x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots = [] min_x = min(xs[0])", "[] for fname in inFiles: x = [] y = [] with open(fname,", "default = 'You should really put in a title and label axes!' parser.add_argument('-i',", "max(xs[0]) max_y = max(ys[0]) for x, y in zip(xs, ys): min_x = min(min_x,", "min(min_x, min(x)) min_y = min(min_y, min(y)) max_x = max(max_x, max(x)) max_y = max(max_y,", "= max(max_x, max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) #", ".05*(max_y - min_y))) # Set specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title)", "args.output title = args.title xlabel = args.xlabel ylabel = args.ylabel # Extract info", "- min_y))) # Set specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel)", "argparse.ArgumentParser() default = 'You should really put in a title and label axes!'", "args.title xlabel = args.xlabel ylabel = args.ylabel # Extract info from each input", "+ .05*(max_y - min_y))) # Set specified title/axes labels & legend plt.legend(plots, inFiles)", "- .05*(max_y - min_y), max_y + .05*(max_y - min_y))) # Set specified title/axes", "'--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel',", "in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots", "title = args.title xlabel = args.xlabel ylabel = args.ylabel # Extract info from", "= min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for x,", "plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y", "= min(min_y, min(y)) max_x = max(max_x, max(x)) max_y = max(max_y, max(y)) plot, =", "= 'You should really put in a title and label axes!' parser.add_argument('-i', '--input',", "= args.ylabel # Extract info from each input file xs = [] ys", ".05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y - min_y)))", "= parser.parse_args() inFiles = args.input outFile = args.output title = args.title xlabel =", "Set specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either", "x = [] y = [] with open(fname, 'r') as f: for line", "= line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots = [] min_x", "ys = [] for fname in inFiles: x = [] y = []", "#!/usr/bin/python import argparse import matplotlib.pyplot as plt # Specify cmdline args parser =", "for x, y in zip(xs, ys): min_x = min(min_x, min(x)) min_y = min(min_y,", "parser.parse_args() inFiles = args.input outFile = args.output title = args.title xlabel = args.xlabel", "args.xlabel ylabel = args.ylabel # Extract info from each input file xs =", "y) plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x +", "for line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate", "- min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y - min_y))) #", "parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y", "xs.append(x) ys.append(y) # Generate plots plots = [] min_x = min(xs[0]) min_y =", "default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') #", "file xs = [] ys = [] for fname in inFiles: x =", "zip(xs, ys): min_x = min(min_x, min(x)) min_y = min(min_y, min(y)) max_x = max(max_x,", "specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save", "min_y), max_y + .05*(max_y - min_y))) # Set specified title/axes labels & legend", "min_x = min(min_x, min(x)) min_y = min(min_y, min(y)) max_x = max(max_x, max(x)) max_y", ".05*(max_y - min_y), max_y + .05*(max_y - min_y))) # Set specified title/axes labels", "legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot if", "= [] with open(fname, 'r') as f: for line in f: data =", "# Either save or show plot if outFile != None: plt.savefig(outFile) else: plt.show()", "= argparse.ArgumentParser() default = 'You should really put in a title and label", "[] min_x = min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0])", "max(max_x, max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) # Set", "plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x", "= plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x - min_x),", "min(x)) min_y = min(min_y, min(y)) max_x = max(max_x, max(x)) max_y = max(max_y, max(y))", "argparse import matplotlib.pyplot as plt # Specify cmdline args parser = argparse.ArgumentParser() default", "min_x = min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for", "in zip(xs, ys): min_x = min(min_x, min(x)) min_y = min(min_y, min(y)) max_x =", "plots = [] min_x = min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y", "parser = argparse.ArgumentParser() default = 'You should really put in a title and", "with open(fname, 'r') as f: for line in f: data = line.strip().split(',') x.append(float(data[0]))", "max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) # Set 5%", "for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') # Parse arguments", "f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots =", "args.ylabel # Extract info from each input file xs = [] ys =", "= args.output title = args.title xlabel = args.xlabel ylabel = args.ylabel # Extract", "line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots = [] min_x =", "= min(min_x, min(x)) min_y = min(min_y, min(y)) max_x = max(max_x, max(x)) max_y =", "'--ylabel', default=default, help='Label for y axis') # Parse arguments args = parser.parse_args() inFiles", "fname in inFiles: x = [] y = [] with open(fname, 'r') as", "Set 5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x - min_x)))", "y = [] with open(fname, 'r') as f: for line in f: data", "plt.ylabel(ylabel) # Either save or show plot if outFile != None: plt.savefig(outFile) else:", "for fname in inFiles: x = [] y = [] with open(fname, 'r')", "Extract info from each input file xs = [] ys = [] for", "open(fname, 'r') as f: for line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1]))", "min_y))) # Set specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel)", "= args.input outFile = args.output title = args.title xlabel = args.xlabel ylabel =", "ys): min_x = min(min_x, min(x)) min_y = min(min_y, min(y)) max_x = max(max_x, max(x))", "x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') # Parse arguments args", "<filename>user/plot.py #!/usr/bin/python import argparse import matplotlib.pyplot as plt # Specify cmdline args parser", "min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y +", "= [] for fname in inFiles: x = [] y = [] with", "# Extract info from each input file xs = [] ys = []", "= args.xlabel ylabel = args.ylabel # Extract info from each input file xs", "'--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title')", "'r') as f: for line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x)", "Parse arguments args = parser.parse_args() inFiles = args.input outFile = args.output title =", "title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for", "max_y = max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) # Set 5% margin", "y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots = [] min_x = min(xs[0]) min_y", "max(y)) plot, = plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x", "each input file xs = [] ys = [] for fname in inFiles:", "- .05*(max_x - min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y -", "y axis') # Parse arguments args = parser.parse_args() inFiles = args.input outFile =", "outFile = args.output title = args.title xlabel = args.xlabel ylabel = args.ylabel #", "'--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for", "max_x = max(xs[0]) max_y = max(ys[0]) for x, y in zip(xs, ys): min_x", "[] ys = [] for fname in inFiles: x = [] y =", "Generate plots plots = [] min_x = min(xs[0]) min_y = min(ys[0]) max_x =", "# Set 5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x -", "min_y = min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for x, y in", "- min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y", "plots plots = [] min_x = min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0])", "as f: for line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y)", "& legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot", "axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default,", "import argparse import matplotlib.pyplot as plt # Specify cmdline args parser = argparse.ArgumentParser()", "# Specify cmdline args parser = argparse.ArgumentParser() default = 'You should really put", "nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x',", "inFiles: x = [] y = [] with open(fname, 'r') as f: for", "plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x", "max_x = max(max_x, max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot)", "help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') # Parse", "min(y)) max_x = max(max_x, max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x, y)", "= [] y = [] with open(fname, 'r') as f: for line in", "args = parser.parse_args() inFiles = args.input outFile = args.output title = args.title xlabel", "import matplotlib.pyplot as plt # Specify cmdline args parser = argparse.ArgumentParser() default =", "arguments args = parser.parse_args() inFiles = args.input outFile = args.output title = args.title", "axis') # Parse arguments args = parser.parse_args() inFiles = args.input outFile = args.output", "min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y - min_y))) # Set", "plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot if outFile", "title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or", "x, y in zip(xs, ys): min_x = min(min_x, min(x)) min_y = min(min_y, min(y))", "5% margin plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y", "plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot if outFile != None:", "parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y',", "f: for line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) #", "help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label", "= [] min_x = min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y =", "args parser = argparse.ArgumentParser() default = 'You should really put in a title", "min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for x, y in zip(xs, ys):", "= args.title xlabel = args.xlabel ylabel = args.ylabel # Extract info from each", "max_y + .05*(max_y - min_y))) # Set specified title/axes labels & legend plt.legend(plots,", "default=default, help='Label for y axis') # Parse arguments args = parser.parse_args() inFiles =", "= max(ys[0]) for x, y in zip(xs, ys): min_x = min(min_x, min(x)) min_y", "label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title',", "max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x -", "inFiles = args.input outFile = args.output title = args.title xlabel = args.xlabel ylabel", "- min_y), max_y + .05*(max_y - min_y))) # Set specified title/axes labels &", "Specify cmdline args parser = argparse.ArgumentParser() default = 'You should really put in", "a title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output", "in a title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output',", "y in zip(xs, ys): min_x = min(min_x, min(x)) min_y = min(min_y, min(y)) max_x", "default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default,", "help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel',", "# Generate plots plots = [] min_x = min(xs[0]) min_y = min(ys[0]) max_x", "min(xs[0]) min_y = min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for x, y", "'--xlabel', default=default, help='Label for x axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis')", "margin plt.xlim((min_x - .05*(max_x - min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y -", "# Parse arguments args = parser.parse_args() inFiles = args.input outFile = args.output title", "data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots plots = []", "as plt # Specify cmdline args parser = argparse.ArgumentParser() default = 'You should", "help='Label for y axis') # Parse arguments args = parser.parse_args() inFiles = args.input", "and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t',", "ylabel = args.ylabel # Extract info from each input file xs = []", "in inFiles: x = [] y = [] with open(fname, 'r') as f:", "matplotlib.pyplot as plt # Specify cmdline args parser = argparse.ArgumentParser() default = 'You", "parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label", "really put in a title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)')", "max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y", "axis') parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') # Parse arguments args =", "xlabel = args.xlabel ylabel = args.ylabel # Extract info from each input file", "= min(ys[0]) max_x = max(xs[0]) max_y = max(ys[0]) for x, y in zip(xs,", "min(min_y, min(y)) max_x = max(max_x, max(x)) max_y = max(max_y, max(y)) plot, = plt.step(x,", "= max(max_y, max(y)) plot, = plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x", "max_y = max(ys[0]) for x, y in zip(xs, ys): min_x = min(min_x, min(x))", "plot, = plt.step(x, y) plots.append(plot) # Set 5% margin plt.xlim((min_x - .05*(max_x -", "parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot", "File(s)') parser.add_argument('-o', '--output', help='Output File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default,", "cmdline args parser = argparse.ArgumentParser() default = 'You should really put in a", "inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show plot if outFile !=", "= max(xs[0]) max_y = max(ys[0]) for x, y in zip(xs, ys): min_x =", "input file xs = [] ys = [] for fname in inFiles: x", "# Set specified title/axes labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) #", "ys.append(y) # Generate plots plots = [] min_x = min(xs[0]) min_y = min(ys[0])", "for y axis') # Parse arguments args = parser.parse_args() inFiles = args.input outFile", "args.input outFile = args.output title = args.title xlabel = args.xlabel ylabel = args.ylabel", "[] with open(fname, 'r') as f: for line in f: data = line.strip().split(',')", "title and label axes!' parser.add_argument('-i', '--input', nargs='+', help='Input File(s)') parser.add_argument('-o', '--output', help='Output File')", "plt.ylim((min_y - .05*(max_y - min_y), max_y + .05*(max_y - min_y))) # Set specified", "labels & legend plt.legend(plots, inFiles) plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) # Either save or show", "max(ys[0]) for x, y in zip(xs, ys): min_x = min(min_x, min(x)) min_y =", "line in f: data = line.strip().split(',') x.append(float(data[0])) y.append(float(data[1])) xs.append(x) ys.append(y) # Generate plots", "min_y = min(min_y, min(y)) max_x = max(max_x, max(x)) max_y = max(max_y, max(y)) plot,", "plt # Specify cmdline args parser = argparse.ArgumentParser() default = 'You should really", "File') parser.add_argument('-t', '--title', default=default, help='Plot title') parser.add_argument('-x', '--xlabel', default=default, help='Label for x axis')", "xs = [] ys = [] for fname in inFiles: x = []", "= [] ys = [] for fname in inFiles: x = [] y", ".05*(max_x - min_x), max_x + .05*(max_x - min_x))) plt.ylim((min_y - .05*(max_y - min_y),", "'You should really put in a title and label axes!' parser.add_argument('-i', '--input', nargs='+',", "from each input file xs = [] ys = [] for fname in", "parser.add_argument('-y', '--ylabel', default=default, help='Label for y axis') # Parse arguments args = parser.parse_args()" ]
[]
[ "fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar()", "carro import Carro fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar()", "# fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() #", "# fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() #", "fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear()", "fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar()", "# fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\") tesla = Carro(\"Tesla\",\"Cybertruck\",\"cinza\",\"Eletrico\")", "Carro fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar()", "fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear()", "# fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() #", "<filename>Aula14/app.py from carro import Carro fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar()", "from carro import Carro fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() #", "Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() #", "fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear()", "fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\") tesla = Carro(\"Tesla\",\"Cybertruck\",\"cinza\",\"Eletrico\") ferrari.ligar()", "fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\")", "# fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari", "fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari =", "fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear()", "# fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() #", "# fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() #", "# fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() #", "fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear()", "# fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari", "= Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar()", "fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() # fusca.frear() # fusca.frear()", "fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() #", "# fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear() #", "# fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\") tesla", "fusca.frear() # fusca.frear() # fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\") tesla =", "fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar()", "# fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() # fusca.frear() #", "import Carro fusca = Carro(\"Volks\",\"Fusca\",\"Azul\",\"Gasolina\") fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() #", "fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.frear()", "# fusca.frear() # fusca.desligar() ferrari = Carro(\"Ferrari\",\"Ferrari 911\",\"Vermelho\",\"Gasolina\") tesla = Carro(\"Tesla\",\"Cybertruck\",\"cinza\",\"Eletrico\") ferrari.ligar() tesla.ligar()", "fusca.ligar() # fusca.ligar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar() # fusca.acelerar()" ]
[ "os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner", "to skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune", "parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class", "fine-tune ONLY the linear classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] =", "best_acc = runner.train(model) # parameters are in args # Validate again logging.info(\"==> Validating", "= True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def validate_args(self, args):", "state_dict_[key_] = val if \"fc\" in key_: del state_dict_[key_] return state_dict_ return update_state_dict", "import torchvision.datasets as datasets from gumi import model_utils from gumi.ops import * from", "\"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args)", "import copy import time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy", "as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import", "os import sys import argparse import copy import time import shutil import json", "def update_state_dict(state_dict): \"\"\" Here are several update rules: - In this new script,", ") args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark", "main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner =", "Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) #", "# Validate logging.info(\"==> Validating the loaded model ...\") loss1, acc1 = runner.validate(model) #", "= copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ = key if \"module\" in", "model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the", "any '.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in", "= val if \"fc\" in key_: del state_dict_[key_] return state_dict_ return update_state_dict def", "\"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if", "state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing", "...\") runner = TransferRunner(args) # load model logging.info(\"==> Loading model ...\") model =", "def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update rules: - In this", "state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\" # initialise runner", "new script, we won't have \"module.\" prefix - There won't be any '.conv2d'", "update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded model ...\") loss1, acc1", "optim import torch.utils.data as data import torchvision.transforms as transforms import torchvision.datasets as datasets", "datasets from gumi import model_utils from gumi.ops import * from gumi.pruning.export import GroupExporter", "update rules: - In this new script, we won't have \"module.\" prefix -", "\"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\", ) args =", "scratch with different conditions. \"\"\" import os import sys import argparse import copy", "json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import torch.nn as", "In this new script, we won't have \"module.\" prefix - There won't be", "create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training", "import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as", "for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training step.\", )", "from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser parser =", "parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training step.\", ) parser.add_argument( \"--fine-tune\",", "runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded model ...\") loss1,", "state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ = key if \"module\"", "key, val in state_dict.items(): key_ = key if \"module\" in key_: del state_dict_[key_]", "this new script, we won't have \"module.\" prefix - There won't be any", "conditions. \"\"\" import os import sys import argparse import copy import time import", "transforms import torchvision.datasets as datasets from gumi import model_utils from gumi.ops import *", "are several update rules: - In this new script, we won't have \"module.\"", "runner = TransferRunner(args) # load model logging.info(\"==> Loading model ...\") model = runner.load_model(", "torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim", "Train if args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run training ...\")", "for transfer learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\"", "from gumi.ops import * from gumi.pruning.export import GroupExporter from gumi.model_runner import utils from", "be any '.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val", "# initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) # load model", "parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\", ) args", "logging.info(\"==> Validating the loaded model ...\") loss1, acc1 = runner.validate(model) # Train if", "import numpy as np import torch import torch.nn as nn import torch.nn.parallel import", "torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def", "model logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate", "def main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner", "from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser #", "\"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\",", "from scratch with different conditions. \"\"\" import os import sys import argparse import", "time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import", "\"module.\" prefix - There won't be any '.conv2d' in the module \"\"\" state_dict_", "import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import", "create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\",", "pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training step.\", ) parser.add_argument(", "transfer learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here", "- In this new script, we won't have \"module.\" prefix - There won't", "we won't have \"module.\" prefix - There won't be any '.conv2d' in the", "del state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\" # initialise", "data import torchvision.transforms as transforms import torchvision.datasets as datasets from gumi import model_utils", "the trained model ...\") loss2, acc2 = runner.validate(model) if __name__ == \"__main__\": main()", "Runner for transfer learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict):", "* from gumi.pruning.export import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner", "different conditions. \"\"\" import os import sys import argparse import copy import time", "skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY", "return update_state_dict def main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner", "cudnn import torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms", "the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the", "torchvision.transforms as transforms import torchvision.datasets as datasets from gumi import model_utils from gumi.ops", "copy import time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as", "torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data as data", "logging.info(\"==> Validating the trained model ...\") loss2, acc2 = runner.validate(model) if __name__ ==", "\"\"\" import os import sys import argparse import copy import time import shutil", "logging.info(\"==> Run training ...\") best_acc = runner.train(model) # parameters are in args #", "Here are several update rules: - In this new script, we won't have", "update_state_dict def main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\")", "help=\"Whether to skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to", "create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update rules: - In this new", "key_: del state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\" #", "help=\"Whether to fine-tune ONLY the linear classifiers.\", ) args = parser.parse_args() # CUDA", "update_state_dict(state_dict): \"\"\" Here are several update rules: - In this new script, we", "\"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ = key if", "key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in key_: del state_dict_[key_] return state_dict_", "utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser parser", "'.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items():", "\"\"\" Training from scratch with different conditions. \"\"\" import os import sys import", "nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data", "import model_utils from gumi.ops import * from gumi.pruning.export import GroupExporter from gumi.model_runner import", "val in state_dict.items(): key_ = key if \"module\" in key_: del state_dict_[key_] key_", "\"\") state_dict_[key_] = val if \"fc\" in key_: del state_dict_[key_] return state_dict_ return", "argparse import copy import time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import", "return state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\" # initialise runner logging.info(\"==>", "runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run", "logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import torch.nn as nn import", "# CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False,", "gumi.ops import * from gumi.pruning.export import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner", "gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI", "for key, val in state_dict.items(): key_ = key if \"module\" in key_: del", "key if \"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] =", "model_utils from gumi.ops import * from gumi.pruning.export import GroupExporter from gumi.model_runner import utils", "gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI", "linear classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda =", "cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def validate_args(self,", "# load model logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune )", "Validate logging.info(\"==> Validating the loaded model ...\") loss1, acc1 = runner.validate(model) # Train", "GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser", "= runner.train(model) # parameters are in args # Validate again logging.info(\"==> Validating the", "in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\"", "= parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True", "are in args # Validate again logging.info(\"==> Validating the trained model ...\") loss2,", "initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) # load model logging.info(\"==>", "load model logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) #", "model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded model", "import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data as data import", "import torch.utils.data as data import torchvision.transforms as transforms import torchvision.datasets as datasets from", "...\") best_acc = runner.train(model) # parameters are in args # Validate again logging.info(\"==>", "won't have \"module.\" prefix - There won't be any '.conv2d' in the module", "torchvision.datasets as datasets from gumi import model_utils from gumi.ops import * from gumi.pruning.export", "TransferRunner ...\") runner = TransferRunner(args) # load model logging.info(\"==> Loading model ...\") model", "parameters are in args # Validate again logging.info(\"==> Validating the trained model ...\")", "import os import sys import argparse import copy import time import shutil import", "torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim", "# CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner):", "args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark =", "else: logging.info(\"==> Run training ...\") best_acc = runner.train(model) # parameters are in args", ") parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\", )", "import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import torch.nn", "logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import torch.nn as nn import torch.nn.parallel", "as data import torchvision.transforms as transforms import torchvision.datasets as datasets from gumi import", "Validate again logging.info(\"==> Validating the trained model ...\") loss2, acc2 = runner.validate(model) if", "del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in key_:", "key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in key_: del state_dict_[key_]", "model ...\") loss1, acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has", "as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as", "args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update rules: -", "step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\",", "val if \"fc\" in key_: del state_dict_[key_] return state_dict_ return update_state_dict def main():", "been skipped.\") else: logging.info(\"==> Run training ...\") best_acc = runner.train(model) # parameters are", "TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn():", "action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\", ) args = parser.parse_args()", "script, we won't have \"module.\" prefix - There won't be any '.conv2d' in", "# Validate again logging.info(\"==> Validating the trained model ...\") loss2, acc2 = runner.validate(model)", "default=False, help=\"Whether to fine-tune ONLY the linear classifiers.\", ) args = parser.parse_args() #", "in args # Validate again logging.info(\"==> Validating the trained model ...\") loss2, acc2", "to fine-tune ONLY the linear classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"]", "CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether", "parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip", "= runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded model ...\")", "= key if \"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_]", "pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update rules: - In", "import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import torch.nn as nn", "gumi.model_runner.parser import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument(", "sys import argparse import copy import time import shutil import json import logging", "again logging.info(\"==> Validating the trained model ...\") loss2, acc2 = runner.validate(model) if __name__", "gumi.pruning.export import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser", "# Train if args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run training", "import argparse import copy import time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG)", "rules: - In this new script, we won't have \"module.\" prefix - There", "training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether to fine-tune ONLY the linear", "= torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\"", "Run training ...\") best_acc = runner.train(model) # parameters are in args # Validate", "= key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in key_: del state_dict_[key_] return", "np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn", "import * from gumi.pruning.export import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import", "the linear classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda", "learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are", "= TransferRunner(args) # load model logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(),", "if args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run training ...\") best_acc", "# parameters are in args # Validate again logging.info(\"==> Validating the trained model", "= args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for", "as transforms import torchvision.datasets as datasets from gumi import model_utils from gumi.ops import", "as datasets from gumi import model_utils from gumi.ops import * from gumi.pruning.export import", "from gumi.model_runner.parser import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\")", "import torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms import", "state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in key_: del", "key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val if \"fc\" in", "- There won't be any '.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict)", "action=\"store_true\", default=False, help=\"Whether to skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False,", "the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ =", "gumi import model_utils from gumi.ops import * from gumi.pruning.export import GroupExporter from gumi.model_runner", "args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for transfer", "parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to", "module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ = key", "loaded model ...\") loss1, acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training", "import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch", "= runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==>", "import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool", "args.skip_train: logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run training ...\") best_acc =", "prefix - There won't be any '.conv2d' in the module \"\"\" state_dict_ =", "shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np import torch import", "skipped.\") else: logging.info(\"==> Run training ...\") best_acc = runner.train(model) # parameters are in", "numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn", "TransferRunner(args) # load model logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune", "default=False, help=\"Whether to skip the training step.\", ) parser.add_argument( \"--fine-tune\", action=\"store_true\", default=False, help=\"Whether", "several update rules: - In this new script, we won't have \"module.\" prefix", "state_dict.items(): key_ = key if \"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\",", "as cudnn import torch.optim as optim import torch.utils.data as data import torchvision.transforms as", "import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\",", "\"\"\" # initialise runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) # load", "ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser parser = create_cli_parser(prog=\"CLI tool for", "in key_: del state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\" Main \"\"\"", "tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the training step.\",", "fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded model ...\") loss1, acc1 =", "from gumi.pruning.export import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from", "import torchvision.transforms as transforms import torchvision.datasets as datasets from gumi import model_utils from", "Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating", ") # Validate logging.info(\"==> Validating the loaded model ...\") loss1, acc1 = runner.validate(model)", "import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data as", "has been skipped.\") else: logging.info(\"==> Run training ...\") best_acc = runner.train(model) # parameters", "torch.optim as optim import torch.utils.data as data import torchvision.transforms as transforms import torchvision.datasets", "runner.train(model) # parameters are in args # Validate again logging.info(\"==> Validating the trained", "with different conditions. \"\"\" import os import sys import argparse import copy import", "if \"fc\" in key_: del state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\"", "import sys import argparse import copy import time import shutil import json import", "runner logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) # load model logging.info(\"==> Loading", "class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def validate_args(self, args): pass def", "as optim import torch.utils.data as data import torchvision.transforms as transforms import torchvision.datasets as", "validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update rules:", "\"\"\" Here are several update rules: - In this new script, we won't", "...\") loss1, acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has been", "key_ = key if \"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\")", "have \"module.\" prefix - There won't be any '.conv2d' in the module \"\"\"", "copy.deepcopy(state_dict) for key, val in state_dict.items(): key_ = key if \"module\" in key_:", "args # Validate again logging.info(\"==> Validating the trained model ...\") loss2, acc2 =", "loss1, acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has been skipped.\")", "CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\"", "Training has been skipped.\") else: logging.info(\"==> Run training ...\") best_acc = runner.train(model) #", "import GroupExporter from gumi.model_runner import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import", "logging.info(\"==> Loading model ...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==>", "def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several update", "if \"module\" in key_: del state_dict_[key_] key_ = key_.replace(\"module.\", \"\") state_dict_[key_] = val", "Validating the loaded model ...\") loss1, acc1 = runner.validate(model) # Train if args.skip_train:", "= create_cli_parser(prog=\"CLI tool for pruning\") parser.add_argument( \"--skip-train\", action=\"store_true\", default=False, help=\"Whether to skip the", "the loaded model ...\") loss1, acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==>", "True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning. \"\"\" def validate_args(self, args): pass", "Validating the trained model ...\") loss2, acc2 = runner.validate(model) if __name__ == \"__main__\":", "won't be any '.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key,", "in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for key, val in state_dict.items(): key_", "acc1 = runner.validate(model) # Train if args.skip_train: logging.info(\"==> Training has been skipped.\") else:", "...\") model = runner.load_model( update_state_dict_fn=create_update_state_dict_fn(), fine_tune=args.fine_tune ) # Validate logging.info(\"==> Validating the loaded", "torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data as data import torchvision.transforms", "There won't be any '.conv2d' in the module \"\"\" state_dict_ = copy.deepcopy(state_dict) for", "\"fc\" in key_: del state_dict_[key_] return state_dict_ return update_state_dict def main(): \"\"\" Main", "use_cuda = torch.cuda.is_available() cudnn.benchmark = True class TransferRunner(ModelRunner): \"\"\" Runner for transfer learning.", "classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id use_cuda = torch.cuda.is_available()", "in state_dict.items(): key_ = key if \"module\" in key_: del state_dict_[key_] key_ =", "Initializing TransferRunner ...\") runner = TransferRunner(args) # load model logging.info(\"==> Loading model ...\")", "import utils from gumi.model_runner.model_runner import ModelRunner from gumi.model_runner.parser import create_cli_parser # CLI parser", "from gumi import model_utils from gumi.ops import * from gumi.pruning.export import GroupExporter from", "Training from scratch with different conditions. \"\"\" import os import sys import argparse", "logging.info(\"==> Training has been skipped.\") else: logging.info(\"==> Run training ...\") best_acc = runner.train(model)", "logging.info(\"==> Initializing TransferRunner ...\") runner = TransferRunner(args) # load model logging.info(\"==> Loading model", "\"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def update_state_dict(state_dict): \"\"\" Here are several", "import time import shutil import json import logging logging.getLogger().setLevel(logging.DEBUG) import numpy as np", "torch.utils.data as data import torchvision.transforms as transforms import torchvision.datasets as datasets from gumi", "\"\"\" Runner for transfer learning. \"\"\" def validate_args(self, args): pass def create_update_state_dict_fn(): def", "ONLY the linear classifiers.\", ) args = parser.parse_args() # CUDA os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_id", "training ...\") best_acc = runner.train(model) # parameters are in args # Validate again" ]
[ "from django.db import models class User(models.Model): pass class Car(models.Model): pass class Parking(models.Model): pass" ]
[ "we are running in a git repo, look up the hash __version__ =", "__version__ except: # otherwise check for a version file try: from . version", "are running in a git repo, look up the hash __version__ = subprocess.Popen(", "__version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for", "stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for a version file try:", "('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for a version file", "import subprocess, os __version__ = '' try: # if we are running in", "check for a version file try: from . version import version as __version__", "except: # otherwise check for a version file try: from . version import", "assert __version__ except: # otherwise check for a version file try: from .", "if we are running in a git repo, look up the hash __version__", "os __version__ = '' try: # if we are running in a git", "__version__ = '' try: # if we are running in a git repo,", "'' try: # if we are running in a git repo, look up", "the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise", "subprocess, os __version__ = '' try: # if we are running in a", "<reponame>bengranett/datam import subprocess, os __version__ = '' try: # if we are running", "subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for a version", "# otherwise check for a version file try: from . version import version", "stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for a version file try: from", "repo, look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__", "look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except:", "a git repo, look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]", "try: # if we are running in a git repo, look up the", "git repo, look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert", "running in a git repo, look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'),", "up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: #", "= subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check for a", "= '' try: # if we are running in a git repo, look", "in a git repo, look up the hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE,", "# if we are running in a git repo, look up the hash", "hash __version__ = subprocess.Popen( ('git','--git-dir',os.path.dirname(__file__),'describe','--always'), stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] assert __version__ except: # otherwise check", "otherwise check for a version file try: from . version import version as", "a version file try: from . version import version as __version__ except: pass", "for a version file try: from . version import version as __version__ except:" ]
[ "for _ in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if", "t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print", "import * from fractions import * from random import * n = 1000000000", "= randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c", "q = 200000 print n, q for _ in xrange(q): t = randrange(1,4)", "from fractions import * from random import * n = 1000000000 q =", "fractions import * from random import * n = 1000000000 q = 200000", "n = 1000000000 q = 200000 print n, q for _ in xrange(q):", "* from fractions import * from random import * n = 1000000000 q", "= 200000 print n, q for _ in xrange(q): t = randrange(1,4) l,r,c", "randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c else: print t,l,r #print", "n, q for _ in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1),", "from random import * n = 1000000000 q = 200000 print n, q", "print n, q for _ in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1),", "= randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c else: print t,l,r", "* from random import * n = 1000000000 q = 200000 print n,", "math import * from fractions import * from random import * n =", "import * n = 1000000000 q = 200000 print n, q for _", "in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t <", "200000 print n, q for _ in xrange(q): t = randrange(1,4) l,r,c =", "import * from random import * n = 1000000000 q = 200000 print", "1000000000 q = 200000 print n, q for _ in xrange(q): t =", "= 1000000000 q = 200000 print n, q for _ in xrange(q): t", "* n = 1000000000 q = 200000 print n, q for _ in", "_ in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t", "l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c else: print", "xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3:", "from math import * from fractions import * from random import * n", "random import * n = 1000000000 q = 200000 print n, q for", "randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c else: print t,l,r #print 3,", "1000000000 if t < 3: print t,l,r,c else: print t,l,r #print 3, 1,", "if t < 3: print t,l,r,c else: print t,l,r #print 3, 1, 1000000000", "q for _ in xrange(q): t = randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000", "randrange(1,4) l,r,c = randrange(1,n+1), randrange(1,n+1), 1000000000 if t < 3: print t,l,r,c else:" ]
[ "matrix based on Fukui 2013: Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering", "There are some notable differences between the paper and this implementation, please refer", "split_size : double, optional Ratio of train:test sample size during evolution. train_subset_size :", ": int, optional If provided, controls random number generation. verbose : bool, optional", "\"\"\"Initialize the learner. Parameters ---------- n_gen : int, optional Number of generations for", "Clustering with Neighbor Relations There are some notable differences between the paper and", "Approach to Semi-supervised Clustering with Neighbor Relations There are some notable differences between", "max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen : int, optional Number", "debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ),", "int, optional Number of generations for the evolution strategy. split_size : double, optional", "train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen : int, optional", "optional If provided, controls random number generation. verbose : bool, optional If true", "Mahalanobis matrix based on Fukui 2013: Evolutionary Distance Metric Learning Approach to Semi-supervised", "Parameters ---------- n_gen : int, optional Number of generations for the evolution strategy.", "Relations There are some notable differences between the paper and this implementation, please", "MetricEvolution from .evolution import fitness as fit from .evolution import strategy as st", "some notable differences between the paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0", "as fit from .evolution import strategy as st from .evolution import transformer as", "the paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import", "def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ----------", "---------- n_gen : int, optional Number of generations for the evolution strategy. split_size", "as tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular Mahalanobis matrix.", "the model during evolution. max_workers : int, optional Number of workers for parallelization.", "triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize", "int, optional If provided, controls random number generation. verbose : bool, optional If", "implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution import", "train_subset_size : double, optional Ratio of samples used in training the model during", "Learning Approach to Semi-supervised Clustering with Neighbor Relations There are some notable differences", "double, optional Ratio of samples used in training the model during evolution. max_workers", "Semi-supervised Clustering with Neighbor Relations There are some notable differences between the paper", "st from .evolution import transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE for", "strategy. split_size : double, optional Ratio of train:test sample size during evolution. train_subset_size", "workers for parallelization. random_state : int, optional If provided, controls random number generation.", "Fukui 2013: Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering with Neighbor Relations", "strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ), fitness_list=[fit.WeightedFMeasureFitness()], transformer_func=tr.TriangularMatrixTransformer(), random_state=random_state, verbose=verbose )", "Using jDE for evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33,", "optional Ratio of samples used in training the model during evolution. max_workers :", "\"\"\" from .evolution import MetricEvolution from .evolution import fitness as fit from .evolution", "\"\"\" Using jDE for evolving a triangular Mahalanobis matrix based on Fukui 2013:", "class JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular Mahalanobis matrix. \"\"\" def", "on Fukui 2013: Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering with Neighbor", "of generations for the evolution strategy. split_size : double, optional Ratio of train:test", "used in training the model during evolution. max_workers : int, optional Number of", "split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen : int,", "optional If true then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size,", "\"\"\" Using jDE for evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25,", "tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular Mahalanobis matrix. \"\"\"", "fitness as fit from .evolution import strategy as st from .evolution import transformer", "to Semi-supervised Clustering with Neighbor Relations There are some notable differences between the", "evolving a triangular Mahalanobis matrix based on Fukui 2013: Evolutionary Distance Metric Learning", "strategy as st from .evolution import transformer as tr class JDE(MetricEvolution): \"\"\" Using", "jDE for evolving a triangular Mahalanobis matrix based on Fukui 2013: Evolutionary Distance", "Distance Metric Learning Approach to Semi-supervised Clustering with Neighbor Relations There are some", "sample size during evolution. train_subset_size : double, optional Ratio of samples used in", "from .evolution import transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving", "to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution import fitness as fit", "super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ), fitness_list=[fit.WeightedFMeasureFitness()], transformer_func=tr.TriangularMatrixTransformer(), random_state=random_state,", "verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen : int, optional Number of generations", "optional Number of generations for the evolution strategy. split_size : double, optional Ratio", "the evolution strategy. split_size : double, optional Ratio of train:test sample size during", "with Neighbor Relations There are some notable differences between the paper and this", "Number of generations for the evolution strategy. split_size : double, optional Ratio of", "a triangular Mahalanobis matrix based on Fukui 2013: Evolutionary Distance Metric Learning Approach", "generation. verbose : bool, optional If true then outputs debugging information. \"\"\" super(JDE,", "based on Fukui 2013: Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering with", "true then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers,", "a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False):", "Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering with Neighbor Relations There are", "Metric Learning Approach to Semi-supervised Clustering with Neighbor Relations There are some notable", "\"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ), fitness_list=[fit.WeightedFMeasureFitness()], transformer_func=tr.TriangularMatrixTransformer(),", "Using jDE for evolving a triangular Mahalanobis matrix based on Fukui 2013: Evolutionary", "and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from", "during evolution. max_workers : int, optional Number of workers for parallelization. random_state :", "fit from .evolution import strategy as st from .evolution import transformer as tr", "transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular Mahalanobis", "as st from .evolution import transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE", "jDE for evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0,", "of workers for parallelization. random_state : int, optional If provided, controls random number", "If provided, controls random number generation. verbose : bool, optional If true then", "please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution import fitness", "Ratio of samples used in training the model during evolution. max_workers : int,", "in training the model during evolution. max_workers : int, optional Number of workers", ": int, optional Number of workers for parallelization. random_state : int, optional If", "triangular Mahalanobis matrix based on Fukui 2013: Evolutionary Distance Metric Learning Approach to", "double, optional Ratio of train:test sample size during evolution. train_subset_size : double, optional", "of train:test sample size during evolution. train_subset_size : double, optional Ratio of samples", ".evolution import fitness as fit from .evolution import strategy as st from .evolution", "learner. Parameters ---------- n_gen : int, optional Number of generations for the evolution", "evolution. max_workers : int, optional Number of workers for parallelization. random_state : int,", "random number generation. verbose : bool, optional If true then outputs debugging information.", ": double, optional Ratio of train:test sample size during evolution. train_subset_size : double,", "JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self,", "Neighbor Relations There are some notable differences between the paper and this implementation,", "during evolution. train_subset_size : double, optional Ratio of samples used in training the", "information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ), fitness_list=[fit.WeightedFMeasureFitness()],", "from .evolution import strategy as st from .evolution import transformer as tr class", "from .evolution import MetricEvolution from .evolution import fitness as fit from .evolution import", "then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state,", "__init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen", "self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose ), fitness_list=[fit.WeightedFMeasureFitness()], transformer_func=tr.TriangularMatrixTransformer(), random_state=random_state, verbose=verbose", "parallelization. random_state : int, optional If provided, controls random number generation. verbose :", "for the evolution strategy. split_size : double, optional Ratio of train:test sample size", "matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner.", "number generation. verbose : bool, optional If true then outputs debugging information. \"\"\"", "bool, optional If true then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen,", "for evolving a triangular Mahalanobis matrix based on Fukui 2013: Evolutionary Distance Metric", "notable differences between the paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\"", "controls random number generation. verbose : bool, optional If true then outputs debugging", "generations for the evolution strategy. split_size : double, optional Ratio of train:test sample", "outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size, max_workers=max_workers, random_state=random_state, verbose=verbose", "\"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters", "the learner. Parameters ---------- n_gen : int, optional Number of generations for the", ".evolution import transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving a", "differences between the paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from", "Ratio of train:test sample size during evolution. train_subset_size : double, optional Ratio of", "https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution import fitness as fit from", "evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None,", "this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution", "paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution", "model during evolution. max_workers : int, optional Number of workers for parallelization. random_state", "size during evolution. train_subset_size : double, optional Ratio of samples used in training", "training the model during evolution. max_workers : int, optional Number of workers for", "int, optional Number of workers for parallelization. random_state : int, optional If provided,", "train:test sample size during evolution. train_subset_size : double, optional Ratio of samples used", ".evolution import strategy as st from .evolution import transformer as tr class JDE(MetricEvolution):", "random_state : int, optional If provided, controls random number generation. verbose : bool,", "import strategy as st from .evolution import transformer as tr class JDE(MetricEvolution): \"\"\"", "of samples used in training the model during evolution. max_workers : int, optional", "evolution. train_subset_size : double, optional Ratio of samples used in training the model", ": bool, optional If true then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution(", "optional Ratio of train:test sample size during evolution. train_subset_size : double, optional Ratio", "verbose : bool, optional If true then outputs debugging information. \"\"\" super(JDE, self).__init__(", "import fitness as fit from .evolution import strategy as st from .evolution import", "for evolving a triangular Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1,", "Mahalanobis matrix. \"\"\" def __init__(self, n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the", "Number of workers for parallelization. random_state : int, optional If provided, controls random", "optional Number of workers for parallelization. random_state : int, optional If provided, controls", "n_gen=25, split_size=0.33, train_subset_size=1.0, max_workers=1, random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen :", "from .evolution import fitness as fit from .evolution import strategy as st from", "for parallelization. random_state : int, optional If provided, controls random number generation. verbose", ": int, optional Number of generations for the evolution strategy. split_size : double,", "evolution strategy. split_size : double, optional Ratio of train:test sample size during evolution.", "n_gen : int, optional Number of generations for the evolution strategy. split_size :", ".evolution import MetricEvolution from .evolution import fitness as fit from .evolution import strategy", "provided, controls random number generation. verbose : bool, optional If true then outputs", ": double, optional Ratio of samples used in training the model during evolution.", "import transformer as tr class JDE(MetricEvolution): \"\"\" Using jDE for evolving a triangular", "between the paper and this implementation, please refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution", "max_workers : int, optional Number of workers for parallelization. random_state : int, optional", "are some notable differences between the paper and this implementation, please refer to", "import MetricEvolution from .evolution import fitness as fit from .evolution import strategy as", "2013: Evolutionary Distance Metric Learning Approach to Semi-supervised Clustering with Neighbor Relations There", "random_state=None, verbose=False): \"\"\"Initialize the learner. Parameters ---------- n_gen : int, optional Number of", "If true then outputs debugging information. \"\"\" super(JDE, self).__init__( strategy=st.SelfAdaptingDifferentialEvolution( n_gen=n_gen, split_size=split_size, train_subset_size=train_subset_size,", "samples used in training the model during evolution. max_workers : int, optional Number", "refer to https://github.com/svecon/thesis-distance-metric-learning/releases/tag/1.0 \"\"\" from .evolution import MetricEvolution from .evolution import fitness as" ]
[ "alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga =", "ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone,", "EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at", "core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env)", "\"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app,", "os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App() net", "aws_cdk import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack", "ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc,", "from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env", "cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN,", "account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at synth/deployment time CIDR =", "CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\",", "CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need", "= os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\",", "from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from", "python3 from aws_cdk import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack", "= ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app,", "from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from", "os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR,", "= core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc,", "region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\",", "\"\") SUB_DOMAIN = \"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env)", "app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\",", "net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb,", "= os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App()", "ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack", "import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment(", "from aws_cdk import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import", "= \"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 =", "SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert)", "alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN, env=deploy_env) aga.add_dependency(net)", "be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\")", "injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN", "= EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env)", "AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack", "CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env)", "ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be", "env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga", "env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN, env=deploy_env)", "\"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb =", "DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App() net = NetworkingStack(app,", "import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import", "at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN =", "EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb", "These need to be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN", "core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at synth/deployment time CIDR", "synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\"", "= NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert", "CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app =", "\"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app,", "ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"],", "import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from", "ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN,", "aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN, env=deploy_env) aga.add_dependency(net) aga.add_dependency(cert) aga.add_dependency(alb) app.synth()", "net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app,", "import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These", "os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack", "env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\",", "ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack", "\"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net)", "need to be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN =", "# These need to be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\")", "time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app", "alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN, env=deploy_env) aga.add_dependency(net) aga.add_dependency(cert) aga.add_dependency(alb)", "deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at synth/deployment", "to be injected at synth/deployment time CIDR = os.getenv(\"VPC_CIDR\", \"\") DOMAIN = os.getenv(\"R53_DOMAIN\",", "ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env =", "\"\") DOMAIN = os.getenv(\"R53_DOMAIN\", \"\") SUB_DOMAIN = \"code-server\" app = core.App() net =", "cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance,", "env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert = CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN,", "ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) #", "= CertsStack(app, \"GravitonBlog-CertsStack\", DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert,", "NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack", "#!/usr/bin/env python3 from aws_cdk import core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from", "DOMAIN, SUB_DOMAIN, env=deploy_env) alb = ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2)", "import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected", "= core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to be injected at synth/deployment time", "\"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc,", "import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import", "NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net) cert =", "from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"]) # These need to", "ALBStack(app, \"GravitonBlog-ALBStack\", net.vpc, ec2.instance, cert.domain_cert, env=deploy_env) alb.add_dependency(net) alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\",", "import AgaStack from ec2_ialb_aga_custom_r53.alb_stack import ALBStack from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import", "alb.add_dependency(ec2) alb.add_dependency(cert) aga = AgaStack(app, \"GravitonBlog-AGAStack\", net.vpc, alb.alb, cert.blog_hosted_zone, SUB_DOMAIN, env=deploy_env) aga.add_dependency(net) aga.add_dependency(cert)", "net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2 = EC2Stack(app, \"GravitonBlog-EC2Stack\", net.vpc, env=deploy_env) ec2.add_dependency(net)", "SUB_DOMAIN = \"code-server\" app = core.App() net = NetworkingStack(app, \"GravitonBlog-NetworkingStack\", CIDR, env=deploy_env) ec2", "from ec2_ialb_aga_custom_r53.certs_stack import CertsStack from ec2_ialb_aga_custom_r53.ec2_stack import EC2Stack deploy_env = core.Environment( account=os.environ[\"CDK_DEFAULT_ACCOUNT\"], region=os.environ[\"CDK_DEFAULT_REGION\"])", "core import os from ec2_ialb_aga_custom_r53.network_stack import NetworkingStack from ec2_ialb_aga_custom_r53.aga_stack import AgaStack from ec2_ialb_aga_custom_r53.alb_stack" ]
[ "translation from vanilla import TemplateView, DetailView, UpdateView from deck.models import Event, Proposal from", "return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object = form.save()", "from django.shortcuts import get_object_or_404 from django.utils import translation from vanilla import TemplateView, DetailView,", "AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field", "class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[", "model = Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username", "ugettext as _ from django.http import Http404, HttpResponseRedirect from django.contrib import messages from", "ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.'))", "form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object =", "context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile form_class =", "and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context =", "django.shortcuts import get_object_or_404 from django.utils import translation from vanilla import TemplateView, DetailView, UpdateView", "= Profile form_class = ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset =", "username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username ==", "self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404", "proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name", "username and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset,", "import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing", "= 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count()", "core.models import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin,", "ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username')", "from django.contrib import messages from django.shortcuts import get_object_or_404 from django.utils import translation from", "ProfilePictureForm def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class", "self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object = form.save() return", "import get_object_or_404 from django.utils import translation from vanilla import TemplateView, DetailView, UpdateView from", "class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile form_class = ProfileForm", "get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated():", "raise Http404 def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self,", "def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class =", "error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object =", "events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView):", "vanilla import TemplateView, DetailView, UpdateView from deck.models import Event, Proposal from core.models import", "ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self,", "return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form): self.object = form.save() return", "def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return", "self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class", "self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin,", "(username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self,", "form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object", "self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def", "not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return", "template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field =", "and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username)", "template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(),", "= self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile elif", "queryset = self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile", "self.object.get_absolute_url() ) def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get()", "if not username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self,", "Proposal from core.models import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins", "messages from django.shortcuts import get_object_or_404 from django.utils import translation from vanilla import TemplateView,", "_ from django.http import Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts import", "= 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field = 'user__username'", "from django.utils.translation import ugettext as _ from django.http import Http404, HttpResponseRedirect from django.contrib", "FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs)", "'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if not username", "= 'account/profile.html' model = Profile form_class = ProfileForm lookup_field = 'user__username' def get_object(self,", "class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo", "'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() )", "IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(),", "context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name = 'about.html' class", "from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs):", "username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context", ") return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile", "if not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser):", "form_class = ProfilePictureForm def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class", "def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object),", "return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile form_class", "form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ] = self.object.language return self.success_redirect(_(u'Language", "= self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing,", "form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ] = self.object.language return self.success_redirect(_(u'Language changed.'))", "return context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model", "for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm", "import TemplateView, DetailView, UpdateView from deck.models import Event, Proposal from core.models import Profile", "ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile form_class = ProfileForm lookup_field", "template_name = 'account/profile.html' model = Profile form_class = ProfileForm lookup_field = 'user__username' def", "= super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return", "HttpResponseRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.utils import translation", "= ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username =", "self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView):", "'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field = 'user__username' def", "self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name = 'about.html'", "as _ from django.http import Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts", "self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request,", "lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if", "*args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for", "deck.models import Event, Proposal from core.models import Profile from core.forms import ProfileForm, ProfilePictureForm,", "self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error in", ") return context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html'", "error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def", "from deck.models import Event, Proposal from core.models import Profile from core.forms import ProfileForm,", "= self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username)", "**kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return", "profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name =", "from django.utils import translation from vanilla import TemplateView, DetailView, UpdateView from deck.models import", "else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object =", "messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form): self.object", "Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username')", "Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class", "LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView,", "UpdateView): template_name = 'account/profile.html' model = Profile form_class = ProfileForm lookup_field = 'user__username'", "== self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form):", "self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save()", "import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name =", "def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ] = self.object.language return", "class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update(", "super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name =", "import User from django.utils.translation import ugettext as _ from django.http import Http404, HttpResponseRedirect", "super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context", "language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html'", "from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView):", "form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect(", "form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object", "ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ] = self.object.language", "def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if not username and", "UpdateView from deck.models import Event, Proposal from core.models import Profile from core.forms import", "import messages from django.shortcuts import get_object_or_404 from django.utils import translation from vanilla import", "context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name", "= 'account/profile.html' model = Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset =", "**kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error", "self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form): self.object = form.save()", "= ProfilePictureForm def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView):", "import Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.utils", "class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field = 'user__username' def get_object(self,", "or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form): self.object =", "HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return", "else: raise Http404 def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def", "django.contrib import messages from django.shortcuts import get_object_or_404 from django.utils import translation from vanilla", "user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object),", "self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form): self.object", "import ugettext as _ from django.http import Http404, HttpResponseRedirect from django.contrib import messages", "self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object", "return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url()", "updated.')) def get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def", "ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def", "get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form):", "import translation from vanilla import TemplateView, DetailView, UpdateView from deck.models import Event, Proposal", "**kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class", "= self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error in form.errors.itervalues():", "self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile else: return", "get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(),", "form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self, form):", "User from django.utils.translation import ugettext as _ from django.http import Http404, HttpResponseRedirect from", "from core.models import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import", "context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView):", "events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model", "ProfileView(DetailView): template_name = 'account/profile.html' model = Profile lookup_field = 'user__username' def get_object(self, **kwargs):", "= Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username =", "self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView,", "form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def", "self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else:", "import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context =", "not username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs):", "ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY", "return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message)", "form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm", "= self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username", "self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object = self.get_object()", "core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name", "form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ]", "ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html'", "return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object =", "**kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(),", "'account/profile.html' model = Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset()", "form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class =", "= self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile else:", "form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class", "return self.request.user.profile elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise", "proposals=self.object.get_profile_proposals(), ) return context class ProfileUpdateView(LoginRequiredMixin, FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model =", "django.http import Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from", "get_object_or_404 from django.utils import translation from vanilla import TemplateView, DetailView, UpdateView from deck.models", "Profile form_class = ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset()", "core.mixins import LoginRequiredMixin, FormValidRedirectMixing class IndexView(TemplateView): template_name = 'index.html' def get_context_data(self, **kwargs): context", "username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile else: return get_object_or_404(queryset,", "class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model = Profile", "form_class = ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username", "self.get_queryset() username = self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username", "Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts import get_object_or_404 from django.utils import", "self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() )", "self.kwargs.get('user__username') if not username and self.request.user.is_authenticated(): return self.request.user.profile elif (username == self.request.user.username or", "def get(self, *args, **kwargs): self.object = self.get_object() return HttpResponseRedirect( self.object.get_absolute_url() ) def form_invalid(self,", ") def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class", "Event, Proposal from core.models import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm from", "from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.http import", "'account/profile.html' model = Profile form_class = ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs):", "django.utils import translation from vanilla import TemplateView, DetailView, UpdateView from deck.models import Event,", "= form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs): self.object = self.get_object() return", "in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView): form_class = ProfilePictureForm def form_valid(self,", "def form_invalid(self, form): for error in form.errors.itervalues(): messages.error(self.request, error.as_data()[0].message) return self.get() class ProfileUpdatePictureView(ProfileUpdateView):", "get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update(", "Http404 def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args,", "= form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form):", "= 'user__username' def get_object(self, **kwargs): queryset = self.get_queryset() username = self.kwargs.get('user__username') if not", "model = Profile form_class = ProfileForm lookup_field = 'user__username' def get_object(self, **kwargs): queryset", "django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.http import Http404,", "return self.request.user.profile else: return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs)", "elif (username == self.request.user.username or self.request.user.is_superuser): return get_object_or_404(queryset, user__username=username) else: raise Http404 def", "DetailView, UpdateView from deck.models import Event, Proposal from core.models import Profile from core.forms", "from vanilla import TemplateView, DetailView, UpdateView from deck.models import Event, Proposal from core.models", "template_name = 'account/profile.html' model = Profile lookup_field = 'user__username' def get_object(self, **kwargs): queryset", "users=User.objects.count() ) return context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name =", "return get_object_or_404(queryset, user__username=username) def get_context_data(self, **kwargs): context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object()", "import Event, Proposal from core.models import Profile from core.forms import ProfileForm, ProfilePictureForm, ProfileChangeLanguageForm", "context = super(ProfileView, self).get_context_data(**kwargs) self.object = self.get_object() context.update( profile_form=ProfileForm(instance=self.object), language_form=ProfileChangeLanguageForm(instance=self.object), events=self.object.get_profile_events(), proposals=self.object.get_profile_proposals(), )", "context class AboutView(TemplateView): template_name = 'about.html' class ProfileView(DetailView): template_name = 'account/profile.html' model =", "user__username=username) else: raise Http404 def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.'))", "= ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language) self.request.session[ translation.LANGUAGE_SESSION_KEY ] =", "def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile updated.')) def get(self, *args, **kwargs):", "= super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context class AboutView(TemplateView): template_name", "FormValidRedirectMixing, UpdateView): template_name = 'account/profile.html' model = Profile form_class = ProfileForm lookup_field =", "changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self, form): self.object = form.save() translation.activate(self.object.language)", "self.object = form.save() return self.success_redirect(_(u'Photo changed.')) class ProfileChangeLanguageView(ProfileUpdateView): form_class = ProfileChangeLanguageForm def form_valid(self,", "get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context.update( events=Event.objects.count(), proposals=Proposal.objects.count(), users=User.objects.count() ) return context", "get_object_or_404(queryset, user__username=username) else: raise Http404 def form_valid(self, form): self.object = form.save() return self.success_redirect(_(u'Profile", "from django.http import Http404, HttpResponseRedirect from django.contrib import messages from django.shortcuts import get_object_or_404", "django.utils.translation import ugettext as _ from django.http import Http404, HttpResponseRedirect from django.contrib import", "TemplateView, DetailView, UpdateView from deck.models import Event, Proposal from core.models import Profile from" ]
[ "list2=[12,14,-95,3] for i in list1: if i>0: print(i) for j in list2: if", "list1=[12,-7,5,64,-14] list2=[12,14,-95,3] for i in list1: if i>0: print(i) for j in list2:", "i in list1: if i>0: print(i) for j in list2: if j>0: print(j)", "for i in list1: if i>0: print(i) for j in list2: if j>0:" ]
[ "geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows", "% self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias.", "will figure out whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted()", "PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def", "allows escaping the binary in the style required by the server's `standard_conforming_string` setting.", "= Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args,", "import * from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from", "import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class", "the binary in the style required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn)", "PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\"", "psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows escaping the binary in the", "method allows escaping the binary in the style required by the server's `standard_conforming_string`", "import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom):", "required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly", "class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper):", "\"Returns a properly quoted string for use in PostgreSQL/PostGIS.\" # psycopg will figure", "getquoted(self): \"Returns a properly quoted string for use in PostgreSQL/PostGIS.\" # psycopg will", "PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs):", "django.db.backends.postgresql_psycopg2.base import * from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation", "# Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation", "style required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a", "def prepare(self, conn): \"\"\" This method allows escaping the binary in the style", "whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter", "__init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method", "def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This", "psycopg will figure out whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' %", "from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def", "Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations", "import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def", "django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter", "figure out whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class", "self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class", "import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import", "= PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args,", "self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string for use in PostgreSQL/PostGIS.\" #", "the style required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns", "<reponame>Mozilla-GitHub-Standards/54c69db06ef83bda60e995a6c34ecfd168ca028994e40ce817295415bb409f0c<filename>make_mozilla/postgis/base.py<gh_stars>1-10 from django.db.backends.postgresql_psycopg2.base import * from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation", "in the style required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self):", "from django.db.backends.postgresql_psycopg2.base import * from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import", "DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations", "from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from", "conn): \"\"\" This method allows escaping the binary in the style required by", "escaping the binary in the style required by the server's `standard_conforming_string` setting. \"\"\"", "use in PostgreSQL/PostGIS.\" # psycopg will figure out whether to use E'\\\\000' or", "super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows escaping", "from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import", "psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self,", "def getquoted(self): \"Returns a properly quoted string for use in PostgreSQL/PostGIS.\" # psycopg", "setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string for use in", "# psycopg will figure out whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)'", "for use in PostgreSQL/PostGIS.\" # psycopg will figure out whether to use E'\\\\000'", "\"\"\" This method allows escaping the binary in the style required by the", "or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor =", "import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter =", "quoted string for use in PostgreSQL/PostGIS.\" # psycopg will figure out whether to", "django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection", "**kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops = PatchedPostGISOperations(self) self.introspection = PostGISIntrospection(self)", "Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper,", "def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops = PatchedPostGISOperations(self)", "return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter #", "as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import", "'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility", "PostgreSQL/PostGIS.\" # psycopg will figure out whether to use E'\\\\000' or '\\000' return", "'\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor = Adapter", "from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import", "PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb)", "by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted", "out whether to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations):", "string for use in PostgreSQL/PostGIS.\" # psycopg will figure out whether to use", "prepare(self, conn): \"\"\" This method allows escaping the binary in the style required", "E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter Adaptor", "django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self,", "in PostgreSQL/PostGIS.\" # psycopg will figure out whether to use E'\\\\000' or '\\000'", "PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter):", "* from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection", "__init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops = PatchedPostGISOperations(self) self.introspection", "django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter", "alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self)", "PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter", "Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation =", "PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter,", "Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs)", "`standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string for use", "DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops =", "binary in the style required by the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def", "*args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops = PatchedPostGISOperations(self) self.introspection =", "self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows escaping the", "the server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string", "class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self, *args, **kwargs): super(DatabaseWrapper, self).__init__(*args, **kwargs) self.creation = PostGISCreation(self) self.ops", "to use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter =", "This method allows escaping the binary in the style required by the server's", "from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2 class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom)", "Adapter = PatchedPostGISAdapter Adaptor = Adapter # Backwards-compatibility alias. class DatabaseWrapper(Psycopg2DatabaseWrapper): def __init__(self,", "self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows escaping the binary", "server's `standard_conforming_string` setting. \"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string for", "a properly quoted string for use in PostgreSQL/PostGIS.\" # psycopg will figure out", "class PatchedPostGISAdapter(PostGISAdapter): def __init__(self, geom): super(PatchedPostGISAdapter, self).__init__(geom) self._adapter = psycopg2.Binary(self.ewkb) def prepare(self, conn):", "properly quoted string for use in PostgreSQL/PostGIS.\" # psycopg will figure out whether", "django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from django.contrib.gis.db.backends.postgis.operations import PostGISOperations from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter import psycopg2", "\"\"\" self._adapter.prepare(conn) def getquoted(self): \"Returns a properly quoted string for use in PostgreSQL/PostGIS.\"", "use E'\\\\000' or '\\000' return 'ST_GeomFromEWKB(%s)' % self._adapter.getquoted() class PatchedPostGISOperations(PostGISOperations): Adapter = PatchedPostGISAdapter", "import DatabaseWrapper as Psycopg2DatabaseWrapper from django.contrib.gis.db.backends.postgis.creation import PostGISCreation from django.contrib.gis.db.backends.postgis.introspection import PostGISIntrospection from", "= psycopg2.Binary(self.ewkb) def prepare(self, conn): \"\"\" This method allows escaping the binary in" ]
[ "= os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async", "== 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take server", "{datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to {dest}') except", "{dest}') except Exception as e: await ctx.send('Backup failed :( Check console for error')", "= json.load(f) # Display mods if (not len(args)): message = '' # Add", "Display mods if (not len(args)): message = '' # Add server mods message", "bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command()", "spawn on Day {args[0]}.') else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"')", "+= 71.8 await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else: await ctx.send('Only", "' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file before dumping the updated contents", "'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server", "dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved", "file day += 71.8 await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else:", "f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help", "f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type}", "except Exception as e: await ctx.send('Backup failed :( Check console for error') print(e)", "== 'server' or args[0] == 'client'): mod_type = args[0] # Format the mod", "(not len(args)): message = '' # Add server mods message += '__**Server Mods:**__\\n'", "'client'): mod_type = args[0] # Format the mod and add it to json", "os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has", "ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage:", "server mods message += '__**Server Mods:**__\\n' for mod in data['server']: message += f'-", "= args[0] # Format the mod and add it to json mod =", "# Update file day += 71.8 await ctx.send(f'Updated: Deerclops will spawn on Day", "{round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f:", "open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will", "commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async def", "async def mods(ctx, *args): with open('data/mods.json', 'r+') as f: data = json.load(f) #", "71.8 await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else: await ctx.send('Only provide", "Add server mods message += '__**Server Mods:**__\\n' for mod in data['server']: message +=", "message += '__**Server Mods:**__\\n' for mod in data['server']: message += f'- {mod}\\n' #", "f'- {mod}\\n' await ctx.send(message) # Add new mod elif (args[0] == 'server' or", "await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+')", "to {dest}') except Exception as e: await ctx.send('Backup failed :( Check console for", "as f: day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn on", "== 'client'): mod_type = args[0] # Format the mod and add it to", "from dotenv import load_dotenv import json import shutil from datetime import datetime load_dotenv()", "load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!')", "ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else: await ctx.send('Only provide 1 argument!", "mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file before dumping the", "elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif (len(args) == 1): #", "# Add client mods message += '\\n__**Client Mods:**__\\n' for mod in data['client']: message", "TODO: take server name as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust", "ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as", "add it to json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json", "def mods(ctx, *args): with open('data/mods.json', 'r+') as f: data = json.load(f) # Display", "with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops", "== 'help'): await ctx.send('Deerclops Usage: ') elif (len(args) == 1): # Update file", "load_dotenv import json import shutil from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN')", "import shutil from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR')", "# Format the mod and add it to json mod = ' '.join(args[1:])", "await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args):", "async def save(ctx): # TODO: take server name as argument src = f'{DST_DIR}/Cluster_5'", "= f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.') elif", "open('data/mods.json', 'r+') as f: data = json.load(f) # Display mods if (not len(args)):", "import json import shutil from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR", "e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+') as f:", "len(args)): message = '' # Add server mods message += '__**Server Mods:**__\\n' for", "import commands from dotenv import load_dotenv import json import shutil from datetime import", "contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to", "name as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest =", "mods message += '\\n__**Client Mods:**__\\n' for mod in data['client']: message += f'- {mod}\\n'", "*args): with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if (not len(args)): await", "Usage: ') elif (len(args) == 1): # Update file day += 71.8 await", "for mod in data['server']: message += f'- {mod}\\n' # Add client mods message", "10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+') as f: data =", "await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif (args[0] == 'help'): await", "Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def", "message = '' # Add server mods message += '__**Server Mods:**__\\n' for mod", "+= '__**Server Mods:**__\\n' for mod in data['server']: message += f'- {mod}\\n' # Add", "the mod and add it to json mod = ' '.join(args[1:]) data[mod_type].append(mod) #", "on Day {args[0]}.') else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod'])", "data['client']: message += f'- {mod}\\n' await ctx.send(message) # Add new mod elif (args[0]", "data[mod_type].append(mod) # Clear the json file before dumping the updated contents f.seek(0) f.truncate()", "src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}'", "mod in data['server']: message += f'- {mod}\\n' # Add client mods message +=", "= os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user}", "Mods:**__\\n' for mod in data['client']: message += f'- {mod}\\n' await ctx.send(message) # Add", "message += f'- {mod}\\n' await ctx.send(message) # Add new mod elif (args[0] ==", "%H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception", "or args[0] == 'client'): mod_type = args[0] # Format the mod and add", "server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest)", "indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif", "saved to {dest}') except Exception as e: await ctx.send('Backup failed :( Check console", "= commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async", "file before dumping the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send", "datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot =", "mod in data['client']: message += f'- {mod}\\n' await ctx.send(message) # Add new mod", "args[0] == 'client'): mod_type = args[0] # Format the mod and add it", "usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take server name as argument src", "await ctx.send('Deerclops Usage: ') elif (len(args) == 1): # Update file day +=", "if (not len(args)): message = '' # Add server mods message += '__**Server", "json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') #", "Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif (len(args) ==", "@bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async def ping(ctx):", "1): # Update file day += 71.8 await ctx.send(f'Updated: Deerclops will spawn on", "Update file day += 71.8 await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.')", "on Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif (len(args)", "def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong!", "await ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops", "and add it to json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the", "# Add new mod elif (args[0] == 'server' or args[0] == 'client'): mod_type", "updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\"", "'server' or args[0] == 'client'): mod_type = args[0] # Format the mod and", "\"{mod}\" to {mod_type} mods!') # Help elif (args[0] == 'help'): await ctx.send('Mods usage:')", "= f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try:", "f'- {mod}\\n' # Add client mods message += '\\n__**Client Mods:**__\\n' for mod in", "shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception as e:", "data['server']: message += f'- {mod}\\n' # Add client mods message += '\\n__**Client Mods:**__\\n'", "# Clear the json file before dumping the updated contents f.seek(0) f.truncate() json.dump(data,", "f.truncate() json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!')", "try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception as", "ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take server name as argument", "the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation! await ctx.send(f'Added", "connected to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops'])", "1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+')", "args[0] # Format the mod and add it to json mod = '", "will spawn on Day {args[0]}.') else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops", "'.join(args[1:]) data[mod_type].append(mod) # Clear the json file before dumping the updated contents f.seek(0)", "for mod in data['client']: message += f'- {mod}\\n' await ctx.send(message) # Add new", "to {mod_type} mods!') # Help elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup'])", "{day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif (len(args) == 1):", "len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0] == 'help'): await", "new mod elif (args[0] == 'server' or args[0] == 'client'): mod_type = args[0]", "mods message += '__**Server Mods:**__\\n' for mod in data['server']: message += f'- {mod}\\n'", "from discord.ext import commands from dotenv import load_dotenv import json import shutil from", "commands from dotenv import load_dotenv import json import shutil from datetime import datetime", "before dumping the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation!", "# Add server mods message += '__**Server Mods:**__\\n' for mod in data['server']: message", "await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else: await ctx.send('Only provide 1", "in data['client']: message += f'- {mod}\\n' await ctx.send(message) # Add new mod elif", "saved!') print(f'Server saved to {dest}') except Exception as e: await ctx.send('Backup failed :(", "{args[0]}.') else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def", "f: data = json.load(f) # Display mods if (not len(args)): message = ''", "datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR')", "def save(ctx): # TODO: take server name as argument src = f'{DST_DIR}/Cluster_5' server_name", "@bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx,", "(len(args) == 1): # Update file day += 71.8 await ctx.send(f'Updated: Deerclops will", "async def on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async def ping(ctx): await", "+= f'- {mod}\\n' await ctx.send(message) # Add new mod elif (args[0] == 'server'", "f: day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn on Day", "ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with", "== 1): # Update file day += 71.8 await ctx.send(f'Updated: Deerclops will spawn", "os from discord.ext import commands from dotenv import load_dotenv import json import shutil", "json file before dumping the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) #", "shutil from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR", "ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception as e: await ctx.send('Backup failed", "\"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+') as f: data", "argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+') as", "Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif (args[0] ==", "argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y", "to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async", "elif (len(args) == 1): # Update file day += 71.8 await ctx.send(f'Updated: Deerclops", "mods!') # Help elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def", "Mods:**__\\n' for mod in data['server']: message += f'- {mod}\\n' # Add client mods", "@bot.command(aliases=['backup']) async def save(ctx): # TODO: take server name as argument src =", "Deerclops will spawn on Day {args[0]}.') else: await ctx.send('Only provide 1 argument! e.g.", "# TODO: take server name as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the", "await ctx.send(message) # Add new mod elif (args[0] == 'server' or args[0] ==", "'\\n__**Client Mods:**__\\n' for mod in data['client']: message += f'- {mod}\\n' await ctx.send(message) #", "rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!')", "message += f'- {mod}\\n' # Add client mods message += '\\n__**Client Mods:**__\\n' for", "TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event", "buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server", "server name as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest", "it to json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file", "take server name as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster'", "mods(ctx, *args): with open('data/mods.json', 'r+') as f: data = json.load(f) # Display mods", "ctx.send(message) # Add new mod elif (args[0] == 'server' or args[0] == 'client'):", "(args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif (len(args) == 1): # Update", "{mod}\\n' # Add client mods message += '\\n__**Client Mods:**__\\n' for mod in data['client']:", "Clear the json file before dumping the updated contents f.seek(0) f.truncate() json.dump(data, f,", "@bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip()", "f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src,", "import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot", "'r+') as f: day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn", "@bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json', 'r+') as f: data = json.load(f)", "to json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file before", "dotenv import load_dotenv import json import shutil from datetime import datetime load_dotenv() TOKEN", "data = json.load(f) # Display mods if (not len(args)): message = '' #", "as argument src = f'{DST_DIR}/Cluster_5' server_name = 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup", "= '' # Add server mods message += '__**Server Mods:**__\\n' for mod in", "in data['server']: message += f'- {mod}\\n' # Add client mods message += '\\n__**Client", "= ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file before dumping the updated", "ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif (args[0] == 'help'): await ctx.send('Mods", "deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if (not len(args)):", "# Send confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif (args[0]", "Day {args[0]}.') else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async", "(args[0] == 'server' or args[0] == 'client'): mod_type = args[0] # Format the", "will spawn on Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ')", "mods if (not len(args)): message = '' # Add server mods message +=", "= f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to", "'r+') as f: data = json.load(f) # Display mods if (not len(args)): message", "day += 71.8 await ctx.send(f'Updated: Deerclops will spawn on Day {args[0]}.') else: await", "message += '\\n__**Client Mods:**__\\n' for mod in data['client']: message += f'- {mod}\\n' await", "discord.ext import commands from dotenv import load_dotenv import json import shutil from datetime", "client mods message += '\\n__**Client Mods:**__\\n' for mod in data['client']: message += f'-", "import os from discord.ext import commands from dotenv import load_dotenv import json import", "* 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day", "mod_type = args[0] # Format the mod and add it to json mod", "= 'the rust buster' dest = f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await", "= os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to", "ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt',", "Help elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): #", "Add client mods message += '\\n__**Client Mods:**__\\n' for mod in data['client']: message +=", "'' # Add server mods message += '__**Server Mods:**__\\n' for mod in data['server']:", "Exception as e: await ctx.send('Backup failed :( Check console for error') print(e) bot.run(TOKEN)", "confirmation! await ctx.send(f'Added \"{mod}\" to {mod_type} mods!') # Help elif (args[0] == 'help'):", "mod and add it to json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear", "dumping the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4) # Send confirmation! await", "await ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception as e: await ctx.send('Backup", "await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take server name as", "async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if", "ctx.send('Deerclops Usage: ') elif (len(args) == 1): # Update file day += 71.8", "'help'): await ctx.send('Deerclops Usage: ') elif (len(args) == 1): # Update file day", "json.load(f) # Display mods if (not len(args)): message = '' # Add server", "mod elif (args[0] == 'server' or args[0] == 'client'): mod_type = args[0] #", "elif (args[0] == 'server' or args[0] == 'client'): mod_type = args[0] # Format", "async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args):", "day = f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.')", "save(ctx): # TODO: take server name as argument src = f'{DST_DIR}/Cluster_5' server_name =", "spawn on Day {day}.') elif (args[0] == 'help'): await ctx.send('Deerclops Usage: ') elif", "') elif (len(args) == 1): # Update file day += 71.8 await ctx.send(f'Updated:", "# Display mods if (not len(args)): message = '' # Add server mods", "Format the mod and add it to json mod = ' '.join(args[1:]) data[mod_type].append(mod)", "DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready():", "BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected", "import load_dotenv import json import shutil from datetime import datetime load_dotenv() TOKEN =", "with open('data/mods.json', 'r+') as f: data = json.load(f) # Display mods if (not", "f.readlines()[0].strip() if (not len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0]", "print(f'{bot.user} has connected to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency *", "*args): with open('data/mods.json', 'r+') as f: data = json.load(f) # Display mods if", "as f: data = json.load(f) # Display mods if (not len(args)): message =", "{mod}\\n' await ctx.send(message) # Add new mod elif (args[0] == 'server' or args[0]", "else: await ctx.send('Only provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx,", "def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with", "json mod = ' '.join(args[1:]) data[mod_type].append(mod) # Clear the json file before dumping", "the json file before dumping the updated contents f.seek(0) f.truncate() json.dump(data, f, indent=4)", "+= f'- {mod}\\n' # Add client mods message += '\\n__**Client Mods:**__\\n' for mod", "provide 1 argument! e.g. \"!deerclops 10\"') @bot.command(aliases=['mod']) async def mods(ctx, *args): with open('data/mods.json',", "'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take server name", "def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day = f.readlines()[0].strip() if (not", "json import shutil from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR =", "has connected to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency * 1000)}ms')", "if (not len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0] ==", "+= '\\n__**Client Mods:**__\\n' for mod in data['client']: message += f'- {mod}\\n' await ctx.send(message)", "(not len(args)): await ctx.send(f'Deerclops will spawn on Day {day}.') elif (args[0] == 'help'):", "'__**Server Mods:**__\\n' for mod in data['server']: message += f'- {mod}\\n' # Add client", "f'{BACKUP_DIR}/{server_name}/Backup {datetime.now().strftime(\"%b-%d-%y %H%M\")}' try: shutil.copytree(src, dest) await ctx.send('Server saved!') print(f'Server saved to {dest}')", "from datetime import datetime load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR =", "on_ready(): print(f'{bot.user} has connected to Discord!') @bot.command() async def ping(ctx): await ctx.send(f'Pong! {round(bot.latency", "{mod_type} mods!') # Help elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async", "# Help elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx):", "elif (args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO:", "print(f'Server saved to {dest}') except Exception as e: await ctx.send('Backup failed :( Check", "1000)}ms') @bot.command(aliases=['clops']) async def deerclops(ctx, *args): with open('data/deerclops.txt', 'r+') as f: day =", "dest) await ctx.send('Server saved!') print(f'Server saved to {dest}') except Exception as e: await", "Add new mod elif (args[0] == 'server' or args[0] == 'client'): mod_type =", "os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print(f'{bot.user} has connected to Discord!')", "(args[0] == 'help'): await ctx.send('Mods usage:') @bot.command(aliases=['backup']) async def save(ctx): # TODO: take", "os.getenv('DISCORD_TOKEN') DST_DIR = os.getenv('DST_DIR') BACKUP_DIR = os.getenv('BACKUP_DIR') bot = commands.Bot(command_prefix='!') @bot.event async def" ]
[ "check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer", "MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert", "bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\"", "node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check !=", "renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source", "renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check", "!= [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer =", "assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert", "== \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider", "== dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check", "GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[])", "renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data", "= GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != []", "bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer", "test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check =", "dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check =", "GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource()", "= GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data ==", "= renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer =", "check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer", "[] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer)", "= GraphRenderer() check = renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source =", "assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[])", "ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check", "__future__ import absolute_import from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer,", "ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check = renderer._check_malformed_graph_source() assert check", "== \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data ==", "None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check == []", "check = renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer", "\"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[],", "test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert", "dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer", "ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name", "[] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer)", "assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle())", "= ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check = renderer._check_malformed_graph_source() assert", "def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check == [] def", "def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\"", "edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check = renderer._check_malformed_graph_source()", "renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert", "\"default\" assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is", "= ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert", "absolute_import from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def", "from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props():", "renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source", "assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert", "edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check = renderer._check_malformed_graph_source() assert check !=", "node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source()", "assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer =", "renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None def", "== dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors():", "from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name ==", "GraphRenderer() check = renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource()", "glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end():", "import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert", "test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check =", "test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index():", "= renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer =", "renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer()", "def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check", "= GlyphRenderer(data_source=edge_source, glyph=MultiLine()) renderer = GraphRenderer(edge_renderer=edge_renderer) check = renderer._check_malformed_graph_source() assert check != []", "assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source, glyph=MultiLine())", "import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer =", "== [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer =", "renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name == \"default\" assert renderer.node_renderer.data_source.data", "def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check", "import absolute_import from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer", "GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name", "renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer = GlyphRenderer(data_source=edge_source,", "GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer() assert renderer.x_range_name == \"default\" assert renderer.y_range_name ==", "Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import GlyphRenderer, GraphRenderer def test_graphrenderer_init_props(): renderer = GraphRenderer()", "renderer._check_malformed_graph_source() assert check == [] def test_graphrenderer_check_malformed_graph_source_no_node_index(): node_source = ColumnDataSource() node_renderer = GlyphRenderer(data_source=node_source,", "end=[]) assert renderer.layout_provider is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source()", "from __future__ import absolute_import from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers import", "is None def test_graphrenderer_check_malformed_graph_source_no_errors(): renderer = GraphRenderer() check = renderer._check_malformed_graph_source() assert check ==", "GlyphRenderer(data_source=node_source, glyph=Circle()) renderer = GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != [] def", "check = renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source = ColumnDataSource() edge_renderer", "= GraphRenderer(node_renderer=node_renderer) check = renderer._check_malformed_graph_source() assert check != [] def test_graphrenderer_check_malformed_graph_source_no_edge_start_or_end(): edge_source =", "<reponame>gully/bokeh from __future__ import absolute_import from bokeh.models import Circle, MultiLine, ColumnDataSource from bokeh.models.renderers", "assert renderer.node_renderer.data_source.data == dict(index=[]) assert renderer.edge_renderer.data_source.data == dict(start=[], end=[]) assert renderer.layout_provider is None" ]
[ "r, x): if (b, r) in p: p[(b, r)] += x else: p[(b,", "add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for", "= {} for ((b, r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p,", "(b, r) in p: p[(b, r)] += x else: p[(b, r)] = x", "p[(b, r)] += x else: p[(b, r)] = x n = 15 dp", "15 dp = [] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p =", "dp = [] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p = {}", "r)] = x n = 15 dp = [] dp.append({(0,0): 1.0}) for rnd", "{} for ((b, r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b,", "v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r), v)", "add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r), v) in", "((b, r), v) in dp[n].items(): if b > r: s += v ans", "dp[n].items(): if b > r: s += v ans = int(1/s) print ans", "dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0", "1.0}) for rnd in xrange(1, n+1): p = {} for ((b, r), v)", "x else: p[(b, r)] = x n = 15 dp = [] dp.append({(0,0):", "for rnd in xrange(1, n+1): p = {} for ((b, r), v) in", "rnd in xrange(1, n+1): p = {} for ((b, r), v) in dp[rnd-1].items():", "in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s =", "v) in dp[n].items(): if b > r: s += v ans = int(1/s)", "b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b,", "else: p[(b, r)] = x n = 15 dp = [] dp.append({(0,0): 1.0})", "r) in p: p[(b, r)] += x else: p[(b, r)] = x n", "p[(b, r)] = x n = 15 dp = [] dp.append({(0,0): 1.0}) for", "dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p = {} for ((b, r),", "in p: p[(b, r)] += x else: p[(b, r)] = x n =", "s = 0 for ((b, r), v) in dp[n].items(): if b > r:", "for ((b, r), v) in dp[n].items(): if b > r: s += v", "v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r), v) in dp[n].items(): if b", "+= x else: p[(b, r)] = x n = 15 dp = []", "b, r, x): if (b, r) in p: p[(b, r)] += x else:", "dp.append(p) s = 0 for ((b, r), v) in dp[n].items(): if b >", "def add(p, b, r, x): if (b, r) in p: p[(b, r)] +=", "p = {} for ((b, r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1))", "= 0 for ((b, r), v) in dp[n].items(): if b > r: s", "n+1): p = {} for ((b, r), v) in dp[rnd-1].items(): add(p, b+1, r,", "[] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p = {} for ((b,", "r), v) in dp[n].items(): if b > r: s += v ans =", "r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r),", "= x n = 15 dp = [] dp.append({(0,0): 1.0}) for rnd in", "p: p[(b, r)] += x else: p[(b, r)] = x n = 15", "r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r), v) in dp[n].items(): if", "in xrange(1, n+1): p = {} for ((b, r), v) in dp[rnd-1].items(): add(p,", "in dp[n].items(): if b > r: s += v ans = int(1/s) print", "add(p, b, r, x): if (b, r) in p: p[(b, r)] += x", "r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p)", "xrange(1, n+1): p = {} for ((b, r), v) in dp[rnd-1].items(): add(p, b+1,", "= [] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p = {} for", "x n = 15 dp = [] dp.append({(0,0): 1.0}) for rnd in xrange(1,", "for ((b, r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1,", "= 15 dp = [] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1): p", "v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1)) dp.append(p) s", "<reponame>huangshenno1/project_euler def add(p, b, r, x): if (b, r) in p: p[(b, r)]", "0 for ((b, r), v) in dp[n].items(): if b > r: s +=", "x): if (b, r) in p: p[(b, r)] += x else: p[(b, r)]", "if (b, r) in p: p[(b, r)] += x else: p[(b, r)] =", "r)] += x else: p[(b, r)] = x n = 15 dp =", "n = 15 dp = [] dp.append({(0,0): 1.0}) for rnd in xrange(1, n+1):", "((b, r), v) in dp[rnd-1].items(): add(p, b+1, r, v/(rnd+1)) add(p, b, r+1, v*rnd/(rnd+1))", "b, r+1, v*rnd/(rnd+1)) dp.append(p) s = 0 for ((b, r), v) in dp[n].items():" ]
[ "self.policy(x, a) v = self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def", "None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type", "output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features,", "= self.policy(x, a) v = self.value_function(x, a) return pi, logp, logp_pi, v class", "a): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x, a) return pi,", "Discrete from .agents import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from", "CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x,", ") def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v =", "mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi,", "__init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0],", "as nn from gym.spaces import Box, Discrete from .agents import MLP, CNN, WorldModel", "output_activation=None, output_squeeze=True ) def forward(self, x, a): pi, logp, logp_pi = self.policy(x, a)", "pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None,", "import torch.nn as nn from gym.spaces import Box, Discrete from .agents import MLP,", "Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features,", "class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__()", "= MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x, a=None):", "isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function", "GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu,", "flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space, Box): self.policy =", "activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi, logp, logp_pi =", "__init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is", "is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0])", "output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v =", "self.policy(x, a) v = self.value_function(x, a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module):", "a) v = self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self,", "return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh,", "class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__()", "self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function =", "cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None):", "ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if", "class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy", "CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if", "action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self,", "= policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) +", "activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a): pi, logp, logp_pi = self.policy(x,", "self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation,", "import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self,", "mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and isinstance(action_space, Discrete):", "self.value_function(x, a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers,", "policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation,", "isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy =", "in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space)", "CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers", "WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class", "activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation", "v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP,", "self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes,", "else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] +", "output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space, Box): self.policy =", ".policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def", "output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self,", "if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel(", "a) v = self.value_function(x, a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def", "CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None,", "logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None,", ".agents import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import", "logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None):", "= GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space,", "WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a): pi, logp,", ") def forward(self, x, a): pi, logp, logp_pi = self.policy(x, a) v =", "policy=None): super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN(", "None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type", "activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space, Box): self.policy", "self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x,", "self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and", "activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def", "list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi =", "logp, logp_pi = self.policy(x, a) v = self.value_function(x, a) return pi, logp, logp_pi,", "import torch import torch.nn as nn from gym.spaces import Box, Discrete from .agents", "elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation,", "logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None):", "def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM(", "self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64,", "and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy", "= CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self,", "self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is", "Box, Discrete from .agents import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP", "MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN,", "v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN,", "v = self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features,", "return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64),", "x, a=None): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x) return pi,", "isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is", "x, a): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x, a) return", "self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def", "policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation,", "output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def", "Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None", "cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None", "is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation,", "import Box, Discrete from .agents import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP,", "= GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None,", "+ [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi, logp,", "in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete): self.policy", "GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True", "pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x, a) return pi, logp,", "output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP(", "forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x) return", "activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True)", "self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN(", "output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN(", "__init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is", "from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None):", "super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers,", "self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers,", "super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function", "CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM", "super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features,", "action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True )", "= CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers,", "Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function =", "self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes,", "hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function", ") elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers,", "activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and isinstance(action_space, Discrete): self.policy", "output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a)", "hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete): self.policy =", "= WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a): pi,", "action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None and", "a=None): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x) return pi, logp,", "def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy", "output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation )", "mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None and", "activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v", "torch import torch.nn as nn from gym.spaces import Box, Discrete from .agents import", "torch.nn as nn from gym.spaces import Box, Discrete from .agents import MLP, CNN,", "gym.spaces import Box, Discrete from .agents import MLP, CNN, WorldModel from .policies import", "cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers +", "action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features]", "activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function =", "pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh,", "+ list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi", "GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space,", "action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes,", "and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type )", "mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers + [1],", "hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation,", "pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x) return pi, logp, logp_pi,", "output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None,", "+ [1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x,", "output_squeeze=True ) def forward(self, x, a): pi, logp, logp_pi = self.policy(x, a) v", "flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x,", "= self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module): def __init__(self, in_features, action_space,", "policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0],", "policy=None): super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP(", "output_squeeze=True ) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v", "= CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation,", "import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN,", "a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None,", "flatten_type=flatten_type ) elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers,", "CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy = policy(in_features, hidden_sizes, activation, output_activation,", "if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation,", "def forward(self, x, a): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x,", "= self.value_function(x, a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers,", "GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and", "Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0], 1,", "forward(self, x, a): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x, a)", ") self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True )", "action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type,", "from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module):", "action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a): pi, logp, logp_pi", "flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True", "and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else: self.policy", "isinstance(action_space, Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif", "logp_pi = self.policy(x, a) v = self.value_function(x) return pi, logp, logp_pi, v class", "hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space,", "v = self.value_function(x, a) return pi, logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self,", "policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes) + [1],", "[1], activation=activation, flatten_type=flatten_type, output_activation=None, output_squeeze=True ) def forward(self, x, a=None): pi, logp, logp_pi", "activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP(", "and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type )", "logp, logp_pi = self.policy(x, a) v = self.value_function(x) return pi, logp, logp_pi, v", "MLP( layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi,", "logp_pi = self.policy(x, a) v = self.value_function(x, a) return pi, logp, logp_pi, v", "policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n,", "cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and isinstance(action_space,", "import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__()", "def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy", "1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a): pi, logp, logp_pi =", "action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation,", "is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyCNN( cnn_layers, mlp_layers, activation, action_space.n, output_activation=output_activation,", "def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a) v = self.value_function(x)", "self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x, a):", "ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if", "= self.policy(x, a) v = self.value_function(x) return pi, logp, logp_pi, v class ActorCriticMLP(nn.Module):", "activation, action_space.n, output_activation=output_activation, flatten_type=flatten_type ) self.value_function = CNN( cnn_layers, mlp_layers + [1], activation=activation,", "activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space, Box):", "elif policy is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation,", "from gym.spaces import Box, Discrete from .agents import MLP, CNN, WorldModel from .policies", "in_features, action_space, hidden_sizes=(64, 64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None", "output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space, Box): self.policy", "layers=[in_features] + list(hidden_sizes) + [1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp,", "nn from gym.spaces import Box, Discrete from .agents import MLP, CNN, WorldModel from", "if policy is None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation,", "action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None and isinstance(action_space, Discrete): self.policy =", "action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten', policy=None): super(ActorCriticCNN, self).__init__() if policy is None and isinstance(action_space,", ") self.value_function = WorldModel( action_space.shape[0], 1, activation=activation, output_activation=None, output_squeeze=True ) def forward(self, x,", "ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box): self.policy =", ".policies import CategoricalPolicyCNN, GaussianPolicyCNN, GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM,", "[1], activation=activation, output_squeeze=True) def forward(self, x, a=None): pi, logp, logp_pi = self.policy(x, a)", "None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n) else:", "Box): self.policy = GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy", "64), activation=torch.tanh, output_activation=None, policy=None): super(ActorCriticMLP, self).__init__() if policy is None and isinstance(action_space, Box):", "isinstance(action_space, Box): self.policy = GaussianPolicyWM( action_space.shape[0], activation=activation, output_activation=output_activation ) self.value_function = WorldModel( action_space.shape[0],", "None and isinstance(action_space, Box): self.policy = GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif", "GaussianPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.shape[0]) elif policy is None and isinstance(action_space, Discrete):", "self.policy = policy(in_features, hidden_sizes, activation, output_activation, action_space) self.value_function = MLP( layers=[in_features] + list(hidden_sizes)", "= GaussianPolicyCNN( cnn_layers, mlp_layers, activation, action_space.shape[0], output_activation=output_activation, flatten_type=flatten_type ) elif policy is None", "is None and isinstance(action_space, Discrete): self.policy = CategoricalPolicyMLP( in_features, hidden_sizes, activation, output_activation, action_dim=action_space.n)", "from .agents import MLP, CNN, WorldModel from .policies import CategoricalPolicyMLP, GaussianPolicyMLP from .policies", "GaussianPolicyWM class ActorCriticWM(nn.Module): def __init__(self, action_space=None, activation=torch.relu, output_activation=None): super(ActorCriticWM, self).__init__() if isinstance(action_space, Box):", "logp, logp_pi, v class ActorCriticCNN(nn.Module): def __init__(self, cnn_layers, mlp_layers, action_space=None, activation=torch.tanh, output_activation=None, flatten_type='flatten'," ]
[ "= 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH", "from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc", "= torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0) return", "str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer", "'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer(", "str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE:", "PIL import Image import pytorch_lightning as pl import torch from torchvision.models import resnet18", "np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}'", "MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net:", "str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet", "Image import pytorch_lightning as pl import torch from torchvision.models import resnet18 from torchvision", "ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str]", "from PIL import Image import pytorch_lightning as pl import torch from torchvision.models import", "= self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int", "0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4),", "std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img) img_torch = torch.stack([transformed_img])", "-> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y", "__init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}'", "BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down',", "= f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet =", "_prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean,", "import numpy as np from PIL import Image import pytorch_lightning as pl import", "import pytorch_lightning as pl import torch from torchvision.models import resnet18 from torchvision import", "self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray,", "resnet18 from torchvision import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self):", "List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]:", "self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path: str):", "= y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name:", "import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000,", "transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True)", "0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img) img_torch = torch.stack([transformed_img]) return img_torch", "pytorch_lightning as pl import torch from torchvision.models import resnet18 from torchvision import transforms", "resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x) h1 =", "['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str", "def forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0) return h1 class Inference:", "def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x):", "path: str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y = self.net(image) #", "int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str:", "class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def", "def run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image =", "int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y = self.net(image)", "= resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x) h1", "1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result,", "initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str) ->", "super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0 =", "4) def forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0) return h1 class", "= transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406],", "PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name:", "_image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform =", "'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name)", "image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([", "self.resnet(x) h1 = self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME: str =", "stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img =", "return h1 class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str =", "str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME,", "def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform", "str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485,", "transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img)", "# NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result)", "as pl import torch from torchvision.models import resnet18 from torchvision import transforms from", "0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img) img_torch", "f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet)", "NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return", "y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str)", "self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0)", "MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand']", "ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])", "PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self,", "str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256),", "import resnet18 from torchvision import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def", "import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet =", "numpy as np from PIL import Image import pytorch_lightning as pl import torch", "ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc =", "MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit',", "= ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]: path:", "で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls]", "transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229,", "from typing import List, Tuple import numpy as np from PIL import Image", "with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray =", "torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0) return h1", "h0 = self.resnet(x) h1 = self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME:", "self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray", "path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている", "f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(),", "import List, Tuple import numpy as np from PIL import Image import pytorch_lightning", "result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def", "ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand',", "from torchvision.models import resnet18 from torchvision import transforms from ml_models.model_initializer import ModelInitializer class", "torchvision.models import resnet18 from torchvision import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule):", "= initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self, image_name: str)", "pl import torch from torchvision.models import resnet18 from torchvision import transforms from ml_models.model_initializer", "import Image import pytorch_lightning as pl import torch from torchvision.models import resnet18 from", "y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls:", "MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME,", "import torch from torchvision.models import resnet18 from torchvision import transforms from ml_models.model_initializer import", "transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456,", "h1 = self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture'", "torchvision import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet", "BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer:", "PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img", "= np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return", "np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self,", "transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ])", "typing import List, Tuple import numpy as np from PIL import Image import", "from torchvision import transforms from ml_models.model_initializer import ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__()", "self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def run(self,", "transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img", "as np from PIL import Image import pytorch_lightning as pl import torch from", "self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0 = self.resnet(x)", "h1 class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt'", "# ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,", "return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def", "transforms.ToTensor(), # PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img =", "0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img) img_torch = torch.stack([transformed_img]) return", "Tuple import numpy as np from PIL import Image import pytorch_lightning as pl", "def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str =", "'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH )", "self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0", "initializer: ModelInitializer = ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names:", "image_name: str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path) with", "decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path:", "torch from torchvision.models import resnet18 from torchvision import transforms from ml_models.model_initializer import ModelInitializer", "'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image", "ModelInitializer class PredPostureNet(pl.LightningModule): def __init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4)", "torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0]", "class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH:", "Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y =", "image = self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす", "run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path)", "cls: int = np.argmax(result) return np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) ->", "def _prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), #", "List, Tuple import numpy as np from PIL import Image import pytorch_lightning as", "return f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的 transforms.Resize(256), transforms.CenterCrop(224),", "= self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので", "# PyTorch公式でもこのmean, stdが推奨されている transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB')", "__init__(self): super().__init__() self.resnet = resnet18(pretrained=True) self.fc = torch.nn.Linear(1000, 4) def forward(self, x): h0", "-> str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([ # ImageNetで学習したモデルを使うときは、256->224の変換が一般的", "= ModelInitializer( BUCKET_NAME, MODEL_SOURCE_NAME, MODEL_FILE_PATH ) self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] =", "str) -> Tuple[np.ndarray, int]: path: str = self._image_file_path(image_name) image = self._prepare_image(path) with torch.no_grad():", "forward(self, x): h0 = self.resnet(x) h1 = self.fc(h0) return h1 class Inference: def", "= self.resnet(x) h1 = self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME: str", "= self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME:", "self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result: np.ndarray = y.softmax(dim=-1).detach().numpy()[0] cls: int =", "str) -> str: return f'media/images/{image_name}' def _prepare_image(self, path: str): transform = transforms.Compose([ #", "np.round(result, decimals=4), self.class_names[cls] def _image_file_path(self, image_name: str) -> str: return f'media/images/{image_name}' def _prepare_image(self,", ") self.net: PredPostureNet = initializer.init_model(network_class=PredPostureNet) self.class_names: List[str] = ['handstand', 'lying_down', 'sit', 'stand'] def", "= 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str = f'ml_models/classify_images/{MODEL_SOURCE_NAME}' initializer: ModelInitializer =", "= self._prepare_image(path) with torch.no_grad(): y = self.net(image) # NOTE: 1行しかないので 0 で次元を落とす result:", "self.fc(h0) return h1 class Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str", "np from PIL import Image import pytorch_lightning as pl import torch from torchvision.models", "'lying_down', 'sit', 'stand'] def run(self, image_name: str) -> Tuple[np.ndarray, int]: path: str =", "0.406], std=[0.229, 0.224, 0.225]) ]) img = Image.open(path).convert('RGB') transformed_img = transform(img) img_torch =", "x): h0 = self.resnet(x) h1 = self.fc(h0) return h1 class Inference: def __init__(self):", "Inference: def __init__(self): BUCKET_NAME: str = 'classify-posture' MODEL_SOURCE_NAME: str = 'posture_4_classes_model.pt' MODEL_FILE_PATH: str" ]
[ "cart element')) def get_base_api_view(): \"\"\" Returns custom pagination class, set in settings \"\"\"", "from typing import Dict, TYPE_CHECKING, Type from django.apps import apps from django.utils.translation import", "model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value,", "from django.utils.translation import ugettext_lazy as _ from ..settings import settings if TYPE_CHECKING: from", "Type from django.apps import apps from django.utils.translation import ugettext_lazy as _ from ..settings", "if TYPE_CHECKING: from django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def", "Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict", "( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers =", "Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path)", "Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class", "pagination class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None:", "settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return", "import apps from django.utils.translation import ugettext_lazy as _ from ..settings import settings if", "class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None: class", "TYPE_CHECKING: from django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer(", "Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\" Returns custom pagination class, set", ") raise Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\" Returns custom pagination", "instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\" Returns", "get_base_api_view(): \"\"\" Returns custom pagination class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW", "element')) def get_base_api_view(): \"\"\" Returns custom pagination class, set in settings \"\"\" BaseAPIView", "set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None: class BaseAPIView:", "model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected", "context=serializer_context ) raise Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\" Returns custom", "ugettext_lazy as _ from ..settings import settings if TYPE_CHECKING: from django.db.models import Model", "django.utils.translation import ugettext_lazy as _ from ..settings import settings if TYPE_CHECKING: from django.db.models", "from django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value:", "= settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class):", "\"\"\" Returns custom pagination class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if", "\"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None: class BaseAPIView: pass return BaseAPIView", "custom pagination class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is", ") def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path,", "def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class", "as _ from ..settings import settings if TYPE_CHECKING: from django.db.models import Model __all__", "import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context:", "from ..settings import settings if TYPE_CHECKING: from django.db.models import Model __all__ = (", "typing import Dict, TYPE_CHECKING, Type from django.apps import apps from django.utils.translation import ugettext_lazy", "__all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ):", "): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if", "'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS", "= apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type", "django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'],", "isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart element'))", "serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise", "if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart", "in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None: class BaseAPIView: pass", "serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\"", "settings if TYPE_CHECKING: from django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view' )", "apps from django.utils.translation import ugettext_lazy as _ from ..settings import settings if TYPE_CHECKING:", "settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView is None: class BaseAPIView: pass return", "TYPE_CHECKING, Type from django.apps import apps from django.utils.translation import ugettext_lazy as _ from", "import settings if TYPE_CHECKING: from django.db.models import Model __all__ = ( 'cart_element_representation_serializer', 'get_base_api_view'", "..settings import settings if TYPE_CHECKING: from django.db.models import Model __all__ = ( 'cart_element_representation_serializer',", "Dict, TYPE_CHECKING, Type from django.apps import apps from django.utils.translation import ugettext_lazy as _", "value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items():", "django.apps import apps from django.utils.translation import ugettext_lazy as _ from ..settings import settings", "= ( 'cart_element_representation_serializer', 'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers", "cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in", "import ugettext_lazy as _ from ..settings import settings if TYPE_CHECKING: from django.db.models import", "apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of", "for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class(", "import Dict, TYPE_CHECKING, Type from django.apps import apps from django.utils.translation import ugettext_lazy as", "of cart element')) def get_base_api_view(): \"\"\" Returns custom pagination class, set in settings", "_ from ..settings import settings if TYPE_CHECKING: from django.db.models import Model __all__ =", "model_class): return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart element')) def", "raise Exception(_('Unexpected type of cart element')) def get_base_api_view(): \"\"\" Returns custom pagination class,", "type of cart element')) def get_base_api_view(): \"\"\" Returns custom pagination class, set in", "def get_base_api_view(): \"\"\" Returns custom pagination class, set in settings \"\"\" BaseAPIView =", "serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class =", "serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context", "Returns custom pagination class, set in settings \"\"\" BaseAPIView = settings.BASE_API_VIEW if BaseAPIView", "return serializer_class( instance=value, context=serializer_context ) raise Exception(_('Unexpected type of cart element')) def get_base_api_view():", "from django.apps import apps from django.utils.translation import ugettext_lazy as _ from ..settings import", "'get_base_api_view' ) def cart_element_representation_serializer( value: Type['Model'], serializer_context: Dict ): serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for", "in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value, model_class): return serializer_class( instance=value, context=serializer_context )", "serializers = settings.ELEMENT_REPRESENTATION_SERIALIZERS for model_path, serializer_class in serializers.items(): model_class = apps.get_model(model_path) if isinstance(value," ]
[ "input_file_name cmd += \" -f \" + filter_path cmd += \" -od .\\\\temp\"", "in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list()", "code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) #", "generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code", "{\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code", "or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file", "+ filter_path cmd += \" -od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd,", "queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if not need_sort: return # topological", "luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code +=", "# generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"]", "= list() def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list()", "name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)):", "input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for", "subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo: input_files = []", "\"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i = file_index elif args[i] ==", "in constuctors: code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions: for", "if args[i] == \"-i\": file_index = i + 1 while file_index < len(args)", "not supported string = \".BeginExtendClass<\" string += class_name + \", \" + base_class_name", ": input directory\") print(\"-o : ouput directory\") def parse_args(args): args_info = ArgsInfo() if", "in functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info,", "= \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer: return", "function_str = \"&\" + class_name + \"::\" + function_name # static function if", "code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1. generate include heads", "else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if not need_sort: return #", "temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer:", "\"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer: return try:", "if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos", "get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i in range(0,", "+ base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code +=", "meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\")) if __name__ == '__main__': run(sys.argv)", "# 3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes", "attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos + 1:epos] break return name #########################################################################################################", "= ArgsInfo() if len(args) == 1: print_help() return args_info for i in range(1,", "make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate", "and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i = file_index", "meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort", "in_map[class_name] = 0 class_map[class_name] = class_meta_info if not need_sort: return # topological sort", "dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue", "base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if", "meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)):", ": list of input files\") print(\"-d : input directory\") print(\"-o : ouput directory\")", "in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if not base_class in edge_map.keys():", "else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") #", "\"\" class MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos = list() def", "= json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or len(jsn) <= 0: return", "i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name,", "map if not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True", "\"::\" + function_name # static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+", "output_file_name): print(\"start to generate:\", output_file_name) # 1. generate include heads codes code =", "len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list() in_map = dict() edge_map =", "run(args): args_info = parse_args(args) output_dir = args_info.output_dir if not output_dir or not check_path_directory(output_dir):", "else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") return", "if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if not", "edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list =", "not os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer: return try: jsn =", "\"&\" + class_name + \"::\" + function_name # static function if jsn[\"is_static\"]: code", "1. generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\")", "+= generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions: for function in functions:", "code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn =", "check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"),", "+ function_name # static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\",", "args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind codes if", "in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i]", "+ 1 i = file_index elif args[i] == \"-o\": args_info.output_dir = args[i +", "code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") return code", "[] output_dir = \"\" input_dir = \"\" class MetaInfo: input_head_files = [] class_base_mapping", "\"\\\", \" + function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\",", "0: queue.append(derived_class_name) new_list = list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list", "ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### #", "+= cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i]", "class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue =", "name = attribute[npos + 1:epos] break return name ######################################################################################################### # generate ######################################################################################################### def", "ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def print_help():", "\">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors: for", "= \"\" input_dir = \"\" class MetaInfo: input_head_files = [] class_base_mapping = dict()", "def sort_dependencies(self): queue = list() in_map = dict() edge_map = dict() need_sort =", "-1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos + 1:epos] break", "directory\") print(\"-o : ouput directory\") def parse_args(args): args_info = ArgsInfo() if len(args) ==", ": ouput directory\") def parse_args(args): args_info = ArgsInfo() if len(args) == 1: print_help()", "codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\")) if __name__", "args[i] == \"-o\": args_info.output_dir = args[i + 1] elif args[i] == \"-d\": args_info.input_dir", "meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0. make temp dir if not", "= \"..\\cppParser.exe\" cmd += \" -i \" + input_file_name cmd += \" -f", "if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if base_class not in", "jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json", "if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str + \")\")", "len(args)): if args[i] == \"-i\": file_index = i + 1 while file_index <", "in class_base_mapping: # multiple inheritance is not supported string = \".BeginExtendClass<\" string +=", "cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes by dependencies", "meta_info) # generate lua bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir)", "jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)): attribute =", "= [] class_base_mapping = dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <=", "edge_map = dict() need_sort = False class_map = dict() # refresh class base", "print(\"-i : list of input files\") print(\"-d : input directory\") print(\"-o : ouput", "elif args[i] == \"-o\": args_info.output_dir = args[i + 1] elif args[i] == \"-d\":", "registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void", "def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list() in_map =", "print_help() return args_info for i in range(1, len(args)): if args[i] == \"-i\": file_index", "0: code += \" ,\" if param[\"is_const\"]: code += \"const \" code +=", "string = \".BeginExtendClass<\" string += class_name + \", \" + base_class_name + \">\"", "file for i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate", "+ get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" +", "jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0,", "return buffer = open(temp_path).read() if not buffer: return try: jsn = json.loads(buffer) except:", "!= -1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos + 1:epos]", "write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def", "+ ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def", "= glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for path in ret: args_info.input_files.append(path)", "+ \">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break", "in base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map", "code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions: for function in", "for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code +=", "class_name = jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0:", "base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string)", "print(\"-help: display help\") print(\"-i : list of input files\") print(\"-d : input directory\")", "temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to generate lua_register code temp_path =", "def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i in", "meta_info.sort_dependencies() # 3. generate lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code", "len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind", "jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") else:", "######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params =", "> 0: for path in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input", "range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): #", ".\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to", "cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4.", "+ class_name + \"::\" + function_name # static function if jsn[\"is_static\"]: code =", "if functions: for function in functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\")", "args_info.output_dir = args[i + 1] elif args[i] == \"-d\": args_info.input_dir = args[i +", "need_sort = False class_map = dict() # refresh class base mapping for class_meta_info", "if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for class_name in new_queue: new_list.append(class_map[class_name])", "code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name,", "os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind codes if not meta_info.is_empty(): if", "= \"&\" + class_name + \"::\" + function_name # static function if jsn[\"is_static\"]:", "buffer = open(temp_path).read() if not buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc()", "= queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in", "queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]:", "in range(1, len(args)): if args[i] == \"-i\": file_index = i + 1 while", "function_name+ \"\\\", \" + function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+", "+ cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies() #", "def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params: for", "cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include ' +", "edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] ==", "+ cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code", "= list() while len(queue) > 0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name)", "for i in range(1, len(args)): if args[i] == \"-i\": file_index = i +", "meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i \" + input_file_name cmd +=", "if params: for i in range(0, len(params)): param = params[i] if i >", "static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str", "string += class_name + \", \" + base_class_name + \">\" string += \"(\\\"\"", "[option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list of input", "in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in", "-f \" + filter_path cmd += \" -od .\\\\temp\" cmd += \" -on", "function_name+ \"\\\", \" + function_str + \")\") return code def generate_class_meta(mete_info, jsn): code", "output_dir = args_info.output_dir if not output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir", "code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params: for i in", "lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list of", "directory\") def parse_args(args): args_info = ArgsInfo() if len(args) == 1: print_help() return args_info", "= [] output_dir = \"\" input_dir = \"\" class MetaInfo: input_head_files = []", "filter_path = \"filter.json\" class ArgsInfo: input_files = [] output_dir = \"\" input_dir =", "for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info", "code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\")", "in_map = dict() edge_map = dict() need_sort = False class_map = dict() #", "# 2. parse meta.json to generate lua_register code temp_path = \"./temp/temp.json\" if not", "len(args) == 1: print_help() return args_info for i in range(1, len(args)): if args[i]", "if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1", "cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) +", "base_class_name in class_base_mapping: # multiple inheritance is not supported string = \".BeginExtendClass<\" string", "for base_class_name in class_base_mapping: # multiple inheritance is not supported string = \".BeginExtendClass<\"", "input_dir = \"\" class MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos =", "args[i + 1] elif args[i] == \"-d\": args_info.input_dir = args[i + 1] return", "for input_head in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\")", "4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main #########################################################################################################", "if not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove", "new_list = list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir):", "= jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] =", "== 1: print_help() return args_info for i in range(1, len(args)): if args[i] ==", "in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext):", "<= 0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option]", "\".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params: for i in range(0, len(params)):", "if i > 0: code += \" ,\" if param[\"is_const\"]: code += \"const", "break return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" #", "cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code +=", "in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn)", "queue = list() in_map = dict() edge_map = dict() need_sort = False class_map", "print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i", "+= \" ,\" if param[\"is_const\"]: code += \"const \" code += param[\"type\"] code", "\" -od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse", "# generate lua bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info,", "list() in_map = dict() edge_map = dict() need_sort = False class_map = dict()", "args_info.input_dir = args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in", "edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name)", "in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name]", "not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json cmd = \"..\\cppParser.exe\"", "if len(args) == 1: print_help() return args_info for i in range(1, len(args)): if", "derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name)", "codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include ' +", "cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") return code def generate_class_meta(mete_info,", "self.class_base_mapping[class_name] for base_class in base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) #", "+= cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name, \"w\")", "list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0", "# topological sort new_queue = list() while len(queue) > 0: class_name = queue[len(queue)", "list() def parse_meta_info(input_file_name, meta_info): # 0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\")", "class_map = dict() # refresh class base mapping for class_meta_info in self.class_meta_infos: base_classes", "args_info = parse_args(args) output_dir = args_info.output_dir if not output_dir or not check_path_directory(output_dir): return", "+ 1:epos] break return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code =", "+ input_file_name cmd += \" -f \" + filter_path cmd += \" -od", "1 i = file_index elif args[i] == \"-o\": args_info.output_dir = args[i + 1]", "1 while file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index", "supported string = \".BeginExtendClass<\" string += class_name + \", \" + base_class_name +", "constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor) #", "return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or len(jsn)", "topological sort new_queue = list() while len(queue) > 0: class_name = queue[len(queue) -", "class_base_mapping = dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <= 0 def", "generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to generate:\",", "# refresh class base mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name", "# parse input file for i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i,", "parse_meta_info(input_file_name, meta_info): # 0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1.", "for i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua", "+ 1 while file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index =", "meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code +=", "function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str", "v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i :", "range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos", "0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn):", "len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos =", "= \"\" class_name = jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping)", "for base_class in base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set", "+ 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if", "code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code +=", "by dependencies meta_info.sort_dependencies() # 3. generate lua registering codes code += cgu.src_line(\"using namespace", "> 0: for base_class_name in class_base_mapping: # multiple inheritance is not supported string", "== \"-o\": args_info.output_dir = args[i + 1] elif args[i] == \"-d\": args_info.input_dir =", "+= param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"]", "multiple inheritance is not supported string = \".BeginExtendClass<\" string += class_name + \",", "-od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json", "return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage:", "ouput directory\") def parse_args(args): args_info = ArgsInfo() if len(args) == 1: print_help() return", "temp json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if", "######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help:", "+= cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include '", "in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else:", "for i in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos", "if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\")) if __name__ ==", "# multiple inheritance is not supported string = \".BeginExtendClass<\" string += class_name +", "= args[i + 1] elif args[i] == \"-d\": args_info.input_dir = args[i + 1]", "attributes = jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)): attribute = attributes[i]", "except: traceback.print_exc() exit(1) if not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info)", "not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp", "base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if base_class not in self.class_base_mapping.keys():", "code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0,", "in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if not", "output_dir = \"\" input_dir = \"\" class MetaInfo: input_head_files = [] class_base_mapping =", "\", \" + base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\"", "class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes:", "path in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input file for i", "is not supported string = \".BeginExtendClass<\" string += class_name + \", \" +", "\"\" input_dir = \"\" class MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos", "+ \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in constuctors:", "not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind codes if not meta_info.is_empty():", "dict() need_sort = False class_map = dict() # refresh class base mapping for", "code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\"))", ",\" if param[\"is_const\"]: code += \"const \" code += param[\"type\"] code += \"))\"", "file_index = file_index + 1 i = file_index elif args[i] == \"-o\": args_info.output_dir", "function in functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def", "args[i] == \"-d\": args_info.input_dir = args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info):", "jsn[\"member_function\"] if functions: for function in functions: code += generate_class_function(function, class_name) code +=", "if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0:", "sort classes by dependencies meta_info.sort_dependencies() # 3. generate lua registering codes code +=", "for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def", "return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params", "= mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in class_base_mapping: # multiple inheritance", "dependencies meta_info.sort_dependencies() # 3. generate lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\")", "= list() in_map = dict() edge_map = dict() need_sort = False class_map =", "attribute.find(\")\") name = attribute[npos + 1:epos] break return name ######################################################################################################### # generate #########################################################################################################", "+= cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1.", "input_head in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") #", "file_index elif args[i] == \"-o\": args_info.output_dir = args[i + 1] elif args[i] ==", "0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd]", "elif args[i] == \"-d\": args_info.input_dir = args[i + 1] return args_info def parse_jsn_meta_info(jsn,", "file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for", "code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct", "string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else: code", "+ \"::\" + function_name # static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" +", "import traceback import glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\"", "\")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str + \")\")", "in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\")", "= self.class_base_mapping[class_name] for base_class in base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class)", "i in range(1, len(args)): if args[i] == \"-i\": file_index = i + 1", "+= class_name + \", \" + base_class_name + \">\" string += \"(\\\"\" +", "param = params[i] if i > 0: code += \" ,\" if param[\"is_const\"]:", "self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for", "meta_info): # 0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use", "######################################################################################################### def run(args): args_info = parse_args(args) output_dir = args_info.output_dir if not output_dir or", "i > 0: code += \" ,\" if param[\"is_const\"]: code += \"const \"", "open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info = parse_args(args)", "= class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in", "= jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)): attribute", "\" ,\" if param[\"is_const\"]: code += \"const \" code += param[\"type\"] code +=", "-i \" + input_file_name cmd += \" -f \" + filter_path cmd +=", "+= \" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to generate lua_register", "class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name)", "base mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if", "+= cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn)", "if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info", "code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include", "import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo: input_files = [] output_dir", "base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class", "code += \"const \" code += param[\"type\"] code += \"))\" return cgu.src_line(code) def", "= \"filter.json\" class ArgsInfo: input_files = [] output_dir = \"\" input_dir = \"\"", "= \".BeginExtendClass<\" string += class_name + \", \" + base_class_name + \">\" string", "include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code +=", "jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list()", "ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for path in ret:", "\"**/*.h\"), recursive=True) if len(ret) > 0: for path in ret: args_info.input_files.append(path) meta_info =", "\"filter.json\" class ArgsInfo: input_files = [] output_dir = \"\" input_dir = \"\" class", "i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind", "bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\")) if", "def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser", "len(queue) > 0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in", "return # topological sort new_queue = list() while len(queue) > 0: class_name =", "ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input file for i in args_info.input_files:", "\"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code", "def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1. generate include heads codes", "not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\")) if __name__ == '__main__':", "code += cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4))", "meta_info) # 3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"]", "cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head", "+ get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor", "in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos", "+= cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") #", "param[\"is_const\"]: code += \"const \" code += param[\"type\"] code += \"))\" return cgu.src_line(code)", "True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if", "cmd += \" -i \" + input_file_name cmd += \" -f \" +", "\"const \" code += param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name):", "if not output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and", "generate lua bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir,", "generate lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read()", "MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos = list() def is_empty(self): return", "= \"\" class MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos = list()", "cmd += \" -f \" + filter_path cmd += \" -od .\\\\temp\" cmd", "in range(0, len(params)): param = params[i] if i > 0: code += \"", "if param[\"is_const\"]: code += \"const \" code += param[\"type\"] code += \"))\" return", "function_name = jsn[\"name\"] function_str = \"&\" + class_name + \"::\" + function_name #", "cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies() # 3. generate lua registering", "generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file output_file", "= dict() need_sort = False class_map = dict() # refresh class base mapping", "try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or len(jsn) <=", "dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json cmd", "cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code,", "if len(class_base_mapping) > 0: for base_class_name in class_base_mapping: # multiple inheritance is not", "is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list() in_map = dict()", "cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for", "if attributes: for i in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") !=", "if len(ret) > 0: for path in ret: args_info.input_files.append(path) meta_info = MetaInfo() #", "get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name", "code += param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name =", "os import traceback import glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path =", "args_info for i in range(1, len(args)): if args[i] == \"-i\": file_index = i", "+= cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies() # 3. generate lua", "jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or len(jsn) <= 0:", "1:epos] break return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\"", "import glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo:", "class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name", "= attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos + 1:epos] break return name", "parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos =", "generate:\", output_file_name) # 1. generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code", "namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i", "= dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self):", "if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for", "# function functions = jsn[\"member_function\"] if functions: for function in functions: code +=", "args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i = file_index elif", "lua bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir): os.makedirs(output_dir) generate(meta_info, os.path.join(output_dir, \"lua_bind_generated.h\"))", "args_info.output_dir if not output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir", "return args_info for i in range(1, len(args)): if args[i] == \"-i\": file_index =", "len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file os.remove(temp_path)", "i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info,", "i + 1 while file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index", "1] elif args[i] == \"-d\": args_info.input_dir = args[i + 1] return args_info def", "cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include '", "self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if not base_class in edge_map.keys(): edge_map[base_class]", "== 0: queue.append(derived_class_name) new_list = list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos =", "= i + 1 while file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index])", "class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0. make temp dir", "code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read() if not", "list of input files\") print(\"-d : input directory\") print(\"-o : ouput directory\") def", "output_file_name) # 1. generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code +=", "name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params", "1. use cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i", "in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2.", "remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"]", "== \"-i\": file_index = i + 1 while file_index < len(args) and args[file_index][0]", "class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]]", "return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse", "class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if", "# construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code +=", "input directory\") print(\"-o : ouput directory\") def parse_args(args): args_info = ArgsInfo() if len(args)", "new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def", "lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code +=", "= cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include", "glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for path in ret: args_info.input_files.append(path) meta_info", "range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code", "exit(1) if not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) # 3.", "2. parse meta.json to generate lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path):", "0: for base_class_name in class_base_mapping: # multiple inheritance is not supported string =", "+ \")\") return code def generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"]", "+ function_name+ \"\\\", \" + function_str + \")\") return code def generate_class_meta(mete_info, jsn):", "base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if not base_class", "' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies()", "\"-o\": args_info.output_dir = args[i + 1] elif args[i] == \"-d\": args_info.input_dir = args[i", "glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo: input_files", "class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if base_class not in self.class_base_mapping.keys(): continue", "output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret", "continue class_base_info.append(base_class) # set edge map if not base_class in edge_map.keys(): edge_map[base_class] =", "= jsn[\"member_function\"] if functions: for function in functions: code += generate_class_function(function, class_name) code", "+= \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else: code +=", "len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code +=", "= in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for", "0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for", "= open(temp_path).read() if not buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1)", "function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str +", "[cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list of input files\")", "json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn,", "class_base_info.append(base_class) # set edge map if not base_class in edge_map.keys(): edge_map[base_class] = list()", "cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to generate", "print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\")", "Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in", "0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to", "= jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for", "code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") else: code", "MetaInfo() # parse input file for i in args_info.input_files: if not os.path.exists(i): continue", "new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0]", "+= cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)):", "\" code += param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name", "jsn[\"params\"] if params: for i in range(0, len(params)): param = params[i] if i", "= class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if base_class", "if not os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer: return try: jsn", "code = \"\" class_name = jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if", "+ \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str +", "len(params)): param = params[i] if i > 0: code += \" ,\" if", "generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions: for function in functions: code", "functions = jsn[\"member_function\"] if functions: for function in functions: code += generate_class_function(function, class_name)", "jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info)", "code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo: input_files = [] output_dir =", "\"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i in range(0, len(class_meta_infos)): class_meta_info =", "parse_args(args) output_dir = args_info.output_dir if not output_dir or not check_path_directory(output_dir): return input_dir =", "= args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret)", "######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params:", "class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if", "sys import os import traceback import glob import subprocess import code_gen_utils.code_gen_utils as cgu", "<= 0: return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file os.remove(temp_path) def", "check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for path in", "# parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd", "= attribute[npos + 1:epos] break return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn):", "if not buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not", "refresh class base mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name =", "l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\")", "parse_meta_info(i, meta_info) # generate lua bind codes if not meta_info.is_empty(): if not os.path.exists(output_dir):", "list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir)", "4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir = args_info.output_dir", "params = jsn[\"params\"] if params: for i in range(0, len(params)): param = params[i]", "not need_sort: return # topological sort new_queue = list() while len(queue) > 0:", "output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir =", "def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos", "code += cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies() # 3. generate", "arguments:\") print(\"-help: display help\") print(\"-i : list of input files\") print(\"-d : input", "return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in", "file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args):", "shell=True) # 2. parse meta.json to generate lua_register code temp_path = \"./temp/temp.json\" if", "for function in functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code", "params: for i in range(0, len(params)): param = params[i] if i > 0:", "for i in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def", "3. generate lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\")", "class_meta_info if not need_sort: return # topological sort new_queue = list() while len(queue)", "2. sort classes by dependencies meta_info.sort_dependencies() # 3. generate lua registering codes code", "help\") print(\"-i : list of input files\") print(\"-d : input directory\") print(\"-o :", "not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] =", "\"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir", "class_base_mapping: # multiple inheritance is not supported string = \".BeginExtendClass<\" string += class_name", "need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] =", "class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info =", "\" -f \" + filter_path cmd += \" -od .\\\\temp\" cmd += \"", "function functions = jsn[\"member_function\"] if functions: for function in functions: code += generate_class_function(function,", "code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write", "if not need_sort: return # topological sort new_queue = list() while len(queue) >", "cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code +=", "args_info = ArgsInfo() if len(args) == 1: print_help() return args_info for i in", "-on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to generate lua_register code temp_path", "file_index + 1 i = file_index elif args[i] == \"-o\": args_info.output_dir = args[i", "jsn[\"name\"] function_str = \"&\" + class_name + \"::\" + function_name # static function", "function_str + \")\") return code def generate_class_meta(mete_info, jsn): code = \"\" class_name =", "attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos +", "range(0, len(params)): param = params[i] if i > 0: code += \" ,\"", "construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor)", "######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\")", "+= \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\"", "= jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor) # function", "+= cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes by", "base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in class_base_mapping:", "codes code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State*", "edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name]", "\"-i\": file_index = i + 1 while file_index < len(args) and args[file_index][0] !=", "len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0.", "check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\")", "input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if", "= parse_args(args) output_dir = args_info.output_dir if not output_dir or not check_path_directory(output_dir): return input_dir", "1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for class_name in new_queue:", "= False class_map = dict() # refresh class base mapping for class_meta_info in", "print(\"start to generate:\", output_file_name) # 1. generate include heads codes code = cgu.src_line(\"//", "+= generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file", "+= cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) #########################################################################################################", "def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir):", "\"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\" +", "= list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return", "constuctors: code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions: for function", "< len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i", "len(ret) > 0: for path in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse", "attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name =", "# 3. generate lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code +=", "args_info.input_files.append(args[file_index]) file_index = file_index + 1 i = file_index elif args[i] == \"-o\":", "= meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\") code", "class_name + \", \" + base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn)", "once\") code += cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in", "generate lua registering codes code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code", "in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input file for i in", "def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display", "get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors: for constuctor in", "= cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") else: code =", "class_name + \"::\" + function_name # static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\"", "generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params: for i", "parse meta.json to generate lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return", "new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] -", "' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code += cgu.src_line('#include ' + cgu.in_quotes(input_head))", "in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name]", "file_index = i + 1 while file_index < len(args) and args[file_index][0] != \"-\":", "ArgsInfo() if len(args) == 1: print_help() return args_info for i in range(1, len(args)):", "# static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" +", "meta.json to generate lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer", "- 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name]", "cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\"", "constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"]", "cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1. generate", "= params[i] if i > 0: code += \" ,\" if param[\"is_const\"]: code", "not output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir):", "import os import traceback import glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path", "subprocess.call(cmd, shell=True) # 2. parse meta.json to generate lua_register code temp_path = \"./temp/temp.json\"", "\" + filter_path cmd += \" -od .\\\\temp\" cmd += \" -on temp.json\"", "> 0: code += \" ,\" if param[\"is_const\"]: code += \"const \" code", "not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir,", "classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in class_base_mapping: #", "= 0 class_map[class_name] = class_meta_info if not need_sort: return # topological sort new_queue", "\" -on temp.json\" subprocess.call(cmd, shell=True) # 2. parse meta.json to generate lua_register code", "return code def generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"] # base", "use cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i \"", "class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir,", "print(\"-d : input directory\") print(\"-o : ouput directory\") def parse_args(args): args_info = ArgsInfo()", "= list() def parse_meta_info(input_file_name, meta_info): # 0. make temp dir if not os.path.exists(\"./temp\"):", "+= cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for", "file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1", "cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i \" +", "+= \" -od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) # 2.", "param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str", "cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\" + class_name +", "main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir = args_info.output_dir if not output_dir", "temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json", "code += \"))\" return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str =", "\"\\\", \" + function_str + \")\") return code def generate_class_meta(mete_info, jsn): code =", "= True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info", "def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\" + class_name + \"::\"", "cgu.src_line(\"}\") # 4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### #", "# 0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser", "= class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0. make temp", "input files\") print(\"-d : input directory\") print(\"-o : ouput directory\") def parse_args(args): args_info", "def parse_meta_info(input_file_name, meta_info): # 0. make temp dir if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") #", "constuctor in constuctors: code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if functions:", "codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\") code", "\" + function_str + \")\") return code def generate_class_meta(mete_info, jsn): code = \"\"", "\">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else:", "new_queue = list() while len(queue) > 0: class_name = queue[len(queue) - 1] queue.pop()", "cmd += \" -od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True) #", "# 1. use cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd += \"", "= dict() # refresh class base mapping for class_meta_info in self.class_meta_infos: base_classes =", "= jsn[\"params\"] if params: for i in range(0, len(params)): param = params[i] if", "continue parse_meta_info(i, meta_info) # generate lua bind codes if not meta_info.is_empty(): if not", "len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i =", "json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes:", "sort_dependencies(self): queue = list() in_map = dict() edge_map = dict() need_sort = False", "buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn or", "meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0. make temp dir if", "import json import sys import os import traceback import glob import subprocess import", "lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer = open(temp_path).read() if", "i in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos =", "= jsn[\"name\"] function_str = \"&\" + class_name + \"::\" + function_name # static", "+ \"\\\")\" code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name +", "functions: for function in functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return", "edge map if not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort =", "= attribute.find(\")\") name = attribute[npos + 1:epos] break return name ######################################################################################################### # generate", "class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if", "return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list() in_map = dict() edge_map", "= new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext", "\"-d\": args_info.input_dir = args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\"", "code def generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"] # base classf", "class_meta_info[\"name\"] if base_classes: class_base_info = self.class_base_mapping[class_name] for base_class in base_classes: if base_class not", "def parse_args(args): args_info = ArgsInfo() if len(args) == 1: print_help() return args_info for", "len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if not need_sort: return", "######################################################################################################### # main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir = args_info.output_dir if", "print(\"-o : ouput directory\") def parse_args(args): args_info = ArgsInfo() if len(args) == 1:", "def run(args): args_info = parse_args(args) output_dir = args_info.output_dir if not output_dir or not", "os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd +=", "\"\" class_name = jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) >", "\" + function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \"", "dict() edge_map = dict() need_sort = False class_map = dict() # refresh class", "# 1. generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma", "0 def sort_dependencies(self): queue = list() in_map = dict() edge_map = dict() need_sort", "= open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info =", "= cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" + function_str + \")\") return code def", "import subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class ArgsInfo: input_files =", "+ \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"] if constuctors:", "os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes = jsn[\"attributes\"] if attributes: for i", "# base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in", "functions: code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name):", "and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) > 0: for path", "cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors =", "print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list of input files\") print(\"-d :", "set edge map if not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort", "new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return", "generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\" + class_name + \"::\" +", "= file_index elif args[i] == \"-o\": args_info.output_dir = args[i + 1] elif args[i]", "args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys():", "code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" +", "return cgu.src_line(code) def generate_class_function(jsn, class_name): function_name = jsn[\"name\"] function_str = \"&\" + class_name", "attributes: for i in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1:", "input_head_files = [] class_base_mapping = dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos)", "\"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"] for i", "+ function_name+ \"\\\", \" + function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" +", "mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in class_base_mapping: # multiple inheritance is", "json import sys import os import traceback import glob import subprocess import code_gen_utils.code_gen_utils", "code += cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l)", "params[i] if i > 0: code += \" ,\" if param[\"is_const\"]: code +=", "\")\") return code def generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"] #", "break else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\")", "def generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"] # base classf class_base_mapping", "inheritance is not supported string = \".BeginExtendClass<\" string += class_name + \", \"", "\"\\\")\" code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\"", "+ class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors = jsn[\"constuctors\"]", "if constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor) # function functions =", "parse_args(args): args_info = ArgsInfo() if len(args) == 1: print_help() return args_info for i", "attribute[npos + 1:epos] break return name ######################################################################################################### # generate ######################################################################################################### def generate_class_contruct(jsn): code", "class_name): function_name = jsn[\"name\"] function_str = \"&\" + class_name + \"::\" + function_name", "args_info.input_files.append(path) meta_info = MetaInfo() # parse input file for i in args_info.input_files: if", "cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn = meta_info.class_meta_infos[i] code", "return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1])", "+= \"const \" code += param[\"type\"] code += \"))\" return cgu.src_line(code) def generate_class_function(jsn,", "generate_class_meta(mete_info, jsn): code = \"\" class_name = jsn[\"name\"] # base classf class_base_mapping =", "return code def generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1. generate include", "code += cgu.src_line('#include ' + cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes", "need_sort: return # topological sort new_queue = list() while len(queue) > 0: class_name", "class base mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"]", "class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info): # 0. make", "to generate:\", output_file_name) # 1. generate include heads codes code = cgu.src_line(\"// codegen_lua_bind\")", "\" -i \" + input_file_name cmd += \" -f \" + filter_path cmd", "class MetaInfo: input_head_files = [] class_base_mapping = dict() class_meta_infos = list() def is_empty(self):", "ArgsInfo: input_files = [] output_dir = \"\" input_dir = \"\" class MetaInfo: input_head_files", "for path in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input file for", "= list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] =", "meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\" in jsn.keys(): class_meta_infos = jsn[\"class\"]", "+= cgu.src_line(\"using namespace Cjing3D;\") code += cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\")", "list() while len(queue) > 0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if", "generate(meta_info, output_file_name): print(\"start to generate:\", output_file_name) # 1. generate include heads codes code", "edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name]", "+ function_str + \")\") return code def generate_class_meta(mete_info, jsn): code = \"\" class_name", "i = file_index elif args[i] == \"-o\": args_info.output_dir = args[i + 1] elif", "<= 0 def sort_dependencies(self): queue = list() in_map = dict() edge_map = dict()", "queue.append(derived_class_name) new_list = list() for class_name in new_queue: new_list.append(class_map[class_name]) self.class_meta_infos = new_list def", "traceback import glob import subprocess import code_gen_utils.code_gen_utils as cgu filter_path = \"filter.json\" class", "in range(0, len(class_meta_infos)): class_meta_info = class_meta_infos[i] meta_info.class_meta_infos.append(class_meta_info) meta_info.class_base_mapping[class_meta_info[\"name\"]] = list() def parse_meta_info(input_file_name, meta_info):", "class_jsn) code += cgu.src_line(\"\") code += cgu.src_line(\"}\") # 4. write file output_file =", "+ 1] elif args[i] == \"-d\": args_info.input_dir = args[i + 1] return args_info", "generate meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i \" + input_file_name cmd", "for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0:", "list() def is_empty(self): return len(self.class_meta_infos) <= 0 def sort_dependencies(self): queue = list() in_map", "in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind codes", "in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for class_name", "parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name =", "1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] =", "class_jsn = meta_info.class_meta_infos[i] code += cgu.src_line(\"LuaBinder(l)\") code += generate_class_meta(meta_info, class_jsn) code += cgu.src_line(\"\")", "= MetaInfo() # parse input file for i in args_info.input_files: if not os.path.exists(i):", "[] class_base_mapping = dict() class_meta_infos = list() def is_empty(self): return len(self.class_meta_infos) <= 0", "or not check_path_directory(output_dir): return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret =", "in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name] - 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list", "class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name in class_base_mapping: # multiple", "# set edge map if not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name)", "jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name] if len(class_base_mapping) > 0: for base_class_name", "os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <=", "base_class in base_classes: if base_class not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge", "= args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys():", "meta_info = MetaInfo() # parse input file for i in args_info.input_files: if not", "if not base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name]", "input file for i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info) #", "+ \", \" + base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn) +", "0 class_map[class_name] = class_meta_info if not need_sort: return # topological sort new_queue =", "self.class_meta_infos = new_list def get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] +", "recursive=True) if len(ret) > 0: for path in ret: args_info.input_files.append(path) meta_info = MetaInfo()", "filter_path cmd += \" -od .\\\\temp\" cmd += \" -on temp.json\" subprocess.call(cmd, shell=True)", "+= \" -f \" + filter_path cmd += \" -od .\\\\temp\" cmd +=", "of input files\") print(\"-d : input directory\") print(\"-o : ouput directory\") def parse_args(args):", "heads codes code = cgu.src_line(\"// codegen_lua_bind\") code += cgu.src_line(\"#pragma once\") code += cgu.src_line(\"\")", "= args_info.output_dir if not output_dir or not check_path_directory(output_dir): return input_dir = args_info.input_dir if", "return input_dir = args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True)", "len(class_base_mapping) > 0: for base_class_name in class_base_mapping: # multiple inheritance is not supported", "traceback.print_exc() exit(1) if not jsn or len(jsn) <= 0: return parse_jsn_meta_info(jsn, meta_info) #", "os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json cmd = \"..\\cppParser.exe\" cmd", "return parse_jsn_meta_info(jsn, meta_info) # 3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name", "base_class in edge_map.keys(): edge_map[base_class] = list() edge_map[base_class].append(class_name) need_sort = True in_map[class_name] = len(base_classes)", "+= \" -i \" + input_file_name cmd += \" -f \" + filter_path", "\".BeginExtendClass<\" string += class_name + \", \" + base_class_name + \">\" string +=", "= file_index + 1 i = file_index elif args[i] == \"-o\": args_info.output_dir =", "args_info.input_dir if input_dir and check_path_directory(input_dir): ret = glob.glob(os.path.join(input_dir, \"**/*.h\"), recursive=True) if len(ret) >", "\"..\\cppParser.exe\" cmd += \" -i \" + input_file_name cmd += \" -f \"", "os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 ######################################################################################################### # parse #########################################################################################################", "1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"]) if \"class\"", "jsn): code = \"\" class_name = jsn[\"name\"] # base classf class_base_mapping = mete_info.class_base_mapping[class_name]", "to generate meta.json cmd = \"..\\cppParser.exe\" cmd += \" -i \" + input_file_name", "for i in range(0, len(params)): param = params[i] if i > 0: code", "= class_meta_info if not need_sort: return # topological sort new_queue = list() while", "+= cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files: code", "output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main ######################################################################################################### def run(args): args_info", "\" + base_class_name + \">\" string += \"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code", "to generate lua_register code temp_path = \"./temp/temp.json\" if not os.path.exists(temp_path): return buffer =", "os.path.exists(temp_path): return buffer = open(temp_path).read() if not buffer: return try: jsn = json.loads(buffer)", "for constuctor in constuctors: code += generate_class_contruct(constuctor) # function functions = jsn[\"member_function\"] if", "<reponame>maoxiezhao/Cjing3D-Test import json import sys import os import traceback import glob import subprocess", "cgu.src_line(\"\") code += cgu.src_line(\"void luabind_registers_AutoBindFunction(lua_State* l) {\") for i in range(0, len(meta_info.class_meta_infos)): class_jsn", "args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if \"head_name\" in jsn.keys(): meta_info.input_head_files.append(jsn[\"head_name\"])", "= \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if params: for i in range(0,", "queue.pop() new_queue.append(class_name) if class_name in edge_map.keys(): for derived_class_name in edge_map[class_name]: in_map[derived_class_name] = in_map[derived_class_name]", "get_path_file_name(dir): return os.path.basename(dir) def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return", "cgu.in_quotes(input_head)) code += cgu.src_line(\"\") # 2. sort classes by dependencies meta_info.sort_dependencies() # 3.", "mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"] class_name = class_meta_info[\"name\"] if base_classes:", "\" + input_file_name cmd += \" -f \" + filter_path cmd += \"", "not buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if not jsn", "cgu filter_path = \"filter.json\" class ArgsInfo: input_files = [] output_dir = \"\" input_dir", "code += generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start", "parse ######################################################################################################### def print_help(): print(\"lua_bind_parser v0.1.0\") print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\")", "== \"-d\": args_info.input_dir = args[i + 1] return args_info def parse_jsn_meta_info(jsn, meta_info): if", "parse input file for i in args_info.input_files: if not os.path.exists(i): continue parse_meta_info(i, meta_info)", "[params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list of input files\") print(\"-d", "- 1 if in_map[derived_class_name] == 0: queue.append(derived_class_name) new_list = list() for class_name in", "generate ######################################################################################################### def generate_class_contruct(jsn): code = \".AddConstructor(_LUA_ARGS_(\" # params params = jsn[\"params\"] if", "input_files = [] output_dir = \"\" input_dir = \"\" class MetaInfo: input_head_files =", "= attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos = attribute.find(\")\") name", "+= cgu.src_line(\".BeginClass<\" + class_name + \">(\\\"\" + get_class_register_name(jsn) + \"\\\")\") # construct constuctors", "sort new_queue = list() while len(queue) > 0: class_name = queue[len(queue) - 1]", "1: print_help() return args_info for i in range(1, len(args)): if args[i] == \"-i\":", "def change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0", "range(1, len(args)): if args[i] == \"-i\": file_index = i + 1 while file_index", "params params = jsn[\"params\"] if params: for i in range(0, len(params)): param =", "# main ######################################################################################################### def run(args): args_info = parse_args(args) output_dir = args_info.output_dir if not", "class_map[class_name] = class_meta_info if not need_sort: return # topological sort new_queue = list()", "if not os.path.exists(i): continue parse_meta_info(i, meta_info) # generate lua bind codes if not", "cmd = \"..\\cppParser.exe\" cmd += \" -i \" + input_file_name cmd += \"", "= dict() edge_map = dict() need_sort = False class_map = dict() # refresh", "if not os.path.exists(\"./temp\"): os.makedirs(\"./temp\") # 1. use cppparser to generate meta.json cmd =", "i in range(0, len(params)): param = params[i] if i > 0: code +=", "as cgu filter_path = \"filter.json\" class ArgsInfo: input_files = [] output_dir = \"\"", "epos = attribute.find(\")\") name = attribute[npos + 1:epos] break return name ######################################################################################################### #", "open(temp_path).read() if not buffer: return try: jsn = json.loads(buffer) except: traceback.print_exc() exit(1) if", "# 2. sort classes by dependencies meta_info.sort_dependencies() # 3. generate lua registering codes", "dict() # refresh class base mapping for class_meta_info in self.class_meta_infos: base_classes = class_meta_info[\"base_class\"]", "False class_map = dict() # refresh class base mapping for class_meta_info in self.class_meta_infos:", "jsn[\"constuctors\"] if constuctors: for constuctor in constuctors: code += generate_class_contruct(constuctor) # function functions", "+= generate_class_function(function, class_name) code += cgu.src_line(\".EndClass();\") return code def generate(meta_info, output_file_name): print(\"start to", "= len(base_classes) else: queue.append(class_name) in_map[class_name] = 0 class_map[class_name] = class_meta_info if not need_sort:", "display help\") print(\"-i : list of input files\") print(\"-d : input directory\") print(\"-o", "while len(queue) > 0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name", "> 0: class_name = queue[len(queue) - 1] queue.pop() new_queue.append(class_name) if class_name in edge_map.keys():", "attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\") != -1: npos = attribute.find(\"(\") epos = attribute.find(\")\")", "0: for path in ret: args_info.input_files.append(path) meta_info = MetaInfo() # parse input file", "code += \" ,\" if param[\"is_const\"]: code += \"const \" code += param[\"type\"]", "+ function_str + \")\") else: code = cgu.src_line(\".AddMethod(\\\"\" + function_name+ \"\\\", \" +", "class ArgsInfo: input_files = [] output_dir = \"\" input_dir = \"\" class MetaInfo:", "args[i] == \"-i\": file_index = i + 1 while file_index < len(args) and", "import sys import os import traceback import glob import subprocess import code_gen_utils.code_gen_utils as", "print(\"usage: lua_bind [option] [cmd] [params]\") print(\"cmd arguments:\") print(\"-help: display help\") print(\"-i : list", "!= \"-\": args_info.input_files.append(args[file_index]) file_index = file_index + 1 i = file_index elif args[i]", "npos = attribute.find(\"(\") epos = attribute.find(\")\") name = attribute[npos + 1:epos] break return", "# 4. write file output_file = open(output_file_name, \"w\") output_file.write(cgu.format_source(code, 4)) ######################################################################################################### # main", "classes by dependencies meta_info.sort_dependencies() # 3. generate lua registering codes code += cgu.src_line(\"using", "= jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)): attribute = attributes[i] if", "files\") print(\"-d : input directory\") print(\"-o : ouput directory\") def parse_args(args): args_info =", "# params params = jsn[\"params\"] if params: for i in range(0, len(params)): param", "jsn[\"attributes\"] if attributes: for i in range(0, len(attributes)): attribute = attributes[i] if attribute.find(\"LUA_BINDER_NAME\")", "function_name # static function if jsn[\"is_static\"]: code = cgu.src_line(\".AddFunction(\\\"\" + function_name+ \"\\\", \"", "code += cgu.src_line(\"\") code += cgu.src_line('#include ' + cgu.in_quotes(\"luaHelper\\luaBinder.h\")) for input_head in meta_info.input_head_files:", "\"(\\\"\" + get_class_register_name(jsn) + \"\\\")\" code += cgu.src_line(string) break else: code += cgu.src_line(\".BeginClass<\"", "while file_index < len(args) and args[file_index][0] != \"-\": args_info.input_files.append(args[file_index]) file_index = file_index +", "change_path_extension(dir, ext): return os.path.splitext(dir)[0] + ext def check_path_directory(dir): return len(os.path.splitext(dir)[1]) <= 0 #########################################################################################################", "not in self.class_base_mapping.keys(): continue class_base_info.append(base_class) # set edge map if not base_class in", "3. remove temp json file os.remove(temp_path) def get_class_register_name(jsn): name = jsn[\"name\"] attributes =" ]
[ "= pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for i", "import pandas as pd, numpy, math, random, DecisionTree from collections import Counter \"\"\"", "= {i:tmp.copy() for i in range(count)} self.labels = {i:[] for i in range(count)}", "labels[r])) for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True),", "= math.floor(random.random() * self.count) # adds key value pair to data, labels #", "62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] = .8", "data, distinct): output = [] output = [dt.classify(data) for dt in self.forest] print(output)", "key value pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index,", "row.drop('retweet_count') retVal = forest.predict(row, True) if retVal != val: incorrect = incorrect +", "tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)} self.labels = {i:[] for i", "testDat['sentiment'] = -1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True) # for", "decision tree Trains model based on given dataset \"\"\" def __init__(self, count=5): testDat=", "0 tmp = pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy()", "in range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest]", "self.data = {i:tmp.copy() for i in range(count)} self.labels = {i:[] for i in", "int(len(data)/3) for i in range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :])", "output.append(x.classify(data)) if distinct: return [word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if", "distinct): output = [] output = [dt.classify(data) for dt in self.forest] print(output) #", "= 0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] =", "testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True) # for i, data_point in", "\"\"\" class RandomForest: \"\"\" Creates random forest from a decision tree Trains model", "prec * int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05) def train(self,", "for i in range(count)} self.labels = {i:[] for i in range(count)} self.forest =", "= 0 tmp = pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data =", "data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] =", "print(output) # for x in self.forest: # output.append(x.classify(data)) if distinct: return [word for", "row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True) if retVal != val: incorrect", "return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping = True): # for i,", "testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data", "tmp = tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)} self.labels = {i:[]", "in index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1)", "# data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count']", "= .8 test = pd.Series(testDat) forest.predict(test, True) # for i, data_point in enumerate(data):", "in range(count)} self.labels = {i:[] for i in range(count)} self.forest = [None for", "adds key value pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata)", "\"__main__\": forest = RandomForest(count = 49) ## train forest csv_data = pd.read_csv('final_data.csv') labels", "= i assigned_tree = math.floor(random.random() * self.count) # adds key value pair to", "# output.append(x.classify(data)) if distinct: return [word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output))", "i in data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random() * self.count) #", "if __name__ == \"__main__\": forest = RandomForest(count = 49) ## train forest csv_data", "index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i]", "return [word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\":", "anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest from a decision tree Trains", "= csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data", "# for i, data_point in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td", "for i in range(count)] self.count = count def round_to(self, n, prec): return prec", "self.round_to(n, 0.05) def train(self, data, labels, bootstrapping = True): # for i, data", "for i, data_point in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td =", "pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for i in", "[dt.classify(data) for dt in self.forest] print(output) # for x in self.forest: # output.append(x.classify(data))", "tmp = pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for", "'Discovered: ', str(retVal), 'err rate so far: ', str(incorrect)) print(\"Error rate: \" +", "0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index = [0]) tmp = tmp.drop(0)", "= int(len(data)/3) for i in range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest,", "= row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True) if retVal != val:", "self.forest[i].build_tree() def predict(self, data, distinct): output = [] output = [dt.classify(data) for dt", "data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in", "RandomForest: \"\"\" Creates random forest from a decision tree Trains model based on", "i in range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index =", "testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test", "# assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for", "pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] =", "True): # for i, data in enumerate(data): for i in data.iterrows(): index, rowdata", "td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0, len(td)): row =", "return prec * int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05) def", "count def round_to(self, n, prec): return prec * int( n/prec+.5 ) def round_to_5(self,", "for i in range(count)} self.forest = [None for i in range(count)] self.count =", "enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0", "in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count = 49)", "# test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat=", "= 49) ## train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data =", "if retVal != val: incorrect = incorrect + 1 print('Real: ', str(val), 'Discovered:", "value pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index]))", "bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data", "for i in range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index", "test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment']", "RandomForest(count = 49) ## train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data", "<filename>src/old_code/RandomForestDriver.py<gh_stars>1-10 import pandas as pd, numpy, math, random, DecisionTree from collections import Counter", "i assigned_tree = math.floor(random.random() * self.count) # adds key value pair to data,", "= pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output", "as pd, numpy, math, random, DecisionTree from collections import Counter \"\"\" @author: anmirjan", "in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self,", "= RandomForest(count = 49) ## train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count']", "@author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest from a decision tree", "= {i:[] for i in range(count)} self.forest = [None for i in range(count)]", "count=5): testDat= {} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment']", "data, labels, bootstrapping = True): # for i, data in enumerate(data): for i", "testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test,", "0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index = [0])", "word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count =", "def __init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] =", "{i:tmp.copy() for i in range(count)} self.labels = {i:[] for i in range(count)} self.forest", "= data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest):", "assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x", "given dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers'] =", "from collections import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random", "incorrect = incorrect + 1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate", "data_point in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect", "for dt in self.forest] print(output) # for x in self.forest: # output.append(x.classify(data)) if", "n, prec): return prec * int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n,", "# for x in self.forest: # output.append(x.classify(data)) if distinct: return [word for word,", "= DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output = [] output =", "i, data in enumerate(data): for i in data.iterrows(): index, rowdata = i assigned_tree", "a decision tree Trains model based on given dataset \"\"\" def __init__(self, count=5):", "output = [] output = [dt.classify(data) for dt in self.forest] print(output) # for", "{i:[] for i in range(count)} self.forest = [None for i in range(count)] self.count", "self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for i,", "tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def", "in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect =", "', str(retVal), 'err rate so far: ', str(incorrect)) print(\"Error rate: \" + str(incorrect/len(td)))", "= incorrect + 1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate so", "= self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i in range(0,", "# for i, data in enumerate(data): for i in data.iterrows(): index, rowdata =", "= test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101", "forest.predict(test, True) # for i, data_point in enumerate(data): # assert forest.predict(data) is labels[i]", "data in enumerate(data): for i in data.iterrows(): index, rowdata = i assigned_tree =", "if bootstrapping: treesPerForest = int(len(data)/3) for i in range(0, self.count): data = data.sample(frac=1)", "i in range(count)} self.forest = [None for i in range(count)] self.count = count", "int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data, labels,", "= tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)} self.labels = {i:[] for", "test = pd.Series(testDat) forest.predict(test, True) # for i, data_point in enumerate(data): # assert", "-1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True) # for i, data_point", "= pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) #", "to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping:", "self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r]))", "random forest from a decision tree Trains model based on given dataset \"\"\"", "for r in index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x =", "dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers'] = 0", "tree Trains model based on given dataset \"\"\" def __init__(self, count=5): testDat= {}", "= test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] =", "= [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)} self.labels", "def train(self, data, labels, bootstrapping = True): # for i, data in enumerate(data):", ":]) index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for i, tree", "0.05) def train(self, data, labels, bootstrapping = True): # for i, data in", "if distinct: return [word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__", "self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output = [] output", "based on given dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following'] = 0", "train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data,", "in range(0, len(td)): row = td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal", "* int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data,", "enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data,", "= 0 for x in range(0, len(td)): row = td.iloc[x] val = row['retweet_count']", "pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction", "= count def round_to(self, n, prec): return prec * int( n/prec+.5 ) def", "[None for i in range(count)] self.count = count def round_to(self, n, prec): return", "self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i in", "from a decision tree Trains model based on given dataset \"\"\" def __init__(self,", "5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test = pd.Series(testDat)", "in range(count)} self.forest = [None for i in range(count)] self.count = count def", "= True): # for i, data in enumerate(data): for i in data.iterrows(): index,", "= csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') #", "bootstrapping: treesPerForest = int(len(data)/3) for i in range(0, self.count): data = data.sample(frac=1) self.data[i]", "= td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True) if", "[0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)} self.labels =", "= 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index = [0]) tmp =", "__name__ == \"__main__\": forest = RandomForest(count = 49) ## train forest csv_data =", "print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0, len(td)): row", "Creates random forest from a decision tree Trains model based on given dataset", "testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp", "0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat,", "labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0, len(td)):", "val: incorrect = incorrect + 1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err", "!= val: incorrect = incorrect + 1 print('Real: ', str(val), 'Discovered: ', str(retVal),", "pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0, len(td)): row = td.iloc[x] val", "[word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest", "dt in self.forest] print(output) # for x in self.forest: # output.append(x.classify(data)) if distinct:", "labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] #", "random, DecisionTree from collections import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\"", ") def round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping =", "= [dt.classify(data) for dt in self.forest] print(output) # for x in self.forest: #", "prediction # test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count'])", "in self.forest: # output.append(x.classify(data)) if distinct: return [word for word, word_count in Counter(output).most_common(2)][0]", "Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count = 49) ##", "row = row.drop('retweet_count') retVal = forest.predict(row, True) if retVal != val: incorrect =", "', str(val), 'Discovered: ', str(retVal), 'err rate so far: ', str(incorrect)) print(\"Error rate:", "testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] =", "x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output = [] output = [dt.classify(data) for", "testDat['sentiment'] = 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index = [0]) tmp", "## train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1)", "x in range(0, len(td)): row = td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count')", "train(self, data, labels, bootstrapping = True): # for i, data in enumerate(data): for", "testDat= {} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] =", "[] output = [dt.classify(data) for dt in self.forest] print(output) # for x in", "= 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp =", "# self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3)", "distinct: return [word for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ ==", "incorrect = 0 for x in range(0, len(td)): row = td.iloc[x] val =", "collections import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest", "# adds key value pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] =", "bootstrapping = True): # for i, data in enumerate(data): for i in data.iterrows():", "True) # for i, data_point in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\")", "in data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random() * self.count) # adds", "True) if retVal != val: incorrect = incorrect + 1 print('Real: ', str(val),", "i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree()", "# labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620", "# prediction # test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data =", "{} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0", "= self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for", "self.count = count def round_to(self, n, prec): return prec * int( n/prec+.5 )", "labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest =", "1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate so far: ', str(incorrect))", "= pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following']", ".8 test = pd.Series(testDat) forest.predict(test, True) # for i, data_point in enumerate(data): #", "DecisionTree from collections import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates", "= 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] =", "def round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping = True):", "math.floor(random.random() * self.count) # adds key value pair to data, labels # self.data[assigned_tree].append((index,", "self.count) # adds key value pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree]", "== \"__main__\": forest = RandomForest(count = 49) ## train forest csv_data = pd.read_csv('final_data.csv')", "testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index", "__init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] = 0", "predict(self, data, distinct): output = [] output = [dt.classify(data) for dt in self.forest]", "round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping = True): #", "enumerate(data): for i in data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random() *", "data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv')", "= [] output = [dt.classify(data) for dt in self.forest] print(output) # for x", "forest from a decision tree Trains model based on given dataset \"\"\" def", "* self.count) # adds key value pair to data, labels # self.data[assigned_tree].append((index, rowdata))", "range(count)} self.forest = [None for i in range(count)] self.count = count def round_to(self,", "row = td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True)", "= 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test =", "pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output =", "0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification'] = 0", "\"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest from a decision", "testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1 testDat['classification']", "i, data_point in enumerate(data): # assert forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv')", "str(val), 'Discovered: ', str(retVal), 'err rate so far: ', str(incorrect)) print(\"Error rate: \"", "forest.predict(row, True) if retVal != val: incorrect = incorrect + 1 print('Real: ',", "range(0, len(td)): row = td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal =", "rowdata = i assigned_tree = math.floor(random.random() * self.count) # adds key value pair", "retVal != val: incorrect = incorrect + 1 print('Real: ', str(val), 'Discovered: ',", "data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest", "self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] =", "Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest from a", "axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output = []", "forest.train(data, labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count']", "n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping", "forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels,", "pd.Series(testDat) forest.predict(test, True) # for i, data_point in enumerate(data): # assert forest.predict(data) is", "data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r,", "49) ## train forest csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'],", "labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction #", "def round_to(self, n, prec): return prec * int( n/prec+.5 ) def round_to_5(self, n):", "self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i in range(0, self.count):", "in enumerate(data): for i in data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random()", "{} testDat['following'] = 62620 testDat['followers'] = 5987 testDat['tweets_count'] = 43101 testDat['sentiment'] = -1", "import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest: \"\"\" Creates random forest from", "for x in range(0, len(td)): row = td.iloc[x] val = row['retweet_count'] row =", "for x in self.forest: # output.append(x.classify(data)) if distinct: return [word for word, word_count", "val = row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True) if retVal !=", "i in range(count)} self.labels = {i:[] for i in range(count)} self.forest = [None", "self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count = 49) ## train forest", "testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count'] = 0 testDat['sentiment'] = 0 testDat['classification']", "axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') # labels =", "csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data = pd.read_csv('verified_test.csv') # labels", "self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for", "self.forest] print(output) # for x in self.forest: # output.append(x.classify(data)) if distinct: return [word", "output = [dt.classify(data) for dt in self.forest] print(output) # for x in self.forest:", "csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True) # prediction # test_data =", "= forest.predict(row, True) if retVal != val: incorrect = incorrect + 1 print('Real:", "0 for x in range(0, len(td)): row = td.iloc[x] val = row['retweet_count'] row", "for i, data in enumerate(data): for i in data.iterrows(): index, rowdata = i", "class RandomForest: \"\"\" Creates random forest from a decision tree Trains model based", "Trains model based on given dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following']", "def predict(self, data, distinct): output = [] output = [dt.classify(data) for dt in", "labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers']", "range(0, self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for", "self.forest: # output.append(x.classify(data)) if distinct: return [word for word, word_count in Counter(output).most_common(2)][0] return", "return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count = 49) ## train", "= 43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True)", "n): return self.round_to(n, 0.05) def train(self, data, labels, bootstrapping = True): # for", "test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {} testDat['following'] = 62620 testDat['followers'] = 5987", "= 0 testDat['sentiment'] = 0 testDat['classification'] = 0 tmp = pd.DataFrame(testDat, index =", "on given dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers']", "self.count): data = data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r", "self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i in range(0, self.count): data", "range(count)} self.labels = {i:[] for i in range(count)} self.forest = [None for i", "\"\"\" def __init__(self, count=5): testDat= {} testDat['following'] = 0 testDat['followers'] = 0 testDat['tweets_count']", "= data.sample(frac=1) self.data[i] = self.data[i].append(data.iloc[1:treesPerForest, :]) index = data.index.values.astype(int)[1:treesPerForest] for r in index:", "range(count)] self.count = count def round_to(self, n, prec): return prec * int( n/prec+.5", "= [None for i in range(count)] self.count = count def round_to(self, n, prec):", "forest = RandomForest(count = 49) ## train forest csv_data = pd.read_csv('final_data.csv') labels =", "print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate so far: ', str(incorrect)) print(\"Error", "\"\"\" Creates random forest from a decision tree Trains model based on given", "= pd.Series(testDat) forest.predict(test, True) # for i, data_point in enumerate(data): # assert forest.predict(data)", "x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct):", "assigned_tree = math.floor(random.random() * self.count) # adds key value pair to data, labels", "i in range(count)] self.count = count def round_to(self, n, prec): return prec *", "is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0,", "len(td)): row = td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row,", "pd, numpy, math, random, DecisionTree from collections import Counter \"\"\" @author: anmirjan \"\"\"", "43101 testDat['sentiment'] = -1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True) #", "for word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest =", "= -1 testDat['classification'] = .8 test = pd.Series(testDat) forest.predict(test, True) # for i,", "data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random() * self.count) # adds key", "in range(count)] self.count = count def round_to(self, n, prec): return prec * int(", "model based on given dataset \"\"\" def __init__(self, count=5): testDat= {} testDat['following'] =", "forest.predict(data) is labels[i] print(\"Completed\") td = pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in", "data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x", "test_data = pd.read_csv('verified_test.csv') # labels = test_data['retweet_count'] # data = test_data.drop(['retweet_count']) testDat= {}", "= pd.read_csv('Final_Test_Data.csv') incorrect = 0 for x in range(0, len(td)): row = td.iloc[x]", "= row.drop('retweet_count') retVal = forest.predict(row, True) if retVal != val: incorrect = incorrect", "for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0, axis=1) self.forest[i] = DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze())", "retVal = forest.predict(row, True) if retVal != val: incorrect = incorrect + 1", "r in index: self.labels[i].append((r, labels[r])) for i, tree in enumerate(self.forest): x = pd.DataFrame(self.labels[i]).drop(0,", "rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i", "round_to(self, n, prec): return prec * int( n/prec+.5 ) def round_to_5(self, n): return", "math, random, DecisionTree from collections import Counter \"\"\" @author: anmirjan \"\"\" class RandomForest:", "DecisionTree.DecisionTree(self.data[i].reset_index(drop=True), x.squeeze()) self.forest[i].build_tree() def predict(self, data, distinct): output = [] output = [dt.classify(data)", "labels, bootstrapping = True): # for i, data in enumerate(data): for i in", "pair to data, labels # self.data[assigned_tree].append((index, rowdata)) self.data[assigned_tree] = self.data[assigned_tree].append(rowdata) self.labels[assigned_tree].append((index, labels[index])) if", "labels[index])) if bootstrapping: treesPerForest = int(len(data)/3) for i in range(0, self.count): data =", "self.forest = [None for i in range(count)] self.count = count def round_to(self, n,", "word, word_count in Counter(output).most_common(2)][0] return self.round_to_5(sum(output)/len(output)) if __name__ == \"__main__\": forest = RandomForest(count", "x in self.forest: # output.append(x.classify(data)) if distinct: return [word for word, word_count in", "index, rowdata = i assigned_tree = math.floor(random.random() * self.count) # adds key value", "treesPerForest = int(len(data)/3) for i in range(0, self.count): data = data.sample(frac=1) self.data[i] =", "td.iloc[x] val = row['retweet_count'] row = row.drop('retweet_count') retVal = forest.predict(row, True) if retVal", "csv_data = pd.read_csv('final_data.csv') labels = csv_data['retweet_count'] data = csv_data.drop(['retweet_count'], axis=1) forest.train(data, labels, bootstrapping=True)", "self.labels = {i:[] for i in range(count)} self.forest = [None for i in", "in self.forest] print(output) # for x in self.forest: # output.append(x.classify(data)) if distinct: return", "incorrect + 1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate so far:", "prec): return prec * int( n/prec+.5 ) def round_to_5(self, n): return self.round_to(n, 0.05)", "numpy, math, random, DecisionTree from collections import Counter \"\"\" @author: anmirjan \"\"\" class", "index = data.index.values.astype(int)[1:treesPerForest] for r in index: self.labels[i].append((r, labels[r])) for i, tree in", "pandas as pd, numpy, math, random, DecisionTree from collections import Counter \"\"\" @author:", "for i in data.iterrows(): index, rowdata = i assigned_tree = math.floor(random.random() * self.count)", "index = [0]) tmp = tmp.drop(0) self.data = {i:tmp.copy() for i in range(count)}", "+ 1 print('Real: ', str(val), 'Discovered: ', str(retVal), 'err rate so far: '," ]
[ "np.ndarray): shape = A.shape[0] mid = shape // 2 C = np.empty([shape, shape])", "= np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo: int, hi:", "C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo: int,", "matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid = shape // 2 C", "shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo: int, hi: int): if", "B: np.ndarray): shape = A.shape[0] mid = shape // 2 C = np.empty([shape,", "A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray,", "matMulAux(mid + 1, shape) def matMulAux(lo: int, hi: int): if lo == hi:", "matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo: int, hi: int): if lo", "shape = A.shape[0] mid = shape // 2 C = np.empty([shape, shape]) matMulAux(0,", "size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid = shape", "4]) B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape =", "// 2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def", "np A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def matMul(A:", "as np A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def", "mid = shape // 2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid +", "+ 1, shape) def matMulAux(lo: int, hi: int): if lo == hi: pass", "size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape", "2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo:", "B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0]", "= A.shape[0] mid = shape // 2 C = np.empty([shape, shape]) matMulAux(0, mid)", "<gh_stars>0 import numpy as np A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10,", "mid) matMulAux(mid + 1, shape) def matMulAux(lo: int, hi: int): if lo ==", "np.ndarray, B: np.ndarray): shape = A.shape[0] mid = shape // 2 C =", "A.shape[0] mid = shape // 2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid", "import numpy as np A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4,", "4]) def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid = shape //", "shape // 2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape)", "= shape // 2 C = np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1,", "= np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B:", "np.empty([shape, shape]) matMulAux(0, mid) matMulAux(mid + 1, shape) def matMulAux(lo: int, hi: int):", "numpy as np A = np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4])", "def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid = shape // 2", "= np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid", "np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray): shape = A.shape[0] mid =", "np.random.randint(10, size=[4, 4]) B = np.random.randint(10, size=[4, 4]) def matMul(A: np.ndarray, B: np.ndarray):" ]
[]
[ "input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError): PCATransformer(n_components=bad_components).fit(X)", "-*- \"\"\"Tests for PCATransformer.\"\"\" import numpy as np import pytest from sktime.transformations.panel.pca import", "= _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError): PCATransformer(n_components=bad_components).fit(X) else: with pytest.raises(ValueError):", "-1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad input", "# -*- coding: utf-8 -*- \"\"\"Tests for PCATransformer.\"\"\" import numpy as np import", "import numpy as np import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import", "sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11])", "exception is raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if", "PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components):", "11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad input args.\"\"\" X", "import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception", "numpy as np import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array", "-*- coding: utf-8 -*- \"\"\"Tests for PCATransformer.\"\"\" import numpy as np import pytest", "test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10),", "import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def", "raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str):", "from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check", "utf-8 -*- \"\"\"Tests for PCATransformer.\"\"\" import numpy as np import pytest from sktime.transformations.panel.pca", "_make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError): PCATransformer(n_components=bad_components).fit(X) else: with pytest.raises(ValueError): PCATransformer(n_components=bad_components).fit(X)", "for PCATransformer.\"\"\" import numpy as np import pytest from sktime.transformations.panel.pca import PCATransformer from", "sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that", "X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError): PCATransformer(n_components=bad_components).fit(X) else: with", "args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError): PCATransformer(n_components=bad_components).fit(X) else:", "is raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components,", "[\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for", "@pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised", "from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1,", "def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad input args.\"\"\" X =", "1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad", "for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with", "bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1) if isinstance(bad_components, str): with pytest.raises(TypeError):", "pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2,", "PCATransformer.\"\"\" import numpy as np import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel", "\"\"\"Tests for PCATransformer.\"\"\" import numpy as np import pytest from sktime.transformations.panel.pca import PCATransformer", "-1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is raised for bad input args.\"\"\"", "\"\"\"Check that exception is raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10,", "that exception is raised for bad input args.\"\"\" X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=1)", "np import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\",", "_make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2, -1.2, -1, 11]) def test_bad_input_args(bad_components): \"\"\"Check that exception is", "import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\", [\"str\", 1.2,", "coding: utf-8 -*- \"\"\"Tests for PCATransformer.\"\"\" import numpy as np import pytest from", "as np import pytest from sktime.transformations.panel.pca import PCATransformer from sktime.utils._testing.panel import _make_nested_from_array @pytest.mark.parametrize(\"bad_components\"," ]
[ "import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class =", "<gh_stars>1-10 from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book", "IsAuthenticated from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer", "import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes = (IsAuthenticated,)", "from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from", "from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all()", "from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class", "rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet):", "Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer", "import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset", "rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers", "src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class", "import IsAuthenticated from rest_framework.viewsets import ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import", "ModelViewSet from src.apps.books.models import Book from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset =", "src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes =", "from src.apps.books.serializers import BookSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer permission_classes" ]
[ "import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def", "self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename,", "myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5) base.accept('d', myvr.list_devices)", "if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if", "left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\")", "= ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left =", "P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename", "if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model", "self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right')", "model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide() right_pose =", "= None self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir,", "print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix", "self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right", "main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left", "= self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand)", "4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand", "0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right,", "ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left')", "self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand')", "is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else:", "right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\")", "if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model", "self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def", "import ShowBase from panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import", "else: if self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix", "= self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state:", "4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1,", "None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if", "self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if", "1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if", "left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand", "self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger", "= self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right =", "self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if", "self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right", "= self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand =", "self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device", "self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not", "\"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right", "1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0,", "self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix =", "None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left", "self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix)", "= self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is", "import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand", "left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle)", "device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose", "model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None:", "openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None:", "self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger", "= loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide()", "ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5)", "= self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self):", "self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None:", "self.right_hand is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init()", "def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4,", "import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand =", "1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is", "loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide() right_pose", "is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if", "from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self)", "model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide() base =", "def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left =", "= self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right =", "= self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger =", "loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide() base", "= MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5) base.accept('d', myvr.list_devices) base.accept('b',", "None self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\")", "MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5) base.accept('d', myvr.list_devices) base.accept('b', base.bufferViewer.toggleEnable)", "right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid:", "os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left')", "self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render)", "is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model", "filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left", "self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\")", "= loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide()", "= self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand =", "if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show()", "right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand", "class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def init_action(self):", "init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left')", "from direct.showbase.ShowBase import ShowBase from panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import", "left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if", "self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\")", "from panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class", "left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model =", "if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger)", "self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left)", "MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def init_action(self): main_dir", "None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if", "self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr", "self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1,", "0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose = self.get_action_pose(self.action_pose_left) if left_pose.pose.bPoseIsValid: left_matrix = self.get_pose_modelview(left_pose.pose)", "self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device =", "= ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10,", "self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not", "None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\")", "self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand", "self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid:", "self.left_hand = None self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename =", "self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right =", "right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model =", "= self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device", "None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is", "if self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix =", "self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True)", "self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger')", "model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix) else: if self.right_hand is not None: self.right_hand.hide() base = ShowBase()", "= None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\") filename = os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\")", "else: if self.right_hand is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr =", "print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state:", "1, openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4,", "self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand", "model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right)", "panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR):", "update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1,", "p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand", "self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1)", "base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0,", "self.left_hand is not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose)", "if self.right_hand is not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR()", "self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state,", "if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show()", "import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None", "def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def init_action(self): main_dir =", "\"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right')", "self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left = self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right')", "self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand')", "P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None", "not None: self.left_hand.hide() right_pose = self.get_action_pose(self.action_pose_right) if right_pose.pose.bPoseIsValid: right_matrix = self.get_pose_modelview(right_pose.pose) if self.right_hand", "openvr.k_ulInvalidInputValueHandle) right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1,", "is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else:", "myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5) base.accept('d', myvr.list_devices) base.accept('b', base.bufferViewer.toggleEnable) base.run()", "self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger')", "= self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) left_pose =", "right_trigger_state, device = self.get_digital_action_rising_edge(self.action_right_trigger) if right_trigger_state: print(\"RIGHT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_right, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle)", "= self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device =", "model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is not None:", "base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model = loader.loadModel(\"panda\") model.reparentTo(render) model.setPos(0, 10, -5) base.accept('d',", "direct.showbase.ShowBase import ShowBase from panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr", "openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand =", "self.right_hand is None: self.right_hand = self.tracking_space.attach_new_node('right-hand') model = loader.loadModel(\"box\") model.reparent_to(self.right_hand) model.set_scale(0.1) self.right_hand.show() self.right_hand.set_mat(right_matrix)", "self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left,", "= self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand)", "self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger = self.vr_input.getActionHandle('/actions/demo/in/left_trigger') self.action_right_trigger = self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger)", "not None: self.right_hand.hide() base = ShowBase() base.setFrameRateMeter(True) myvr = MinimalOpenVR() myvr.init() model =", "= os.path.join(main_dir, \"demo_actions.json\") self.load_action_manifest(filename, \"/actions/demo\") self.action_haptic_left = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Left') self.source_left = self.vr_input.getInputSourceHandle('/user/hand/left') self.action_pose_left =", "= self.vr_input.getActionHandle('/actions/demo/in/right_trigger') def update_action(self): left_trigger_state, device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0,", "= self.vr_input.getActionHandle('/actions/demo/in/Hand_Left') self.action_haptic_right = self.vr_input.getActionHandle('/actions/demo/out/Haptic_Right') self.source_right = self.vr_input.getInputSourceHandle('/user/hand/right') self.action_pose_right = self.vr_input.getActionHandle('/actions/demo/in/Hand_Right') self.action_left_trigger =", "device = self.get_digital_action_rising_edge(self.action_left_trigger) if left_trigger_state: print(\"LEFT\") self.vr_input.triggerHapticVibrationAction(self.action_haptic_left, 0, 1, 4, 1, openvr.k_ulInvalidInputValueHandle) right_trigger_state,", "self.get_pose_modelview(left_pose.pose) if self.left_hand is None: self.left_hand = self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1)", "__init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def init_action(self): main_dir = ExecutionEnvironment.getEnvironmentVariable(\"MAIN_DIR\")", "ShowBase from panda3d.core import ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os", "ExecutionEnvironment from p3dopenvr.p3dopenvr import P3DOpenVR import openvr import os class MinimalOpenVR(P3DOpenVR): def __init__(self):", "os class MinimalOpenVR(P3DOpenVR): def __init__(self): P3DOpenVR.__init__(self) self.left_hand = None self.right_hand = None def", "= self.tracking_space.attach_new_node('left-hand') model = loader.loadModel(\"box\") model.reparent_to(self.left_hand) model.set_scale(0.1) self.left_hand.show() self.left_hand.set_mat(left_matrix) else: if self.left_hand is" ]
[ "Dictionary from a seqp Vocabulary. It manipulates the Dictionary's internal state to avoid", "We clear up the internal state to write it from scratch (and without", "the Dictionary's internal state to avoid reserving token 0 for Lua compatibility in", "to avoid reserving token 0 for Lua compatibility in order to respect the", "ImportError: assert False, \"Fairseq is needed for seqp integration with fairseq!\" from seqp.vocab", "from scratch (and without # the Lua heritage token zero, to keep token", "it from scratch (and without # the Lua heritage token zero, to keep", "Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary from a seqp Vocabulary. It", "Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary", "source tree. try: from fairseq.data import Dictionary except ImportError: assert False, \"Fairseq is", "Vocabulary. :param vocab: Vocabulary to convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol", "in the original Vocabulary. :param vocab: Vocabulary to convert to Dictionary. :return: Resulting", "# # This source code is licensed under the license found in the", "ID associations in the original Vocabulary. :param vocab: Vocabulary to convert to Dictionary.", "# the Lua heritage token zero, to keep token IDs) dictionary.symbols = []", "for Lua compatibility in order to respect the token ID associations in the", "clear up the internal state to write it from scratch (and without #", "needed for seqp integration with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary)", "internal state to avoid reserving token 0 for Lua compatibility in order to", "0 for Lua compatibility in order to respect the token ID associations in", "in the LICENSE file in # the root directory of this source tree.", "1 # frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index", "# All rights reserved. # # This source code is licensed under the", "Vocabulary to convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol", "the original Vocabulary. :param vocab: Vocabulary to convert to Dictionary. :return: Resulting Dictionary.", "Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol =", "state to write it from scratch (and without # the Lua heritage token", "= [] dictionary.indices = {} dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency", "# the root directory of this source tree. try: from fairseq.data import Dictionary", "under the license found in the LICENSE file in # the root directory", "dictionary.count = [] dictionary.indices = {} dictionary.nspecial = 3 for symbol in vocab.idx2symbol:", "All rights reserved. # # This source code is licensed under the license", "[] dictionary.indices = {} dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency =", "LICENSE file in # the root directory of this source tree. try: from", "= Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the internal state to write", "# We clear up the internal state to write it from scratch (and", "in # the root directory of this source tree. try: from fairseq.data import", "of this source tree. try: from fairseq.data import Dictionary except ImportError: assert False,", "file in # the root directory of this source tree. try: from fairseq.data", "directory of this source tree. try: from fairseq.data import Dictionary except ImportError: assert", "Dictionary: \"\"\" Creates a fairseq Dictionary from a seqp Vocabulary. It manipulates the", "symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency info is not available dictionary.add_symbol(symbol,", "from a seqp Vocabulary. It manipulates the Dictionary's internal state to avoid reserving", "a seqp Vocabulary. It manipulates the Dictionary's internal state to avoid reserving token", "dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the internal state to", "-> Dictionary: \"\"\" Creates a fairseq Dictionary from a seqp Vocabulary. It manipulates", "with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates", "<NAME> # All rights reserved. # # This source code is licensed under", "a fairseq Dictionary from a seqp Vocabulary. It manipulates the Dictionary's internal state", "\"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol,", "manipulates the Dictionary's internal state to avoid reserving token 0 for Lua compatibility", "vocab.idx2symbol: unknown_frequency = 1 # frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index", "available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id dictionary.unk_index = vocab.unk_id return", "= 1 # frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id", "keep token IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices = {} dictionary.nspecial", "vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up", "fairseq Dictionary from a seqp Vocabulary. It manipulates the Dictionary's internal state to", "assert False, \"Fairseq is needed for seqp integration with fairseq!\" from seqp.vocab import", "vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the internal state", "IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices = {} dictionary.nspecial = 3", "rights reserved. # # This source code is licensed under the license found", "dictionary.symbols = [] dictionary.count = [] dictionary.indices = {} dictionary.nspecial = 3 for", "licensed under the license found in the LICENSE file in # the root", ":return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id]", "tree. try: from fairseq.data import Dictionary except ImportError: assert False, \"Fairseq is needed", "= vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the internal", "# This source code is licensed under the license found in the LICENSE", "(and without # the Lua heritage token zero, to keep token IDs) dictionary.symbols", "except ImportError: assert False, \"Fairseq is needed for seqp integration with fairseq!\" from", "heritage token zero, to keep token IDs) dictionary.symbols = [] dictionary.count = []", "dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id dictionary.unk_index = vocab.unk_id return dictionary", "= vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol)", "the license found in the LICENSE file in # the root directory of", "Dictionary except ImportError: assert False, \"Fairseq is needed for seqp integration with fairseq!\"", "the Lua heritage token zero, to keep token IDs) dictionary.symbols = [] dictionary.count", "license found in the LICENSE file in # the root directory of this", "the root directory of this source tree. try: from fairseq.data import Dictionary except", "info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id dictionary.unk_index", "respect the token ID associations in the original Vocabulary. :param vocab: Vocabulary to", "pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol,", "seqp integration with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary:", "2019-present, <NAME> # All rights reserved. # # This source code is licensed", "order to respect the token ID associations in the original Vocabulary. :param vocab:", "Creates a fairseq Dictionary from a seqp Vocabulary. It manipulates the Dictionary's internal", "= vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear", "Lua compatibility in order to respect the token ID associations in the original", "source code is licensed under the license found in the LICENSE file in", "is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id dictionary.unk_index =", "this source tree. try: from fairseq.data import Dictionary except ImportError: assert False, \"Fairseq", ":param vocab: Vocabulary to convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol =", "to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol", "frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id", "\"Fairseq is needed for seqp integration with fairseq!\" from seqp.vocab import Vocabulary def", "token ID associations in the original Vocabulary. :param vocab: Vocabulary to convert to", "state to avoid reserving token 0 for Lua compatibility in order to respect", "code is licensed under the license found in the LICENSE file in #", "to respect the token ID associations in the original Vocabulary. :param vocab: Vocabulary", "convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id]", "try: from fairseq.data import Dictionary except ImportError: assert False, \"Fairseq is needed for", "Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary =", "= 3 for symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency info is", "reserved. # # This source code is licensed under the license found in", "from fairseq.data import Dictionary except ImportError: assert False, \"Fairseq is needed for seqp", "seqp Vocabulary. It manipulates the Dictionary's internal state to avoid reserving token 0", "in order to respect the token ID associations in the original Vocabulary. :param", "fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a", "to convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id] eos_symbol =", "zero, to keep token IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices =", "for symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency info is not available", "[] dictionary.count = [] dictionary.indices = {} dictionary.nspecial = 3 for symbol in", "import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary from", "Dictionary's internal state to avoid reserving token 0 for Lua compatibility in order", "Vocabulary. It manipulates the Dictionary's internal state to avoid reserving token 0 for", "the LICENSE file in # the root directory of this source tree. try:", "reserving token 0 for Lua compatibility in order to respect the token ID", "associations in the original Vocabulary. :param vocab: Vocabulary to convert to Dictionary. :return:", "to write it from scratch (and without # the Lua heritage token zero,", "avoid reserving token 0 for Lua compatibility in order to respect the token", "This source code is licensed under the license found in the LICENSE file", "= [] dictionary.count = [] dictionary.indices = {} dictionary.nspecial = 3 for symbol", "found in the LICENSE file in # the root directory of this source", "scratch (and without # the Lua heritage token zero, to keep token IDs)", "up the internal state to write it from scratch (and without # the", "\"\"\" Creates a fairseq Dictionary from a seqp Vocabulary. It manipulates the Dictionary's", "for seqp integration with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) ->", "is needed for seqp integration with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab:", "# Copyright (c) 2019-present, <NAME> # All rights reserved. # # This source", "<filename>seqp/integration/fairseq/dictionary.py # Copyright (c) 2019-present, <NAME> # All rights reserved. # # This", "Copyright (c) 2019-present, <NAME> # All rights reserved. # # This source code", "integration with fairseq!\" from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\"", "not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index = vocab.eos_id dictionary.unk_index = vocab.unk_id", "unknown_frequency = 1 # frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index =", "def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary from a seqp", "token IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices = {} dictionary.nspecial =", "to keep token IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices = {}", "Lua heritage token zero, to keep token IDs) dictionary.symbols = [] dictionary.count =", "False, \"Fairseq is needed for seqp integration with fairseq!\" from seqp.vocab import Vocabulary", "Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the internal state to write it", "unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We clear up the", "in vocab.idx2symbol: unknown_frequency = 1 # frequency info is not available dictionary.add_symbol(symbol, unknown_frequency)", "It manipulates the Dictionary's internal state to avoid reserving token 0 for Lua", "{} dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency", "# frequency info is not available dictionary.add_symbol(symbol, unknown_frequency) dictionary.pad_index = vocab.pad_id dictionary.eos_index =", "compatibility in order to respect the token ID associations in the original Vocabulary.", "without # the Lua heritage token zero, to keep token IDs) dictionary.symbols =", "eos=eos_symbol) # We clear up the internal state to write it from scratch", "root directory of this source tree. try: from fairseq.data import Dictionary except ImportError:", "fairseq.data import Dictionary except ImportError: assert False, \"Fairseq is needed for seqp integration", "the internal state to write it from scratch (and without # the Lua", "is licensed under the license found in the LICENSE file in # the", "token zero, to keep token IDs) dictionary.symbols = [] dictionary.count = [] dictionary.indices", "dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency info", "internal state to write it from scratch (and without # the Lua heritage", "seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary", "token 0 for Lua compatibility in order to respect the token ID associations", "the token ID associations in the original Vocabulary. :param vocab: Vocabulary to convert", "dictionary.indices = {} dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency = 1", "= {} dictionary.nspecial = 3 for symbol in vocab.idx2symbol: unknown_frequency = 1 #", "from seqp.vocab import Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq", "3 for symbol in vocab.idx2symbol: unknown_frequency = 1 # frequency info is not", "original Vocabulary. :param vocab: Vocabulary to convert to Dictionary. :return: Resulting Dictionary. \"\"\"", "write it from scratch (and without # the Lua heritage token zero, to", "vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary from a seqp Vocabulary.", "import Dictionary except ImportError: assert False, \"Fairseq is needed for seqp integration with", "vocab.idx2symbol[vocab.pad_id] eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) #", "(c) 2019-present, <NAME> # All rights reserved. # # This source code is", "Vocabulary def vocab_to_dictionary(vocab: Vocabulary) -> Dictionary: \"\"\" Creates a fairseq Dictionary from a", "vocab: Vocabulary to convert to Dictionary. :return: Resulting Dictionary. \"\"\" pad_symbol = vocab.idx2symbol[vocab.pad_id]", "eos_symbol = vocab.idx2symbol[vocab.eos_id] unk_symbol = vocab.idx2symbol[vocab.unk_id] dictionary = Dictionary(pad=pad_symbol, unk=unk_symbol, eos=eos_symbol) # We", "unk=unk_symbol, eos=eos_symbol) # We clear up the internal state to write it from" ]
[ "[True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials:", "cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host", "(can't run actions on it). Cluster has 1 service added. \"\"\" cluster =", "tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS", "_wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each to be finished (results", "Unless required by applicable law or agreed to in writing, software # distributed", "version ADCM with a lot of different objects. Upgrade ADCM. Run actions on", "above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts,", "remove every 4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) ->", "str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\")", "providers, hosts, tasks @allure.step('Create a lot of simple clusters') def create_simple_clusters( self, adcm_client:", "def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM images\"\"\" return", "cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to", "= self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one", "def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with many different objects:", "cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty", "on component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action'])", "after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) #", "f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle", "bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT:", "services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components", "ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create", "the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from", "adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True)", "manipulated (you can run actions on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo", "'service_id': service.id, 'component_id': component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id),", "host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert", "that Jobs have correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create", "upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that actions availability from old DSL", "use it more than 1 time). :returns: Create provider and hosts create tasks", "adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait for", "it). Cluster has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name)", "in providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:] for host in provider.host_list()", "supply hosts for complex clusters (all hosts created by provider action and taken", "by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions", "objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], )", "action, run actions on some of hosts and then delete multiple of them", "bundle Create many clusters: - With one service and launched action on component", "= service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service", "obj.reread() actions = {action.name for action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS", "@contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they aren't changed", "'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create", "and check that they aren't changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict:", ") -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create", "Upload complex_provider and complex_cluster Create two complex providers: 1. Provider that supply hosts", "action on component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component =", "action :returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters = 34 params =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm]", "least on of simple clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject)", "None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to be\" with catch_failed(ObjectNotFound,", "Cluster: \"\"\"Create cluster with one service and config history\"\"\" def get_random_config_map() -> dict:", "actions \"\"\" with allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all services')", "import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string", "clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster,", "cluster @allure.step(\"Run actions on provider's hosts and remove every 4th host by action", "_assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class", "adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object),", "config of cluster, service and component - With two services and launched cluster", "Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\")", "cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient,", "get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs: List[Job] =", "fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with many", "cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\",", "* 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE", "Bundle, created clusters and tasks \"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config':", "not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait()", "# Components # on cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT =", "cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks on provider to", "[True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials:", "with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on", "_ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for", "time). :returns: Create provider and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider", "it may break 'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for tasks')", "previous version ADCM with a lot of different objects. Upgrade ADCM. Run actions", "service: Service, components: dict, hosts: tuple): \"\"\"Utility function to run actions on components", "software # distributed under the License is distributed on an \"AS IS\" BASIS,", "-> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with old and new version", "allure.step('Add two services to clusters and run action on them'): for install_cluster_with_two_services in", "complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded':", "many different objects: bundles, clusters, providers, hosts, jobs. All jobs are waited to", "and \"stable\" properties - objects can be manipulated (you can run actions on", "in provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create a lot of simple", "object to one big dict Useful for dirty upgrade \"\"\" return { 'name_or_fqdn':", "-> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to be\" with", "dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id", "objects didn't loose their configs and \"stable\" properties - objects can be manipulated", "create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]:", "sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject):", "dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with", "host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service:", "test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None:", ") with allure.step('Add two services to clusters and run action on them'): for", "on provider's hosts and remove every 4th host by action on host\") def", "\"Only one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"):", "range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) ==", "upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade( self,", "def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) ->", "hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in providers ]", "run actions on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"'", "and launched cluster install action :returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters", "# fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with", "clusters of previous version 3. Run dummy actions on both of them 4.", "allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service", "self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run", "old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade =", "= cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"):", "dummy actions on each second host and delete each fourth host after tasks", "List, Iterable, Any import allure import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects", "def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True)", "and config history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass':", "_check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\",", "import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service,", "Jobs have correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple", "be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:])", "Path from typing import Tuple, Union, List, Iterable, Any import allure import pytest", "host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy", "# pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import contextmanager from pathlib import", "and finished jobs 2. Cluster with config history (on cluster, one service and", "self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want", "actions on some of hosts and then delete multiple of them by host", "-> None: \"\"\"Test that actions availability from old DSL remains the same after", "1. Cluster with all services and finished jobs 2. Cluster with config history", "= bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions =", "to be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def", "bundle: Bundle) -> Cluster: \"\"\"Create cluster with one service and config history\"\"\" def", "\"\"\"Create cluster with one service and config history\"\"\" def get_random_config_map() -> dict: return", "Not configured cluster just with hosts and one service added :returns: Tuple with", "upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) ->", "@allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action in", "/ \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters,", "} cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'):", "upgradable clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) ->", "host and delete each fourth host after tasks are finished\"\"\" hosts = tuple(provider.host_list())", "= 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self,", "- With two services and launched cluster install action :returns: Bundle, created clusters", "'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [", "{ 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured':", "that previously created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert", "clusters and run action on component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component'])", "with allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component'])", "to one big dict Useful for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name", "all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE)", "adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def", "allure.step('Run actions on the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts)", "of one of providers and one of hosts Run failed actions on 3", "create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload", "} # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm(", "not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type:", "cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs:", "Upload simple_provider bundle Create 10 providers and 20 hosts on each provider Change", "upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM:", "= one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for", "simple_clusters), None, ) if cluster_with_job is None: raise ValueError('At least on of simple", "encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff)", "@pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI", "get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in jobs} yield with allure.step('Assert that", "frozen_objects = {job.job_id: extract_job_info(job) for job in jobs} yield with allure.step('Assert that Jobs", "cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1,", "TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient)", "cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create", "== AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created", "indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], )", "create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\"", "return cluster @allure.step(\"Run actions on provider's hosts and remove every 4th host by", "ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None,", "to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str =", "obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs:", "\"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in", "not use this file except in compliance with the License. # You may", "upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr,", "old and new version with possibility of upgrade 2. Create two clusters of", "Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility function to run actions on", "}, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\",", "allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add", "ADCM with many different objects: bundles, clusters, providers, hosts, jobs. All jobs are", "ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider =", "'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts':", "want to wait for tasks on provider to be finished (for hosts to", "if visibility is changed, it may break 'actions': set(action.id for action in adcm_object.action_list()),", "_create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) ->", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "= _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM", "and run action on component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component:", "ADCMClient): \"\"\"Freeze jobs and check that they aren't changed after upgrade\"\"\" def extract_job_info(job:", "in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider and", "hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id in (", "BREAD_SERVICE = 'bread_service' # Components # on cheese MILK_COMPONENT = 'milk' # on", "{'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich',", "no-self-use, too-many-arguments import random from contextlib import contextmanager from pathlib import Path from", "bundle Create 10 providers and 20 hosts on each provider Change config of", "agreed to in writing, software # distributed under the License is distributed on", "# limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments", "and 20 hosts on each provider Change config of one of providers and", ") cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two", ") jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in jobs}", "hosts and one service added :returns: Tuple with provider and cluster objects in", "history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with one service and", "Run dummy actions on both of them 4. Upgrade one of clusters :returns:", "self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in", "with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service", "run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with", "for hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def", "with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster,", "amount of hosts. Cluster is not configured (can't run actions on it). Cluster", "of an object to one big dict Useful for dirty upgrade \"\"\" return", "def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config", "cluster, one service and its components) 3. Not configured cluster just with hosts", "all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return {", "good_old_cluster @allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history:", "if cluster_with_job is None: raise ValueError('At least on of simple clusters should have", ":returns: Dictionary with providers, clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) /", "install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts", "clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with prefix \"{template}\" by action')", "-> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2,", "2. Cluster with config history (on cluster, one service and its components) 3.", "comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path )", "def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one", "'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info,", "\"\"\" with allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag':", "{'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id),", "Cluster with config history (on cluster, one service and its components) 3. Not", "action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available", "clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one service to", "= Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir )", "simple_cluster bundle Create many clusters: - With one service and launched action on", "config history (on cluster, one service and its components) 3. Not configured cluster", "create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles", "@allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None:", "= cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service", "tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for", "cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore", "from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task, Job, Upgrade", "Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers and 20", "bundles with old and new version with possibility of upgrade 2. Create two", "from typing import Tuple, Union, List, Iterable, Any import allure import pytest from", "range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name} and add hosts to", ") -> None: \"\"\"Test that actions availability from old DSL remains the same", "to in writing, software # distributed under the License is distributed on an", "config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config", "implied. # See the License for the specific language governing permissions and #", "dirty_adcm: dict, ): \"\"\" Create previous version ADCM with a lot of different", ":returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters = 34 params = {", "Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two complex", "dict Useful for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name')", "service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]],", "cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT),", "upgraded cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory /", "ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str],", "Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with old and new", "dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that actions availability from old", "with allure.step('Assert that Jobs have correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id),", "history (on cluster, one service and its components) 3. Not configured cluster just", "on both of them 4. Upgrade one of clusters :returns: Tuple with upgraded", "host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider,", "Apache License, Version 2.0 (the \"License\"); # you may not use this file", "upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that", "dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze", "= [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) ->", "= 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations}", "service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to clusters and run action on", "images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle", "previous version 3. Run dummy actions on both of them 4. Upgrade one", "providers and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path )", "service.id, 'component_id': component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id,", "cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts", "(for hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts", "parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images()", "None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs,", "# See the License for the specific language governing permissions and # limitations", "the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "cluster, add service {service_name} and add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle:", "def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action in obj.action_list()} assert (", "'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service':", "@pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags:", "and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they", "in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history') def", "-> dict: \"\"\" Fill ADCM with many different objects: bundles, clusters, providers, hosts,", "the specific language governing permissions and # limitations under the License. \"\"\"Tests for", "{'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13),", "service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations}", "on: cluster, service, component. Run failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE)", "after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id, 'status': job.status,", "ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str],", "service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts:", "}, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4)", "the Apache License, Version 2.0 (the \"License\"); # you may not use this", "you may not use this file except in compliance with the License. #", "@allure.step('Create a lot of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path", "str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs)", "on of simple clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) ->", "Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create", "one of clusters :returns: Tuple with upgraded cluster and old-version cluster \"\"\" old_version_bundle", "tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one", "[only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str,", "one service and its components) 3. Not configured cluster just with hosts and", "in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service,", "host: Host) -> None: assert len(cluster.host_list()) == 1, \"Only one host expected to", "hosts. Cluster is not configured (can't run actions on it). Cluster has 1", "-> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should", "for the specific language governing permissions and # limitations under the License. \"\"\"Tests", "components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id']))", "actions on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' *", "for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}')", "hosts with prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle, template: str", "in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected:", "= cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service)", "tasks \"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False,", "complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider,", "provider, task @allure.step('Create two complex providers and three complex clusters') def create_complex_providers_and_clusters( self,", "'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle:", "sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle:", "# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may", "cluster: Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility function to run actions", "provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create a lot of simple clusters')", "adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm", "catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils", "job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id", "(you can run actions on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n", "[ host.action(name='install').run() for provider in providers[-2:] for host in provider.host_list() ] return provider_bundle,", "adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from", "template}) return provider, task @allure.step('Create two complex providers and three complex clusters') def", "return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for", "cluster.host_add(host) with allure.step('Run actions on the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service,", "cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\" Run successful actions on: cluster,", "service and change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in", "actions on it). Cluster has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with", "from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component,", "history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc':", "_create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host)", "_create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider", "(cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self,", "= _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True],", "component - With two services and launched cluster install action :returns: Bundle, created", "more than 1 time). :returns: Create provider and hosts create tasks \"\"\" provider", "_ in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run()", "tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list", "def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two", "False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install',", "Create previous version ADCM with a lot of different objects. Upgrade ADCM. Run", "to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'],", "self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of", ") ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple clusters", "complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete", "tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir)", "two clusters of previous version 3. Run dummy actions on both of them", "Dictionary with providers, clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\"", "in providers[-2:] for host in provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create", "'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon'", "on each provider Change config of one of providers and one of hosts", "'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks", "and complex_cluster Create two complex providers: 1. Provider that supply hosts for complex", "Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr,", "build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark =", "import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils", "and component - With two services and launched cluster install action :returns: Bundle,", "them 4. Upgrade one of clusters :returns: Tuple with upgraded cluster and old-version", "Host) -> None: assert len(cluster.host_list()) == 1, \"Only one host expected to be\"", "order that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider,", "config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True],", "2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for", "component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add", "ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that actions availability", "that supply hosts for complex clusters (all hosts created by provider action and", "@pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs:", "returning result dictionary. :returns: Dictionary with providers, clusters and sometimes bundles. \"\"\" dirty_dir", "Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters:", "'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14,", "jobs are waited to be finished before returning result dictionary. :returns: Dictionary with", "actions availability from old DSL remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs,", "cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add", "import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin", "= cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT),", "\"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks", "each second host and delete each fourth host after tasks are finished\"\"\" hosts", "cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE", "{ 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded':", "bundles, clusters, providers, hosts, jobs. All jobs are waited to be finished before", "action on hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers", "AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]:", "ValueError('At least on of simple clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object:", "simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs,", "host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id,", "self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters)", "service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) )", "cluster with one service and config history\"\"\" def get_random_config_map() -> dict: return {", "in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for", "fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff)", "indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], )", "= [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in", "some actions \"\"\" with allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all", "4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run", "cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster with three", "cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE)", "tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts,", "with allure.step('Run actions on the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components,", "created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list()) ==", "@pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with many different", "with upgraded cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory", "host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs:", "jobs} yield with allure.step('Assert that Jobs have correct info'): for job_id, job_info in", "cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, )", "objects can upgrade correctly: - objects didn't loose their configs and \"stable\" properties", "correctly: - objects didn't loose their configs and \"stable\" properties - objects can", "Add three hosts on it Set components on hosts Run some actions \"\"\"", "/ \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good", "'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component':", "jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in jobs} yield", "None, ) if cluster_with_job is None: raise ValueError('At least on of simple clusters", "service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list()) == 1,", "= adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters =", "tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _", "'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': {", "adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\"", "exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list()) == 1, \"Only", "with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\")", "service and config history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25),", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "action in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait`", "'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with", "(hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for", "/ \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers = providers[-2]", "I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run", ") _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None:", "self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for", "break 'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait:", "with one service and config history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text':", "run action on component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component", "-> dict: \"\"\" Save all common fields of an object to one big", "tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with prefix", "dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\",", "self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and", "provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory", "filled with different objects can upgrade correctly: - objects didn't loose their configs", "[True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials:", "self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) -> Cluster:", "cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions", "in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config {config_change_iterations} times\"): service", "should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str,", ") simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster", "'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir", "host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts: tuple):", "lot of different objects. Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed =", "its components) 3. Not configured cluster just with hosts and one service added", "if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None),", "See the License for the specific language governing permissions and # limitations under", "components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc", "@pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient,", "@allure.step('Create two upgradable clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory:", "Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be", "+ [ host.action(name='install').run() for provider in providers[-2:] for host in provider.host_list() ] return", "'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster,", "indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict,", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in", "dict: \"\"\" Fill ADCM with many different objects: bundles, clusters, providers, hosts, jobs.", "be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created", "ADCM filled with different objects can upgrade correctly: - objects didn't loose their", "= [provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:]", "them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload", "have correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers')", "for _ in range(4) ], } def get_component_random_config_map() -> dict: return {'illicium': random.random()}", "'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on cheese MILK_COMPONENT", "upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()],", "job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()}, } comparator", "\"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return", "aren't changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id,", "return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of", "are waited to be finished before returning result dictionary. :returns: Dictionary with providers,", "of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}')", "None: \"\"\"Test that actions availability from old DSL remains the same after update\"\"\"", "with different objects can upgrade correctly: - objects didn't loose their configs and", "sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run actions", "= self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services,", "provider action and taken by clusters) 2. Provider that create multiple hosts via", ") if cluster_with_job is None: raise ValueError('At least on of simple clusters should", "Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient,", "info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers(", ") -> None: \"\"\" Run successful actions on: cluster, service, component. Run failed", "ADCM and expect all objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs,", "Service, components: dict, hosts: tuple): \"\"\"Utility function to run actions on components (host", "on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions on each", "config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with one service", "times\"): component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster,", "clusters and tasks \"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments': 2,", "cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with", "config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change", "List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters: - With one service", "and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks", "objects in order that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\")", "hosts on each provider Change config of one of providers and one of", "upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object,", "provider to be finished (for hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services(", "# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host)", "Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle,", "frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path", "LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE", "on hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers =", "jobs and check that they aren't changed after upgrade\"\"\" def extract_job_info(job: Job) ->", "it more than 1 time). :returns: Create provider and hosts create tasks \"\"\"", "'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa',", "for action in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over", "log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job", "of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1.", "hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster with three services Add", "and its components) 3. Not configured cluster just with hosts and one service", "(provide template if you want to use it more than 1 time). :returns:", "host delete action And three complex clusters: 1. Cluster with all services and", "for provider in providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:] for host", "for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config", "with given amount of hosts. Cluster is not configured (can't run actions on", "service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to clusters", "clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services", "'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4],", "add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service", "with allure.step('Add one service to clusters and run action on component'): for one_service_cluster", "= 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on cheese", "pathlib import Path from typing import Tuple, Union, List, Iterable, Any import allure", "one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config", "simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple clusters where at least one", "with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster:", "action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more')", "Fill ADCM with many different objects: bundles, clusters, providers, hosts, jobs. All jobs", "config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change", "adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with", "License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib", "self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky',", "= sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj:", "params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import (", "Upload two bundles with old and new version with possibility of upgrade 2.", "only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from", "import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools", "catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\")", "cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\"", "action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None: raise ValueError('At least", "providers Run install action on hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir", "job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common fields of", "fourth host after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in", "encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True],", "-> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs,", "def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster", "on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider,", "'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle =", "hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster", "on hosts Run some actions \"\"\" with allure.step('Create cluster and add services'): cluster", "Service, Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils", "def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter", "cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato'", "from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from", "KIND, either express or implied. # See the License for the specific language", "@allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\",", "upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]:", "[provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:] for", "random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)),", "service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service", "return {'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with", "dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs)", "upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade:", "\"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs:", "adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade with encrypted", "sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager", "cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of them') def create_upgradable_clusters(self,", "With one service and altered config of cluster, service and component - With", "for _ in range(amount_of_clusters)] with allure.step('Add one service to clusters and run action", "components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(),", "on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks", ":returns: Tuple with provider and cluster objects in order that is declared above", "\"\"\" Run successful actions on: cluster, service, component. Run failed action on provider.", "int = 18 ) -> Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts", "cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with prefix \"{template}\" by", "{ self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'):", "dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name':", "ANY KIND, either express or implied. # See the License for the specific", "\"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _", "import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task,", "multiple of them by host delete action And three complex clusters: 1. Cluster", "get_config(adcm_object), # if visibility is changed, it may break 'actions': set(action.id for action", "visibility is changed, it may break 'actions': set(action.id for action in adcm_object.action_list()), }", "changed, it may break 'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See", "Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters: - With one", "helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they aren't", "return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person':", "that they aren't changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return {", "Task, Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin", "/ \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster =", "hosts Run some actions \"\"\" with allure.step('Create cluster and add services'): cluster =", "of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle,", "clusters and run action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run())", "= old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade =", "f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service'", "components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id}", "and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) ->", "where at least one job was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list())", "component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config in", "clusters: - With one service and launched action on component - With one", "not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def", "component's config {config_change_iterations} times\"): component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return", "cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts", "Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two complex providers:", "@allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host,", "and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade", "adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers =", "of simple clusters where at least one job was ran\"\"\" cluster_with_job = next(", "with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with", "install action :returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters = 34 params", "assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm(", "old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be", "\"\"\"Test that actions availability from old DSL remains the same after update\"\"\" cluster", "20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' #", "from pathlib import Path from typing import Tuple, Union, List, Iterable, Any import", "- objects can be manipulated (you can run actions on them) \"\"\" LONG_TEXT", "import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag", "am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some", "\"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check", "{'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\",", "with provider and cluster objects in order that is declared above \"\"\" provider_bundle", "services Add three hosts on it Set components on hosts Run some actions", "not configured (can't run actions on it). Cluster has 1 service added. \"\"\"", "old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade()", "Tuple[str, str], ) -> None: \"\"\"Test that actions availability from old DSL remains", "dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous version ADCM with", "itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM,", "sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that actions", "\"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not", "from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed,", "AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = {", "old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0]", "dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir", "hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str", "provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of them') def", "\"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects to", "adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() ->", "*[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(),", "adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload", "under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "launched action on component - With one service and altered config of cluster,", "of them 4. Upgrade one of clusters :returns: Tuple with upgraded cluster and", "one service and launched action on component - With one service and altered", "range(4) ], } def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations = 100", "And three complex clusters: 1. Cluster with all services and finished jobs 2.", "added :returns: Tuple with provider and cluster objects in order that is declared", "upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image", "build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) ->", "Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import", "LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\"", "sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\"", "services and launched cluster install action :returns: Bundle, created clusters and tasks \"\"\"", "{ 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition':", "= 'bread_service' # Components # on cheese MILK_COMPONENT = 'milk' # on sauce", "complex_provider and complex_cluster Create two complex providers: 1. Provider that supply hosts for", "applicable law or agreed to in writing, software # distributed under the License", "objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade(", "host.action(name='install').run() for provider in providers[-2:] for host in provider.host_list() ] return provider_bundle, providers,", "tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from", "ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster", "-> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs:", "be finished (for hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3]", "{'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action':", "CONDITIONS OF ANY KIND, either express or implied. # See the License for", "\"\"\"Utility function to run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( (", "get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\",", "None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service =", "filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is", "status='failed') @allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host,", "jobs 2. Cluster with config history (on cluster, one service and its components)", "hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts and remove every 4th", "complex providers and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path", "writing, software # distributed under the License is distributed on an \"AS IS\"", "cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way", "def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir))", "Iterable, Any import allure import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import", "and wait for each to be finished (results aren't checked)\"\"\" for task in", "2. Provider that create multiple hosts via action, run actions on some of", "cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable", "} with allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run actions on", "compliance with the License. # You may obtain a copy of the License", "{random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create", "!===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with", "for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with", "them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 #", "complex clusters: 1. Cluster with all services and finished jobs 2. Cluster with", ") # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and", "two complex providers and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory:", "= provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return", "clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] )", "sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks =", "ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import", "next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job", "task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two complex providers", "== 1, \"Only one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster", "ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous version", "clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts,", "catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service])", "allure.step('Add one service to clusters and run action on component'): for one_service_cluster in", "one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20)", "hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self,", "{amount_of_hosts} hosts with prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle, template:", "from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils", "adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host')", "pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle,", "and one of hosts Run failed actions on 3 of providers Run install", ").wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], )", "Useful for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else", "( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0],", "int(random.randint(1, 200))} for _ in range(4) ], } def get_component_random_config_map() -> dict: return", "via action (provide template if you want to use it more than 1", "# on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' #", "create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count':", "name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects =", "Any]: \"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir:", "'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field':", "\"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea':", "the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target)", "job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client:", "cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster,", "1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with", ":returns: Tuple with upgraded cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory /", "bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with old and", "for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts:", "config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff(", "Run failed actions on 3 of providers Run install action on hosts of", "provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two", "= 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) ->", "'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed, it may", "for job in jobs} yield with allure.step('Assert that Jobs have correct info'): for", "indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str],", "adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they aren't changed after upgrade\"\"\" def", "\"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials,", "_wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict,", "from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\",", "is None: raise ValueError('At least on of simple clusters should have a job')", "ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create", "cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service =", "(the \"License\"); # you may not use this file except in compliance with", "extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects to be same'), objects_are_not_changed( sdk_client_fs", "@allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle,", "for log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj:", "# Unless required by applicable law or agreed to in writing, software #", "str], ) -> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs,", "by applicable law or agreed to in writing, software # distributed under the", "hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster", "bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in", "\"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str,", "_wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster:", "cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None: raise ValueError('At least on of", "{ 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12),", "def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each to be finished", "simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir)", "= self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters,", "= _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster,", "cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\"", "allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service", "def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility function to", "file except in compliance with the License. # You may obtain a copy", "update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !=====", "@pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict,", "changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id, 'status':", "Provider ) -> None: \"\"\" Run successful actions on: cluster, service, component. Run", "'template': template}) return provider, task @allure.step('Create two complex providers and three complex clusters')", "clusters) 2. Provider that create multiple hosts via action, run actions on some", "Change config of one of providers and one of hosts Run failed actions", "second host and delete each fourth host after tasks are finished\"\"\" hosts =", "upgrade 2. Create two clusters of previous version 3. Run dummy actions on", "'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _", "clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save", "Job) -> dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date,", "run actions on some of hosts and then delete multiple of them by", "provider and {amount_of_hosts} hosts with prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle:", "Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with old and new version with", "Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster =", "providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT})", "adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider", "hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components:", "configured (can't run actions on it). Cluster has 1 service added. \"\"\" cluster", "'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility", "be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run()))", "@pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient,", "def create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int = 18", "Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM')", "with allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component() for _ in range(config_change_iterations):", "cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\",", "# type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old", "same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0],", "import contextmanager from pathlib import Path from typing import Tuple, Union, List, Iterable,", "for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with", "finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in", "sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str =", "both of them 4. Upgrade one of clusters :returns: Tuple with upgraded cluster", "@params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs:", "providers and one of hosts Run failed actions on 3 of providers Run", "with config history (on cluster, one service and its components) 3. Not configured", "one of simple clusters where at least one job was ran\"\"\" cluster_with_job =", "from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator", "OR CONDITIONS OF ANY KIND, either express or implied. # See the License", "may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "_ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component()", "to clusters and run action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service'])", "@allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster,", "hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task =", "allure.step('Upgrade ADCM and expect all objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs):", ") ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent()", "self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks on provider to be finished", "hosts Run failed actions on 3 of providers Run install action on hosts", "Provider that create multiple hosts via action, run actions on some of hosts", "sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with", "'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()}, } comparator =", "provider, bunch of hosts via action (provide template if you want to use", "provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]]", "possibility of upgrade 2. Create two clusters of previous version 3. Run dummy", "-> None: assert len(cluster.host_list()) == 1, \"Only one host expected to be\" with", "one service and altered config of cluster, service and component - With two", "'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), #", "expect all objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials,", "'bread_service' # Components # on cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT", "providers[-2:] for host in provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create a", "= old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way I", "tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0],", "components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with", "= 'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on cheese MILK_COMPONENT = 'milk'", "remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials,", "in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None: raise ValueError('At least on", "provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate',", "complex providers: 1. Provider that supply hosts for complex clusters (all hosts created", "200))} for _ in range(4) ], } def get_component_random_config_map() -> dict: return {'illicium':", "hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4])))", "cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in", "provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of them')", "of different objects. Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None,", "cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks on provider", "obj: f\"Job with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id:", "on component - With one service and altered config of cluster, service and", "service and launched action on component - With one service and altered config", "{service_name} and add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host,", "cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE)", "components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create", "= { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode':", "return provider, task @allure.step('Create two complex providers and three complex clusters') def create_complex_providers_and_clusters(", "action (provide template if you want to use it more than 1 time).", "we want to wait for tasks on provider to be finished (for hosts", "of hosts Run failed actions on 3 of providers Run install action on", "of hosts. Cluster is not configured (can't run actions on it). Cluster has", "a lot of different objects. Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed", "of them by host delete action And three complex clusters: 1. Cluster with", "job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient,", "for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each to", "created clusters and tasks \"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments':", "for host in provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create a lot", "cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client:", "def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster,", "-> Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts via action (provide template", "cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\",", "on some of hosts and then delete multiple of them by host delete", "new version with possibility of upgrade 2. Create two clusters of previous version", "and {amount_of_hosts} hosts with prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle,", "CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on", "big dict Useful for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object,", "tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import", "= cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run", "actions on the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run()", "change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map())", "= self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks)", "on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures", "simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks =", "upgrade\"\"\" def extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date':", "providers, hosts, jobs. All jobs are waited to be finished before returning result", "Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task", "Upgrade one of clusters :returns: Tuple with upgraded cluster and old-version cluster \"\"\"", "import Tuple, Union, List, Iterable, Any import allure import pytest from adcm_client.base import", "\"\"\" Create provider, bunch of hosts via action (provide template if you want", "def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common fields of an object", "from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result,", "@pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target:", "_wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with", "bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and", "Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not", "1. Provider that supply hosts for complex clusters (all hosts created by provider", "\"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts:", "return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None),", "actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id,", "component. Run failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service,", "Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two complex providers: 1. Provider", "'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle", "'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony',", "Create provider and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag':", "in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters:", "with allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run actions on the", "self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in hosts: cluster.host_add(host)", "None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ):", "SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with given amount of hosts. Cluster", "'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir /", "'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all", "to wait for tasks on provider to be finished (for hosts to be", "typing import Tuple, Union, List, Iterable, Any import allure import pytest from adcm_client.base", "{config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its", "run actions on it). Cluster has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster", "_wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete", "two complex providers: 1. Provider that supply hosts for complex clusters (all hosts", "all services and finished jobs 2. Cluster with config history (on cluster, one", "of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts':", "def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm:", "_create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade", "list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs:", "parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import", "dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple", "with allure.step('Add two services to clusters and run action on them'): for install_cluster_with_two_services", "Provider, Task, Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from", "With one service and launched action on component - With one service and", "and delete each fourth host after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run()", "-> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two", "in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with", "of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config']", "allure.step(f\"Add service and change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _", "\\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service'", "cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade(", "same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster)", "= 34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config':", "run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle,", "services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait()", "Any import allure import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient,", "def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\"", "_check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster", "install action on hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\")", "actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously", "sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add hosts'): for host in hosts:", "return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services:", "-> None: \"\"\"Delete one of simple clusters where at least one job was", "hosts via action (provide template if you want to use it more than", "range(amount_of_clusters)] with allure.step('Add one service to clusters and run action on component'): for", "return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle =", "the License for the specific language governing permissions and # limitations under the", "in jobs} yield with allure.step('Assert that Jobs have correct info'): for job_id, job_info", "service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name}", "= self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects =", "adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task, Job, Upgrade from", "\"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if", "not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster: Cluster, host:", "adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test", "{ \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM", "altered config of cluster, service and component - With two services and launched", "ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str],", "and one service added :returns: Tuple with provider and cluster objects in order", "Run failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread')", "one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run() for", "each provider Change config of one of providers and one of hosts Run", "actions on provider's hosts and remove every 4th host by action on host\")", "clusters where at least one job was ran\"\"\" cluster_with_job = next( filter(lambda cluster:", "previously created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list())", "and add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE)", "\"stable\" properties - objects can be manipulated (you can run actions on them)", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #", "adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check", "comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\" )", "@allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None:", "host expected to be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check", "limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import", "def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]:", "getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if", "of hosts and then delete multiple of them by host delete action And", "str], ) -> None: \"\"\"Test that actions availability from old DSL remains the", "Create two complex providers: 1. Provider that supply hosts for complex clusters (all", "Run some actions \"\"\" with allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With", "with allure.step(f\"Add service and change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for", "sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir)", "for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import contextmanager", "upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded", "3 of providers Run install action on hosts of 2 providers \"\"\" provider_bundle", "{'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4) ], } def get_component_random_config_map()", "actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect", "{action.name for action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list", "Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster", "cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) ->", "\"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import", "= { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), } with allure.step('Add", "(host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for", "by action') def create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int", "), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\")", "dict: return {'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6})", "all common fields of an object to one big dict Useful for dirty", "= tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def", "Version 2.0 (the \"License\"); # you may not use this file except in", "amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]: \"\"\" Create provider, bunch of", "== \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM,", "random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, },", "hosts and remove every 4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider:", "if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) #", "clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster,", "actions on: cluster, service, component. Run failed action on provider. \"\"\" sauce_service =", "# we want to wait for tasks on provider to be finished (for", "clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one service", "with hosts and one service added :returns: Tuple with provider and cluster objects", "adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions", "adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def", "dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs", "cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to clusters and run", "Save all common fields of an object to one big dict Useful for", "services and finished jobs 2. Cluster with config history (on cluster, one service", "from contextlib import contextmanager from pathlib import Path from typing import Tuple, Union,", "components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[", "version 3. Run dummy actions on both of them 4. Upgrade one of", "that actions availability from old DSL remains the same after update\"\"\" cluster =", "host in provider.host_list() ] return provider_bundle, providers, hosts, tasks @allure.step('Create a lot of", "with many different objects: bundles, clusters, providers, hosts, jobs. All jobs are waited", "provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history", "= build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs:", "correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def", "objects. Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with", "With two services and launched cluster install action :returns: Bundle, created clusters and", "for complex clusters (all hosts created by provider action and taken by clusters)", "they aren't changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return { 'task_id':", "tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each to be", "simple clusters where at least one job was ran\"\"\" cluster_with_job = next( filter(lambda", "and launched action on component - With one service and altered config of", "before returning result dictionary. :returns: Dictionary with providers, clusters and sometimes bundles. \"\"\"", "'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed, it may break 'actions':", "64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes':", "'validate', status='failed') @allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts:", "one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers),", "import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\")", "_get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common fields of an object to", "\"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) ->", "simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts),", "run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id':", "return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for", "( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from", "of clusters :returns: Tuple with upgraded cluster and old-version cluster \"\"\" old_version_bundle =", "cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map())", "- objects didn't loose their configs and \"stable\" properties - objects can be", "= 'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT =", "# if visibility is changed, it may break 'actions': set(action.id for action in", "Run install action on hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir /", "then delete multiple of them by host delete action And three complex clusters:", "_create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with one service and config history\"\"\"", "return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle =", "'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters':", "bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir:", "to run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id,", "job was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()),", "template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we", "and change its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations):", "be manipulated (you can run actions on them) \"\"\" LONG_TEXT = f'{\"Many\" *", "bundle_dir: str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\")", "def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir))", "hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run actions on the cluster, all", "one service to clusters and run action on component'): for one_service_cluster in clusters[:4]:", "random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker,", "upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers", "== 1, \"Only one host expected to be\" with catch_failed(ObjectNotFound, \"Previously created host", "providers, clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers,", "'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4) ], }", "dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster,", "complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, },", "three hosts on it Set components on hosts Run some actions \"\"\" with", "available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster:", "def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) ->", "if you want to use it more than 1 time). :returns: Create provider", "adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster", "on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20", "provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions", "str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return", "str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))}", "on it Set components on hosts Run some actions \"\"\" with allure.step('Create cluster", "def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions on each second host", "maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of", "= next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, ) if", "List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers and 20 hosts on each", "= 'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]: \"\"\" Create provider,", "component'): for one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run())", "actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider", "failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT),", "cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts and remove every 4th host", "self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in providers", "that ADCM filled with different objects can upgrade correctly: - objects didn't loose", "found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() ==", "from old DSL remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster)", "id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job", "OF ANY KIND, either express or implied. # See the License for the", "hosts: cluster.host_add(host) with allure.step('Run actions on the cluster, all components and services'): self._run_actions_on_components(cluster,", "add service {service_name} and add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle,", "self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create two upgradable clusters, upgrade", "{log.id for log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda", "function to run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id':", "@allure.step('Create two complex providers and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient,", "provider and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4})", ") ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ],", "_check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM,", "actions on 3 of providers Run install action on hosts of 2 providers", "import allure import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster,", "are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host", "cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs,", "hosts created by provider action and taken by clusters) 2. Provider that create", "= \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name)", "self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) #", "Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components #", "\"\"\"Freeze jobs and check that they aren't changed after upgrade\"\"\" def extract_job_info(job: Job)", "at least one job was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for", "cluster with given amount of hosts. Cluster is not configured (can't run actions", "random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's", "sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\"", "ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM images\"\"\"", "simple_provider: Provider ) -> None: \"\"\" Run successful actions on: cluster, service, component.", "cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for", "in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir:", "tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", }", "cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") ->", "complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https", "cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id in", "indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], )", "service added :returns: Tuple with provider and cluster objects in order that is", "# Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check", "one host expected to be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn)", "in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set(", "too-many-arguments import random from contextlib import contextmanager from pathlib import Path from typing", "simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster =", "want to use it more than 1 time). :returns: Create provider and hosts", "cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common fields of an", "_check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list()) == 1, \"Only one host", "objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects to be", "clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters':", "delete action And three complex clusters: 1. Cluster with all services and finished", "with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add", "Tuple with provider and cluster objects in order that is declared above \"\"\"", "-> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters: - With", "and run action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return", "\"\"\" 1. Upload two bundles with old and new version with possibility of", "Create many clusters: - With one service and launched action on component -", "providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _", "or agreed to in writing, software # distributed under the License is distributed", "successful actions on: cluster, service, component. Run failed action on provider. \"\"\" sauce_service", "for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster,", "governing permissions and # limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\" #", "hosts for complex clusters (all hosts created by provider action and taken by", "to be finished (for hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle,", "actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster)", "components) 3. Not configured cluster just with hosts and one service added :returns:", "random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in", "to be finished before returning result dictionary. :returns: Dictionary with providers, clusters and", "job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()}, } comparator = build_objects_comparator(", "_delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple clusters where at least", "_create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name", "under the Apache License, Version 2.0 (the \"License\"); # you may not use", "dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with many different objects: bundles,", "allure import pytest from adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host,", "with config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with one", "can run actions on them) \"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To", "License. # You may obtain a copy of the License at # #", "= [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts", "sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr,", "\"\"\" Check that ADCM filled with different objects can upgrade correctly: - objects", "that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task", "service and its components) 3. Not configured cluster just with hosts and one", "\"\"\" Create cluster with three services Add three hosts on it Set components", "{ 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex':", "import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config, get_objects_via_pagination", "wait for tasks on provider to be finished (for hosts to be created)", "return provider_bundle, providers, hosts, tasks @allure.step('Create a lot of simple clusters') def create_simple_clusters(", "tasks @allure.step('Create a lot of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir:", "and add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...],", "lot of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) ->", "\"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def", "type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM", "permissions and # limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name,", "True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me',", "action on component - With one service and altered config of cluster, service", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "= adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers", "len(cluster.host_list()) == 1, \"Only one host expected to be\" with catch_failed(ObjectNotFound, \"Previously created", "provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider,", "adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result,", "and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service))", "ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result,", "'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all services') def", "-> dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids':", "] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run()", "allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map())", "* 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service'", "ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle", "three complex clusters') def create_complex_providers_and_clusters( self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider,", "4. Upgrade one of clusters :returns: Tuple with upgraded cluster and old-version cluster", "\"\"\" Fill ADCM with many different objects: bundles, clusters, providers, hosts, jobs. All", "2. Create two clusters of previous version 3. Run dummy actions on both", "[previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str,", "return cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with prefix \"{template}\"", "upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters", "'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action':", "self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run() for provider", "cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components =", "service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component() for _ in", "'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12),", "(cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), )", "License, Version 2.0 (the \"License\"); # you may not use this file except", "@allure.step(\"Run actions on provider's hosts and remove every 4th host by action on", "after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run()", "too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id", "cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster", "-> None: \"\"\" Run successful actions on: cluster, service, component. Run failed action", "Cluster with all services and finished jobs 2. Cluster with config history (on", "cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster", "tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]},", "provider's hosts and remove every 4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self,", "ADCM with a lot of different objects. Upgrade ADCM. Run actions on ADCM.", "get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\",", "finished before returning result dictionary. :returns: Dictionary with providers, clusters and sometimes bundles.", "service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to clusters and run action", "allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers':", "tuple): \"\"\"Utility function to run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple(", "= f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE =", "# Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self,", "on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all", "_ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history =", "= _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs,", "objects can be manipulated (you can run actions on them) \"\"\" LONG_TEXT =", "provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ =", "False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action':", "extract_job_info(job) for job in jobs} yield with allure.step('Assert that Jobs have correct info'):", ") -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters: -", "[cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one service to clusters and", "should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all", "10 providers and 20 hosts on each provider Change config of one of", "simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': {", "cluster with three services Add three hosts on it Set components on hosts", "on provider to be finished (for hosts to be created) host_create_task.wait() cluster_with_all_services =", "'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs:", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return", "providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:] for host in provider.host_list() ]", "ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm", "Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts via action (provide template if", "its config {config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with", "cluster objects in order that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory /", "self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history,", "-> Cluster: \"\"\" Create cluster with given amount of hosts. Cluster is not", "all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\"", "bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle Create many", "= adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait", "two services to clusters and run action on them'): for install_cluster_with_two_services in clusters[12:30]:", ") -> Cluster: \"\"\" Create cluster with given amount of hosts. Cluster is", "host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) )", "them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create", "Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM", "wait for each to be finished (results aren't checked)\"\"\" for task in tasks_to_wait:", ") from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest", "just with hosts and one service added :returns: Tuple with provider and cluster", "AnyADCMObject): obj.reread() actions = {action.name for action in obj.action_list()} assert ( actions ==", "has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host", "(hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks( (", "params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False,", "ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None:", "\"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return", "old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str,", "of upgrade 2. Create two clusters of previous version 3. Run dummy actions", "from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import", "one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name)", "config of one of providers and one of hosts Run failed actions on", "service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with given amount", "'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object,", "to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle,", "components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of", "one big dict Useful for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if", "on the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for", "given amount of hosts. Cluster is not configured (can't run actions on it).", "each fourth host after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host", "Task]: \"\"\" Create provider, bunch of hosts via action (provide template if you", "_create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True)", "or implied. # See the License for the specific language governing permissions and", "\"\"\" Save all common fields of an object to one big dict Useful", "Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs:", "self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int = 18 ) ->", "= cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT:", "dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64),", "cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster)", "Tuple, Union, List, Iterable, Any import allure import pytest from adcm_client.base import ObjectNotFound", "hosts') cluster.service_add(name=service_name) for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's", "can upgrade correctly: - objects didn't loose their configs and \"stable\" properties -", "get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history')", "service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster)", "delete each fourth host after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for", "components on hosts Run some actions \"\"\" with allure.step('Create cluster and add services'):", "# on cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT", "None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed, it may break", "{ 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'},", "parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__,", "not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with", "bunch of hosts via action (provide template if you want to use it", "found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host)", "upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import", "cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None:", "hosts via action, run actions on some of hosts and then delete multiple", "cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT:", "\"\"\"Iterate over `tasks_to_wait` and wait for each to be finished (results aren't checked)\"\"\"", "import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from", "None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is", "clusters :returns: Tuple with upgraded cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory", "range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component() for _", "18 ) -> Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts via action", "_wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions", "different objects. Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields)", "job.finish_date, 'log_ids': {log.id for log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job", "cluster.hostcomponent() ], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster])", "that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert", "-> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True)", "in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider )", "'component_id': component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id),", "ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade with", "[provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts =", "Host, Service, Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import params from", "hosts and then delete multiple of them by host delete action And three", "previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list())", "Union, List, Iterable, Any import allure import pytest from adcm_client.base import ObjectNotFound from", "], ) _wait_for_tasks( ( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) ->", "with providers, clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle,", "indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict,", "in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config", "via action, run actions on some of hosts and then delete multiple of", "use this file except in compliance with the License. # You may obtain", "tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service =", "= self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\")", "} def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations = 100 cluster =", "adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous version ADCM", "assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check", "{amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one", "component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name} and add hosts to cluster')", "and then delete multiple of them by host delete action And three complex", "'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\")", "and tasks \"\"\" amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot':", "service, component. Run failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich')", "cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\")", "in order that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept()", "cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I", "\"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for", "1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = {", "Tuple with upgraded cluster and old-version cluster \"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\")", "result dictionary. :returns: Dictionary with providers, clusters and sometimes bundles. \"\"\" dirty_dir =", "version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2))", "clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of", "them by host delete action And three complex clusters: 1. Cluster with all", "= {job.job_id: extract_job_info(job) for job in jobs} yield with allure.step('Assert that Jobs have", "= SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with given amount of hosts.", "upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import contextmanager from pathlib", "job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()},", "with old and new version with possibility of upgrade 2. Create two clusters", "'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself", "one of hosts Run failed actions on 3 of providers Run install action", "times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config", "for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) )", "in range(amount_of_clusters)] with allure.step('Add one service to clusters and run action on component'):", "To (me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE", "be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj:", "component_id} for host_id, component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), )", "self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs,", "raise ValueError('At least on of simple clusters should have a job') cluster_with_job.delete() def", "(hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]),", "ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import contextmanager from", "@allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each", "\"\"\" Create previous version ADCM with a lot of different objects. Upgrade ADCM.", "provider: Provider) -> None: \"\"\"Run dummy actions on each second host and delete", "Components # on cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT = 'spice'", "self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept()", "providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]] + [", "\"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the", "_run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions on each second host and", "bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\")", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "complex cluster with all services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host])", "provider and cluster objects in order that is declared above \"\"\" provider_bundle =", "cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in cluster.hostcomponent() ], ) _wait_for_tasks(", "complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test", "times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config", "of simple clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict:", "and remove every 4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider)", "list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str =", "{AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) ->", "Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to be\"", "cluster, service, component. Run failed action on provider. \"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services,", "_check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade(", "Create 10 providers and 20 hosts on each provider Change config of one", "=====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different objects can upgrade", "_ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config {config_change_iterations} times\"):", "f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def", "exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only", "and expect all objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs,", "@pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient,", "with prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle, template: str =", "Upgrade ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade", "component_id in ( (hosts[1].id, components[self.SPICE_COMPONENT].id), (hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait()", "upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff =", "action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions on", "# distributed under the License is distributed on an \"AS IS\" BASIS, #", "contextlib import contextmanager from pathlib import Path from typing import Tuple, Union, List,", "[True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient,", "sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) #", "'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', }", ") ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']), service.component(id=hc['component_id'])) for hc in", "adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster bundle", "amount_of_clusters = 34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT},", "one of providers and one of hosts Run failed actions on 3 of", "one service and config history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string':", "in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component = service.component() for", "def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they aren't changed after", "check that they aren't changed after upgrade\"\"\" def extract_job_info(job: Job) -> dict: return", "ADCMClient, cluster: Cluster) -> None: assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected", "be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'],", "\"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) _assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====!", "providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host],", "with the License. # You may obtain a copy of the License at", "/ \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider)", "cluster, service and component - With two services and launched cluster install action", "return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle':", "Set components on hosts Run some actions \"\"\" with allure.step('Create cluster and add", "AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster", "two upgradable clusters, upgrade one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path)", "that create multiple hosts via action, run actions on some of hosts and", "= \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\")", "bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create", "None: \"\"\"Run dummy actions on each second host and delete each fourth host", "an object to one big dict Useful for dirty upgrade \"\"\" return {", "to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously", "34 params = { 'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best':", ":returns: Create provider and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}')", "expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that", "Bundle) -> Cluster: \"\"\"Create cluster with one service and config history\"\"\" def get_random_config_map()", "random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4) ], } def get_component_random_config_map() ->", "= cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT),", "law or agreed to in writing, software # distributed under the License is", "Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10", "{config_change_iterations} times\"): service = cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's", "'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services':", "didn't loose their configs and \"stable\" properties - objects can be manipulated (you", "properties - objects can be manipulated (you can run actions on them) \"\"\"", "range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config {config_change_iterations} times\"): service =", "adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster", "TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different objects can upgrade correctly: -", "one job was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action in", "under the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random", "-> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers and", "cluster just with hosts and one service added :returns: Tuple with provider and", "bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers(", "complex provider and {amount_of_hosts} hosts with prefix \"{template}\" by action') def create_complex_provider( self,", ") -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers", "ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name =", "\"\"\" sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed')", "{random_string(6)}') for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [", "actions on each second host and delete each fourth host after tasks are", "actions = {action.name for action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ),", "cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts,", "\"\"\"Run dummy actions on each second host and delete each fourth host after", "with all services and finished jobs 2. Cluster with config history (on cluster,", "action and taken by clusters) 2. Provider that create multiple hosts via action,", "sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster: Cluster, host: Host) ->", "complex clusters (all hosts created by provider action and taken by clusters) 2.", "in compliance with the License. # You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different objects can upgrade correctly:", "than 1 time). :returns: Create provider and hosts create tasks \"\"\" provider =", "= 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill", "2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better': True},", "every 4th host by action on host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None:", "'cluster_altered_config': {'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config':", "cluster @allure.step('Create cluster, add service {service_name} and add hosts to cluster') def _create_cluster_with_hosts(", "def extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date,", "many clusters: - With one service and launched action on component - With", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "the cluster, all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service", "List[Task]]: \"\"\" Upload simple_cluster bundle Create many clusters: - With one service and", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "all objects to be same'), objects_are_not_changed( sdk_client_fs ), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target)", "\"\"\" old_version_bundle = adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will", "ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider", "Create cluster with three services Add three hosts on it Set components on", "dictionary. :returns: Dictionary with providers, clusters and sometimes bundles. \"\"\" dirty_dir = Path(get_data_dir(__file__))", "tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers':", "Cluster: \"\"\" Create cluster with given amount of hosts. Cluster is not configured", "be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]],", "'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in job.log_list()}, }", "in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name} and add hosts", "expected to be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\")", "_create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials,", "allure.step('Add hosts'): for host in hosts: cluster.host_add(host) with allure.step('Run actions on the cluster,", "_create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster with", "sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM with many different objects: bundles, clusters,", "upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(),", "delete multiple of them by host delete action And three complex clusters: 1.", "sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT),", "of previous version 3. Run dummy actions on both of them 4. Upgrade", "install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider", "with allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': {", "info', name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects", "Cluster, Cluster, Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two complex providers: 1.", "cluster.service_add(name=self.SAUCE_SERVICE) for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component", "service to clusters and run action on component'): for one_service_cluster in clusters[:4]: service", "len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created", "provider_bundle, providers, hosts, tasks @allure.step('Create a lot of simple clusters') def create_simple_clusters( self,", "= build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects to be same'),", "yield with allure.step('Assert that Jobs have correct info'): for job_id, job_info in frozen_objects.items():", "cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters", "components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service,", "'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state,", "None: raise ValueError('At least on of simple clusters should have a job') cluster_with_job.delete()", "} comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\"", "action') def create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int =", "\"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff = dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags)", "}, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4) ],", "different objects: bundles, clusters, providers, hosts, jobs. All jobs are waited to be", "objects: bundles, clusters, providers, hosts, jobs. All jobs are waited to be finished", "service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'):", "host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory /", "for host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts and", "test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None:", "good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return", "three services Add three hosts on it Set components on hosts Run some", "adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade(", "\"Only one host expected to be\" with catch_failed(ObjectNotFound, \"Previously created host not found\"):", "availability from old DSL remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\")", "task @allure.step('Create two complex providers and three complex clusters') def create_complex_providers_and_clusters( self, adcm_client:", "sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous", "for action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of", "tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject, get_config,", "and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task", "Provider that supply hosts for complex clusters (all hosts created by provider action", "complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, }", "with allure.step('Create cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6})", "adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test", "Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous version ADCM with a lot", "{'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], },", "action And three complex clusters: 1. Cluster with all services and finished jobs", "for action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None: raise ValueError('At", "-> Tuple[List[Tuple[str, str]], Any]: \"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def", "check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that they aren't changed after upgrade\"\"\"", "Host, Host]) -> Cluster: \"\"\" Create cluster with three services Add three hosts", "Provider) -> None: \"\"\"Run dummy actions on each second host and delete each", "adcm_client.base import ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider,", "bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def", "Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster with three services", "_wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple':", "pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def", "by host delete action And three complex clusters: 1. Cluster with all services", "AnyADCMObject) -> dict: \"\"\" Save all common fields of an object to one", "@allure.step('Create cluster, add service {service_name} and add hosts to cluster') def _create_cluster_with_hosts( self,", "random from contextlib import contextmanager from pathlib import Path from typing import Tuple,", "taken by clusters) 2. Provider that create multiple hosts via action, run actions", "'log_ids': {log.id for log in job.log_list()}, } comparator = build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info',", "services to clusters and run action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component'])", "cluster install action :returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters = 34", "-> Cluster: \"\"\" Create cluster with three services Add three hosts on it", "All jobs are waited to be finished before returning result dictionary. :returns: Dictionary", "provider in providers[:3]] + [ host.action(name='install').run() for provider in providers[-2:] for host in", "adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\") config_diff", "distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT", "get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import", "3. Not configured cluster just with hosts and one service added :returns: Tuple", "ADCMClient) -> dict: \"\"\" Fill ADCM with many different objects: bundles, clusters, providers,", ") def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple clusters where", "{ 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle,", "Cluster]: \"\"\" Upload complex_provider and complex_cluster Create two complex providers: 1. Provider that", "host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs, cluster) _check_that_host_exists(cluster, host) @pytest.mark.parametrize(\"adcm_is_upgradable\",", "Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True) def test_upgrade_dirty_adcm( self, adcm_fs:", "tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2]))) _wait_for_tasks(tuple((host.action(name='remove_host').run() for host in hosts[::4]))) def _run_actions_on_components(self,", "dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\"", "SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def", "extract_job_info(job: Job) -> dict: return { 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date':", "/ \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks", "sauce_service = cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create", "= f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host:", "it Set components on hosts Run some actions \"\"\" with allure.step('Create cluster and", "-> Cluster: \"\"\"Create cluster with one service and config history\"\"\" def get_random_config_map() ->", "specific language governing permissions and # limitations under the License. \"\"\"Tests for ADCM", "with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for", "provider in providers[-2:] for host in provider.host_list() ] return provider_bundle, providers, hosts, tasks", "\"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str", "'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster},", "this file except in compliance with the License. # You may obtain a", "can be manipulated (you can run actions on them) \"\"\" LONG_TEXT = f'{\"Many\"", "self, adcm_client: ADCMClient, bundles_directory: Path ) -> Tuple[Provider, Provider, Cluster, Cluster, Cluster]: \"\"\"", "str]], Any]: \"\"\"A list of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient,", "providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider", "'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), },", "provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template})", "in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts and remove every", "'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True)", "= { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual", "List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers and 20 hosts on", "hosts, jobs. All jobs are waited to be finished before returning result dictionary.", "run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all services') def _create_cluster_with_all_services(self,", "- With one service and launched action on component - With one service", "is not configured (can't run actions on it). Cluster has 1 service added.", "for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name} and", "sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster", "= self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with jobs'):", "history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations):", "actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id,", "one service added :returns: Tuple with provider and cluster objects in order that", "'config': get_config(adcm_object), # if visibility is changed, it may break 'actions': set(action.id for", "def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name: str = SAUCE_SERVICE )", "_assert_available_actions(cluster) # !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM", "), self.check_job_related_objects_are_not_changed(sdk_client_fs): upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps", "cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT: sauce_service.component(name=self.TOMATO_COMPONENT), self.LEMON_COMPONENT: sauce_service.component(name=self.LEMON_COMPONENT), self.SPICE_COMPONENT: sauce_service.component(name=self.SPICE_COMPONENT), }", "obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\"", "self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider], List[Host], List[Task]]: \"\"\" Upload", "old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") ->", "self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client:", "_ in range(4) ], } def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations", "upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_that_cluster_exists(sdk_client_fs,", "for host in hosts: cluster.host_add(host) with allure.step('Run actions on the cluster, all components", "\"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I", "[] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)]", "return cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster:", "prefix \"{template}\" by action') def create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host',", "adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host", "{random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one service to clusters and run", "Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and", "for _ in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks =", "\"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def", "}, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True],", "] return provider_bundle, providers, hosts, tasks @allure.step('Create a lot of simple clusters') def", "Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient): \"\"\"Freeze jobs and check that", "two bundles with old and new version with possibility of upgrade 2. Create", "...], service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with given", "from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, )", ") -> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host)", "def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\"", "\"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service = cluster.service_add(name=\"PassCheckerService\")", "_run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility function to run", "one of them') def create_upgradable_clusters(self, adcm_client: ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\"", "-> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\") service", "random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name': random_string(13), 'age':", "waited to be finished before returning result dictionary. :returns: Dictionary with providers, clusters", "in range(4) ], } def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to", "} @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for", "= service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config'])", "clusters: 1. Cluster with all services and finished jobs 2. Cluster with config", "@allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster", "simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Provider],", "= [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file':", "import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result,", "the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade,", "random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code':", "jobs. All jobs are waited to be finished before returning result dictionary. :returns:", "service and altered config of cluster, service and component - With two services", "host in hosts: cluster.host_add(host) return cluster @allure.step(\"Run actions on provider's hosts and remove", "Create cluster with given amount of hosts. Cluster is not configured (can't run", "= provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two complex providers and", "Cluster, simple_provider: Provider ) -> None: \"\"\" Run successful actions on: cluster, service,", "required by applicable law or agreed to in writing, software # distributed under", "loose their configs and \"stable\" properties - objects can be manipulated (you can", "def _check_that_host_exists(cluster: Cluster, host: Host) -> None: assert len(cluster.host_list()) == 1, \"Only one", "): \"\"\" Create previous version ADCM with a lot of different objects. Upgrade", "-> dict: return {'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag':", "`tasks_to_wait` and wait for each to be finished (results aren't checked)\"\"\" for task", "{job.job_id: extract_job_info(job) for job in jobs} yield with allure.step('Assert that Jobs have correct", "service in (cheese_service, sauce_service, bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history')", "dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self, adcm_client: ADCMClient):", "Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host =", "\"\"\" Upload simple_cluster bundle Create many clusters: - With one service and launched", "and cluster objects in order that is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory", "and # limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\" # pylint:disable=redefined-outer-name, no-self-use,", "is declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task =", "amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two complex providers and three complex", "\"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name',", "provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle =", "provider Change config of one of providers and one of hosts Run failed", "\"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle", "54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two complex", "( components[self.TOMATO_COMPONENT].action(name='add_more').run(), components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one", "Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\" Run successful actions on:", "(on cluster, one service and its components) 3. Not configured cluster just with", "different objects can upgrade correctly: - objects didn't loose their configs and \"stable\"", "with allure.step('Upgrade ADCM and expect all objects to be same'), objects_are_not_changed( sdk_client_fs ),", "Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import", "self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\" Run successful", "their configs and \"stable\" properties - objects can be manipulated (you can run", "1 time). :returns: Create provider and hosts create tasks \"\"\" provider = provider_bundle.provider_create(name=f'Complex", "run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import", "You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade':", "cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle) ->", "hosts on it Set components on hosts Run some actions \"\"\" with allure.step('Create", "_check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM,", "{ 'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log", "of providers Run install action on hosts of 2 providers \"\"\" provider_bundle =", "{ 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': {", "adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that actions availability from", "provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)]", "} @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\" if not cmd_opts.adcm_image:", "simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs,", "ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different objects", "'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict:", "hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state':", "provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template': template}) return provider, task @allure.step('Create two complex providers and three", "List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in jobs} yield with", "cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to", "Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different", "providers: 1. Provider that supply hosts for complex clusters (all hosts created by", "{config_change_iterations} times\"): component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create", "configured cluster just with hosts and one service added :returns: Tuple with provider", "a lot of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path )", "def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': {", "hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility function", "pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts)", "common fields of an object to one big dict Useful for dirty upgrade", "None: \"\"\"Delete one of simple clusters where at least one job was ran\"\"\"", "ADCM. Run actions on ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM", "return cluster @allure.step('Create cluster, add service {service_name} and add hosts to cluster') def", "indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials:", "\"\"\" Upload simple_provider bundle Create 10 providers and 20 hosts on each provider", "config history\"\"\" def get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)},", "hosts, tasks @allure.step('Create a lot of simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient,", "contextmanager from pathlib import Path from typing import Tuple, Union, List, Iterable, Any", "'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size': random.randint(2, 64), 'person': { 'name':", "List[Provider], List[Host], List[Task]]: \"\"\" Upload simple_provider bundle Create 10 providers and 20 hosts", "a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common fields", "3. Run dummy actions on both of them 4. Upgrade one of clusters", "least one job was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action", "with possibility of upgrade 2. Create two clusters of previous version 3. Run", "set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate", "for tasks on provider to be finished (for hosts to be created) host_create_task.wait()", "cluster's config {config_change_iterations} times\"): for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and", "dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks) with allure.step('Delete one of simple clusters with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return", "test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None:", "run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils", "Cluster, Host, Service, Bundle, Component, Provider, Task, Job, Upgrade from adcm_pytest_plugin import params", "cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to", "jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle':", ") -> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_pass_verify\")", "'lemon' # fixtures @pytest.fixture() def dirty_adcm(self, sdk_client_fs: ADCMClient) -> dict: \"\"\" Fill ADCM", "for _ in range(config_change_iterations): service.config_set_diff(get_random_config_map()) with allure.step(f\"Change component's config {config_change_iterations} times\"): component =", "provided\") return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]:", "with a lot of different objects. Upgrade ADCM. Run actions on ADCM. \"\"\"", "MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT", "# you may not use this file except in compliance with the License.", "cluster and add services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service =", "1. Upload two bundles with old and new version with possibility of upgrade", "\"\"\" provider = provider_bundle.provider_create(name=f'Complex Provider {random_string(6)}') provider.config_set_diff({'very_important_flag': 54.4}) task = provider.action(name='create_hosts').run(config={'count': amount_of_hosts, 'template':", "pylint:disable=redefined-outer-name, no-self-use, too-many-arguments import random from contextlib import contextmanager from pathlib import Path", "Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait for each to be finished (results aren't", "from tests.functional.conftest import only_clean_adcm from tests.functional.plugin_utils import build_objects_checker, build_objects_comparator from tests.functional.tools import AnyADCMObject,", "'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, },", "= adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle) provider_with_free_hosts, _ = self.create_complex_provider(provider_bundle,", "service {service_name} and add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts:", "be finished before returning result dictionary. :returns: Dictionary with providers, clusters and sometimes", "service and component - With two services and launched cluster install action :returns:", "declared above \"\"\" provider_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_provider\") provider_bundle.license_accept() provider, host_create_task = self.create_complex_provider(provider_bundle)", "\"\"\" dirty_dir = Path(get_data_dir(__file__)) / \"dirty_upgrade\" simple_provider_bundle, simple_providers, simple_hosts, all_tasks = self.create_simple_providers( sdk_client_fs,", "old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way I am')", "\"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def upgrade_target(cmd_opts) -> Tuple[str, str]: \"\"\"Actual ADCM version\"\"\"", "in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and", "# !===== Dirty ADCM upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled", "\"\"\"Delete one of simple clusters where at least one job was ran\"\"\" cluster_with_job", "'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = []", "adcm upgrade\"\"\" cluster = _create_cluster(sdk_client_fs) host = _create_host(sdk_client_fs) cluster.host_add(host) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags)", "= 18 ) -> Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts via", "two services and launched cluster install action :returns: Bundle, created clusters and tasks", "of cluster, service and component - With two services and launched cluster install", "bundle_dir: str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\"", "for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info) @allure.step('Create simple providers') def create_simple_providers( self,", "SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on cheese MILK_COMPONENT =", "'mazepa', 'component_with_config': 'symphony', 'component_action': 'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks =", "clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]:", "= cluster_config_history.service(name=self.SAUCE_SERVICE) run_cluster_action_and_assert_result(cluster_all_services, 'eat_sandwich') run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex", "License for the specific language governing permissions and # limitations under the License.", "providers and 20 hosts on each provider Change config of one of providers", "\"simple_provider\") providers = [provider_bundle.provider_create(f'Provider {random_string(6)}') for _ in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key':", "], } def get_component_random_config_map() -> dict: return {'illicium': random.random()} config_change_iterations = 100 cluster", "get_random_config_map() -> dict: return { 'a_lot_of_text': {'simple_string': random_string(25), 'file_pass': random_<PASSWORD>(16)}, 'from_doc': { 'memory_size':", "DSL remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs, sdk_client_fs,", "Create provider, bunch of hosts via action (provide template if you want to", "\"License\"); # you may not use this file except in compliance with the", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with prefix \"{template}\" by action') def", "in range(10)] one_of_providers = providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _", "actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action in obj.action_list()}", "any(len(action.task_list()) for action in cluster.action_list()), simple_clusters), None, ) if cluster_with_job is None: raise", "'config_history': complex_objects[3], 'not_configured': complex_objects[4], }, }, 'upgrade': {'upgraded': upgraded_cluster, 'not_upgraded': not_upgraded_cluster}, } #", "= sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str", "= bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"): for _", "Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create cluster with three services Add three", "cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster: Cluster,", ") -> Tuple[Provider, Task]: \"\"\" Create provider, bunch of hosts via action (provide", "fields of an object to one big dict Useful for dirty upgrade \"\"\"", "-> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions", "for _ in range(config_change_iterations): cluster.config_set_diff(get_random_config_map()) with allure.step(f\"Add service and change its config {config_change_iterations}", "Cluster: \"\"\" Create cluster with three services Add three hosts on it Set", "= cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in upgraded ADCM') def", "adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade\"\"\" cluster =", "launched cluster install action :returns: Bundle, created clusters and tasks \"\"\" amount_of_clusters =", "80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1, 200))} for", "hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts =", "to use it more than 1 time). :returns: Create provider and hosts create", "_ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster @allure.step('Create cluster, add service {service_name} and add", "created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check that previously created service exists\") def _check_that_host_exists(cluster:", "import random from contextlib import contextmanager from pathlib import Path from typing import", "will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(),", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,", "in writing, software # distributed under the License is distributed on an \"AS", "'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed,", "ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\") -> Cluster:", "version with possibility of upgrade 2. Create two clusters of previous version 3.", "created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return", "= {action.name for action in obj.action_list()} assert ( actions == AVAILABLE_ACTIONS ), f\"Unexpected", "failed actions on 3 of providers Run install action on hosts of 2", "simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2],", "upgrade =====! class TestUpgradeFilledADCM: \"\"\" Check that ADCM filled with different objects can", "self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster], List[Task]]: \"\"\" Upload simple_cluster", "for provider in providers[-2:] for host in provider.host_list() ] return provider_bundle, providers, hosts,", "Cluster, host: Host) -> None: assert len(cluster.host_list()) == 1, \"Only one host expected", "= providers[-2] one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for", "test_upgrade_dirty_adcm( self, adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], dirty_adcm: dict,", "\"\"\" Create cluster with given amount of hosts. Cluster is not configured (can't", "ObjectNotFound from adcm_client.objects import ADCMClient, Cluster, Host, Service, Bundle, Component, Provider, Task, Job,", "allure.step('Assert that Jobs have correct info'): for job_id, job_info in frozen_objects.items(): comparator(adcm_client.job(id=job_id), job_info)", "= cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two services to clusters and", "Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]:", "Union[Cluster, Service]) -> None: assert obj.action(name=\"check-password\").run().wait() == \"success\" @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(),", "template: str = 'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]: \"\"\"", "tuple(provider.host_list())[:3] ) cluster_with_hosts = self._create_cluster_with_hosts(cluster_bundle, tuple(provider.host_list())[3:]) return provider, provider_with_free_hosts, cluster_with_all_services, cluster_with_history, cluster_with_hosts @allure.step('Create", "}, 'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history':", "100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change cluster's config {config_change_iterations} times\"):", "job_info) @allure.step('Create simple providers') def create_simple_providers( self, adcm_client: ADCMClient, bundle_dir: Path ) ->", "hosts: tuple): \"\"\"Utility function to run actions on components (host actions too)\"\"\" cluster.action(name='make_sauce').run(", "indirect=True) @pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict,", "finished jobs 2. Cluster with config history (on cluster, one service and its", "import Path from typing import Tuple, Union, List, Iterable, Any import allure import", "[[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target:", "of old ADCM images\"\"\" return parametrized_by_adcm_version(adcm_min_version=\"2019.10.08\")[0] def _create_cluster(sdk_client_fs: ADCMClient, bundle_dir: str = \"cluster_bundle\")", "Cluster has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for", "str], dirty_adcm: dict, ): \"\"\" Create previous version ADCM with a lot of", "host\") def _run_actions_on_host_and_delete_with_action(self, provider: Provider) -> None: \"\"\"Run dummy actions on each second", "with jobs'): self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters),", "in hosts[::4]))) def _run_actions_on_components(self, cluster: Cluster, service: Service, components: dict, hosts: tuple): \"\"\"Utility", "else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config':", "Cluster is not configured (can't run actions on it). Cluster has 1 service", "for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex", "'task_id': job.task_id, 'status': job.status, 'start_date': job.start_date, 'finish_date': job.finish_date, 'log_ids': {log.id for log in", "config {config_change_iterations} times\"): component = service.component() for _ in range(config_change_iterations): component.config_set_diff(get_component_random_config_map()) return cluster", "allure.step('Change config of clusters'): for cluster_to_change_config in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config'])", "Upgrade from adcm_pytest_plugin import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version", "run action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle,", "@allure.step('Create complex provider and {amount_of_hosts} hosts with prefix \"{template}\" by action') def create_complex_provider(", "(hosts[1].id, components[self.LEMON_COMPONENT].id), (hosts[2].id, components[self.TOMATO_COMPONENT].id), ) ) ) ).wait() cluster.hostcomponent_set( (hosts[0], components[self.MILK_COMPONENT]), *[ (cluster.host(id=hc['host_id']),", "dummy actions on both of them 4. Upgrade one of clusters :returns: Tuple", "field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list)", "simple_provider bundle Create 10 providers and 20 hosts on each provider Change config", "str = \"cluster_bundle\") -> Cluster: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__, bundle_dir)) cluster_name = f\"test_{random_string()}\" return", "Tuple[Host, ...], service_name: str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with", "# Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE = 'bread_service' # Components", "2.0 (the \"License\"); # you may not use this file except in compliance", "run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version from", "way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster", "[ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT})", "add hosts to cluster') def _create_cluster_with_hosts( self, cluster_bundle: Bundle, hosts: Tuple[Host, ...], service_name:", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the", "have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\" Save all common", "action on them'): for install_cluster_with_two_services in clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters,", "# # Unless required by applicable law or agreed to in writing, software", "good_old_cluster = old_version_bundle.cluster_create('I am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade", "express or implied. # See the License for the specific language governing permissions", "complex_cluster Create two complex providers: 1. Provider that supply hosts for complex clusters", "range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider", "create multiple hosts via action, run actions on some of hosts and then", "for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in", "cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not found\"): sdk_client_fs.cluster(name=cluster.name) @allure.step(\"Check", "'no_sense_to_run_me', } cluster_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters}", "create_complex_provider( self, provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int = 18 )", "services'): cluster = cluster_bundle.cluster_create(name='With all services') cluster.config_set_diff({'very_important_flag': 1.6}) cheese_service = cluster.service_add(name=self.CHEESE_SERVICE) sauce_service =", "may break 'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for tasks') def", "either express or implied. # See the License for the specific language governing", "'sauce_service' BREAD_SERVICE = 'bread_service' # Components # on cheese MILK_COMPONENT = 'milk' #", "three complex clusters: 1. Cluster with all services and finished jobs 2. Cluster", "one_of_providers.config_set_diff({'ssh_key': self.LONG_TEXT}) hosts = [ provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in", "all components and services'): self._run_actions_on_components(cluster, sauce_service, components, hosts) _wait_for_tasks(service.action().run() for service in (cheese_service,", "@pytest.mark.parametrize(\"image\", old_adcm_images(), ids=repr, indirect=True) def test_pass_in_config_encryption_after_upgrade( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags:", "params['component_altered_config'] ) with allure.step('Add two services to clusters and run action on them'):", "- With one service and altered config of cluster, service and component -", "provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action", "Upload simple_cluster bundle Create many clusters: - With one service and launched action", "'fast'}, 'component_altered_config': {'simpler-is-better': True}, 'cluster_action': 'install', 'service_with_component': 'Tchaikovsky', 'lonely_service': 'Shostakovich', 'component_with_action': 'mazepa', 'component_with_config':", "assert len(cluster.host_list()) == 1, \"Only one host expected to be\" with catch_failed(ObjectNotFound, \"Previously", "( {'host_id': host_id, 'service_id': service.id, 'component_id': component_id} for host_id, component_id in ( (hosts[1].id,", "cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\" Run successful actions", "the License. # You may obtain a copy of the License at #", "'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]):", "getattr(adcm_object, 'edition', None), 'state': adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed, it", "(me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE = 'sauce_service' BREAD_SERVICE =", "import params from adcm_pytest_plugin.docker_utils import ADCM from adcm_pytest_plugin.plugin import parametrized_by_adcm_version from adcm_pytest_plugin.steps.actions import", "with three services Add three hosts on it Set components on hosts Run", "old_adcm_images(), ids=repr, indirect=True) def test_upgrade_adcm( adcm_fs: ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str,", "availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action in obj.action_list()} assert", "for dirty upgrade \"\"\" return { 'name_or_fqdn': adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn,", "= adcm_client.upload_from_fs(bundles_directory / \"cluster_to_upgrade\") adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded')", "tasks on provider to be finished (for hosts to be created) host_create_task.wait() cluster_with_all_services", "you want to use it more than 1 time). :returns: Create provider and", "some actions in upgraded ADCM') def run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider:", "Run successful actions on: cluster, service, component. Run failed action on provider. \"\"\"", "( actions == AVAILABLE_ACTIONS ), f\"Unexpected list of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that", "good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do() return cluster_to_upgrade, good_old_cluster @allure.step('Run some actions in", "str = SAUCE_SERVICE ) -> Cluster: \"\"\" Create cluster with given amount of", "host after tasks are finished\"\"\" hosts = tuple(provider.host_list()) _wait_for_tasks(tuple((host.action(name='dummy_action').run() for host in hosts[::2])))", "job in jobs} yield with allure.step('Assert that Jobs have correct info'): for job_id,", "build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects to be same'), objects_are_not_changed(", "adcm_client.upload_from_fs(bundles_directory / \"cluster_greater_version\") cluster_to_upgrade = old_version_bundle.cluster_create('I will be upgraded') good_old_cluster = old_version_bundle.cluster_create('I am", "self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects = self.create_complex_providers_and_clusters(sdk_client_fs, dirty_dir) upgraded_cluster, not_upgraded_cluster = self.create_upgradable_clusters(sdk_client_fs, dirty_dir) all_tasks.extend(tasks) _wait_for_tasks(all_tasks)", "import AnyADCMObject, get_config, get_objects_via_pagination from tests.library.utils import previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS =", "_check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def test_actions_availability_after_upgrade( adcm_fs:", "ADCMClient, bundles_directory: Path) -> Tuple[Cluster, Cluster]: \"\"\" 1. Upload two bundles with old", "self._delete_simple_cluster_with_job(simple_clusters) return { 'simple': { 'providers': tuple(simple_providers), 'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle,", "'hosts': tuple(simple_hosts), 'clusters': tuple(simple_clusters), 'provider_bundle': simple_provider_bundle, 'cluster_bundle': simple_cluster_bundle, }, 'complex': { 'providers': {'host_supplier':", "in clusters[6:10]: cluster_to_change_config.config_set_diff(params['cluster_altered_config']) service = cluster_to_change_config.service_add(name=params['service_with_component']) service.config_set_diff(params['service_altered_config']) service.component(name=params['component_with_config']).config_set_diff( params['component_altered_config'] ) with allure.step('Add two", "bread_service)) cluster.action(name='make_sandwich').run().wait() return cluster @allure.step('Create cluster with config history') def _create_cluster_with_config_history(self, bundle: Bundle)", "provider.host_create(f'{random_string(6)}-{random_string(6)}') for _ in range(20) for provider in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks", "on components (host actions too)\"\"\" cluster.action(name='make_sauce').run( hc=tuple( ( {'host_id': host_id, 'service_id': service.id, 'component_id':", "template if you want to use it more than 1 time). :returns: Create", "for each to be finished (results aren't checked)\"\"\" for task in tasks_to_wait: task.wait()", "to clusters and run action on component'): for one_service_cluster in clusters[:4]: service =", "on it). Cluster has 1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts')", "finished (for hosts to be created) host_create_task.wait() cluster_with_all_services = self._create_cluster_with_all_services( cluster_bundle, tuple(provider.host_list())[:3] )", "'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]: \"\"\" Create provider, bunch", "in hosts: cluster.host_add(host) with allure.step('Run actions on the cluster, all components and services'):", "sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True)", "None: assert len(cluster.host_list()) == 1, \"Only one host expected to be\" with catch_failed(ObjectNotFound,", "{'illicium': random.random()} config_change_iterations = 100 cluster = bundle.cluster_create(name='Config history') cluster.config_set_diff({'very_important_flag': 1.6}) with allure.step(f\"Change", "component - With one service and altered config of cluster, service and component", "_assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name for action in obj.action_list()} assert ( actions", "and new version with possibility of upgrade 2. Create two clusters of previous", "\"\"\" LONG_TEXT = f'{\"Many\" * 200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services", "some of hosts and then delete multiple of them by host delete action", "components[self.SPICE_COMPONENT].action(name='add_more').run(), ) ) def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple", "clusters[12:30]: install_cluster_with_two_services.service_add(name=params['service_with_component']) install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts}", "upgrade_target: Tuple[str, str], dirty_adcm: dict, ): \"\"\" Create previous version ADCM with a", "(all hosts created by provider action and taken by clusters) 2. Provider that", "adcm_pytest_plugin.steps.actions import ( run_cluster_action_and_assert_result, run_service_action_and_assert_result, run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir,", "\"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks on", "host in hosts: cluster.host_add(host) with allure.step('Run actions on the cluster, all components and", "str = 'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]: \"\"\" Create", "def _create_cluster_with_config_history(self, bundle: Bundle) -> Cluster: \"\"\"Create cluster with one service and config", "bundle.cluster_prototype().cluster_create(name=cluster_name) def _create_host(sdk_client_fs: ADCMClient, bundle_dir: str = \"hostprovider\") -> Host: bundle = sdk_client_fs.upload_from_fs(get_data_dir(__file__,", "clusters (all hosts created by provider action and taken by clusters) 2. Provider", "1, \"Only one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously created cluster not", "{obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in", "None: \"\"\" Run successful actions on: cluster, service, component. Run failed action on", "'not_upgraded': not_upgraded_cluster}, } # Test itself @params.including_https @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [previous_adcm_version_tag()], indirect=True)", "ADCM version\"\"\" if not cmd_opts.adcm_image: pytest.fail(\"CLI parameter adcm_image should be provided\") return tuple(cmd_opts.adcm_image.split(\":\",", "20 hosts on each provider Change config of one of providers and one", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "created by provider action and taken by clusters) 2. Provider that create multiple", "dict: \"\"\" Save all common fields of an object to one big dict", "[ {'country': random_string(12), 'code': int(random.randint(1, 200))} for _ in range(4) ], } def", "1, \"Only one host expected to be\" with catch_failed(ObjectNotFound, \"Previously created host not", "1 service added. \"\"\" cluster = cluster_bundle.cluster_create(name='Cluster with hosts') cluster.service_add(name=service_name) for host in", "adcm_object.action_list()), } @allure.step('Wait for tasks') def _wait_for_tasks(tasks_to_wait: Iterable[Task]): \"\"\"Iterate over `tasks_to_wait` and wait", "/ \"simple_cluster\") tasks = [] with allure.step(f'Create {amount_of_clusters} clusters'): clusters = [cluster_bundle.cluster_create(f'Cluster {random_string(8)}')", "'code': int(random.randint(1, 200))} for _ in range(4) ], } def get_component_random_config_map() -> dict:", "_ in range(amount_of_clusters)] with allure.step('Add one service to clusters and run action on", "on each second host and delete each fourth host after tasks are finished\"\"\"", "ADCM, sdk_client_fs: ADCMClient, adcm_api_credentials: dict, upgrade_target: Tuple[str, str], ) -> None: \"\"\"Test that", "'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country': random_string(12), 'code': int(random.randint(1,", "ADCM. \"\"\" objects_are_not_changed = build_objects_checker(changed=None, extractor=_get_object_fields) with allure.step('Upgrade ADCM and expect all objects", "assert len(sdk_client_fs.cluster_list()) == 1, \"Only one cluster expected to be\" with catch_failed(ObjectNotFound, \"Previously", "upgrade_target) self.run_actions_after_upgrade( dirty_adcm['complex']['clusters']['all_services'], dirty_adcm['complex']['clusters']['config_history'], dirty_adcm['simple']['providers'][0], ) # Steps and helpers @contextmanager def check_job_related_objects_are_not_changed(self,", "adcm_object.state, 'config': get_config(adcm_object), # if visibility is changed, it may break 'actions': set(action.id", "= dict(password=\"<PASSWORD>\") cluster.config_set_diff(config_diff) service.config_set_diff(config_diff) upgrade_adcm_version(adcm_fs, sdk_client_fs, adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True)", "was ran\"\"\" cluster_with_job = next( filter(lambda cluster: any(len(action.task_list()) for action in cluster.action_list()), simple_clusters),", "components: dict, hosts: tuple): \"\"\"Utility function to run actions on components (host actions", "by provider action and taken by clusters) 2. Provider that create multiple hosts", "200}Words\\nTo \\\"Say\\\"\\n To (me)\\n\"' * 20 # Services CHEESE_SERVICE = 'cheese_service' SAUCE_SERVICE =", "of hosts via action (provide template if you want to use it more", "= [cluster_bundle.cluster_create(f'Cluster {random_string(8)}') for _ in range(amount_of_clusters)] with allure.step('Add one service to clusters", "created host not found\"): cluster.host(fqdn=host.fqdn) @allure.step(\"Check encryption\") def _check_encryption(obj: Union[Cluster, Service]) -> None:", "Create two clusters of previous version 3. Run dummy actions on both of", "of providers and one of hosts Run failed actions on 3 of providers", "\"\"\" Upload complex_provider and complex_cluster Create two complex providers: 1. Provider that supply", "services') def _create_cluster_with_all_services(self, cluster_bundle: Bundle, hosts: Tuple[Host, Host, Host]) -> Cluster: \"\"\" Create", "and taken by clusters) 2. Provider that create multiple hosts via action, run", "except in compliance with the License. # You may obtain a copy of", "run_component_action_and_assert_result, run_provider_action_and_assert_result, ) from adcm_pytest_plugin.utils import catch_failed, get_data_dir, random_string from tests.upgrade_utils import upgrade_adcm_version", "over `tasks_to_wait` and wait for each to be finished (results aren't checked)\"\"\" for", "adcm_api_credentials, adcm_image_tags) _check_encryption(cluster) _check_encryption(service) @pytest.mark.parametrize(\"adcm_is_upgradable\", [True], indirect=True) @pytest.mark.parametrize(\"image\", [[\"hub.arenadata.io/adcm/adcm\", \"2021.06.17.06\"]], ids=repr, indirect=True) def", "-> None: \"\"\"Run dummy actions on each second host and delete each fourth", "bundle_dir)) provider = bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread()", "Cluster]: \"\"\" 1. Upload two bundles with old and new version with possibility", "old DSL remains the same after update\"\"\" cluster = _create_cluster(sdk_client_fs, \"cluster_with_actions\") _assert_available_actions(cluster) upgrade_adcm_version(adcm_fs,", "may not use this file except in compliance with the License. # You", "License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "bundle.provider_create(name=f\"test_{random_string()}\") return provider.host_create(fqdn=f\"test_host_{random_string()}\") @allure.step(\"Check actions availability\") def _assert_available_actions(obj: AnyADCMObject): obj.reread() actions = {action.name", "simple clusters should have a job') cluster_with_job.delete() def _get_object_fields(adcm_object: AnyADCMObject) -> dict: \"\"\"", "Check that ADCM filled with different objects can upgrade correctly: - objects didn't", "am good the way I am') _wait_for_tasks((cluster_to_upgrade.action(name='dummy').run(), good_old_cluster.action(name='dummy').run())) upgrade: Upgrade = cluster_to_upgrade.upgrade() upgrade.do()", "run_actions_after_upgrade( self, cluster_all_services: Cluster, cluster_config_history: Cluster, simple_provider: Provider ) -> None: \"\"\" Run", "configs and \"stable\" properties - objects can be manipulated (you can run actions", "List[Cluster]) -> None: \"\"\"Delete one of simple clusters where at least one job", "actions on both of them 4. Upgrade one of clusters :returns: Tuple with", "tasks = [provider.action(name='validate').run() for provider in providers[:3]] + [ host.action(name='install').run() for provider in", "by clusters) 2. Provider that create multiple hosts via action, run actions on", "Host]) -> Cluster: \"\"\" Create cluster with three services Add three hosts on", "on 3 of providers Run install action on hosts of 2 providers \"\"\"", "dict, ): \"\"\" Create previous version ADCM with a lot of different objects.", "{'number_of_segments': 2, 'auto_reboot': False, 'textarea': self.LONG_TEXT}, 'service_altered_config': {'simple-is-best': False, 'mode': 'fast'}, 'component_altered_config': {'simpler-is-better':", "= self._create_cluster_with_config_history(cluster_bundle) # we want to wait for tasks on provider to be", "previous_adcm_version_tag pytestmark = [only_clean_adcm] AVAILABLE_ACTIONS = { \"single_state-available\", \"state_list-available\", \"state_any-available\", } @pytest.fixture(scope=\"session\") def", "def _delete_simple_cluster_with_job(self, simple_clusters: List[Cluster]) -> None: \"\"\"Delete one of simple clusters where at", "provider_bundle: Bundle, template: str = 'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider,", "= get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job) for job in jobs} yield with allure.step('Assert", "hosts of 2 providers \"\"\" provider_bundle = adcm_client.upload_from_fs(bundle_dir / \"simple_provider\") providers = [provider_bundle.provider_create(f'Provider", "one_service_cluster in clusters[:4]: service = one_service_cluster.service_add(name=params['service_with_component']) component: Component = service.component(name=params['component_with_action']) tasks.append(component.action(name=params['component_action']).run()) with allure.step('Change", "cluster.service_add(name=self.CHEESE_SERVICE) sauce_service = cluster.service_add(name=self.SAUCE_SERVICE) bread_service = cluster.service_add(name=self.BREAD_SERVICE) components = { self.MILK_COMPONENT: cheese_service.component(name=self.MILK_COMPONENT), self.TOMATO_COMPONENT:", "sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT = 'tomato' LEMON_COMPONENT = 'lemon' # fixtures @pytest.fixture()", "adcm_object.name if hasattr(adcm_object, 'name') else adcm_object.fqdn, 'display_name': getattr(adcm_object, 'display_name', None), 'edition': getattr(adcm_object, 'edition',", "simple clusters') def create_simple_clusters( self, adcm_client: ADCMClient, bundle_dir: Path ) -> Tuple[Bundle, List[Cluster],", "multiple hosts via action, run actions on some of hosts and then delete", "and altered config of cluster, service and component - With two services and", "= self.create_complex_provider(provider_bundle, template='doomed-host') self._run_actions_on_host_and_delete_with_action(provider) cluster_bundle = adcm_client.upload_from_fs(bundles_directory / \"complex_cluster\") cluster_bundle.license_accept() cluster_with_history = self._create_cluster_with_config_history(cluster_bundle)", "upgrade correctly: - objects didn't loose their configs and \"stable\" properties - objects", "'complex': { 'providers': {'host_supplier': complex_objects[0], 'free_hosts': complex_objects[1]}, 'clusters': { 'all_services': complex_objects[2], 'config_history': complex_objects[3],", "clusters, providers, hosts, jobs. All jobs are waited to be finished before returning", "build_objects_comparator( get_compare_value=extract_job_info, field_name='Job info', name_composer=lambda obj: f\"Job with id {obj.id}\" ) jobs: List[Job]", "{ 'name': random_string(13), 'age': str(random.randint(14, 80)), 'custom_field': random_string(12), }, }, 'country_codes': [ {'country':", "cluster_with_job is None: raise ValueError('At least on of simple clusters should have a", "on cheese MILK_COMPONENT = 'milk' # on sauce SPICE_COMPONENT = 'spice' TOMATO_COMPONENT =", "all_tasks = self.create_simple_providers( sdk_client_fs, dirty_dir ) simple_cluster_bundle, simple_clusters, tasks = self.create_simple_clusters(sdk_client_fs, dirty_dir) complex_objects", "is changed, it may break 'actions': set(action.id for action in adcm_object.action_list()), } @allure.step('Wait", "return tuple(cmd_opts.adcm_image.split(\":\", maxsplit=2)) # type: ignore def old_adcm_images() -> Tuple[List[Tuple[str, str]], Any]: \"\"\"A", "sdk_client_fs: ADCMClient, adcm_api_credentials: dict, adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade", "run_service_action_and_assert_result(sauce_service, 'put_on_bread') run_component_action_and_assert_result(sauce_service.component(name=self.SPICE_COMPONENT), 'add_more') run_provider_action_and_assert_result(simple_provider, 'validate', status='failed') @allure.step('Create complex cluster with all services')", "install_cluster_with_two_services.service_add(name=params['lonely_service']) tasks.append(install_cluster_with_two_services.action(name=params['cluster_action']).run()) return cluster_bundle, clusters, tasks @allure.step('Create complex provider and {amount_of_hosts} hosts with", "adcm_image_tags: Tuple[str, str], ) -> None: \"\"\"Test adcm upgrade with encrypted fields\"\"\" cluster", "Bundle, template: str = 'complex-host', amount_of_hosts: int = 18 ) -> Tuple[Provider, Task]:", "language governing permissions and # limitations under the License. \"\"\"Tests for ADCM upgrade\"\"\"", "f\"Job with id {obj.id}\" ) jobs: List[Job] = get_objects_via_pagination(adcm_client.job_list) frozen_objects = {job.job_id: extract_job_info(job)", "of available actions!\\nExpected: {AVAILABLE_ACTIONS}\\nActual:{actions}\" @allure.step(\"Check that previously created cluster exists\") def _check_that_cluster_exists(sdk_client_fs: ADCMClient,", "dict, hosts: tuple): \"\"\"Utility function to run actions on components (host actions too)\"\"\"", "in providers ] one_of_providers.host_list()[-1].config_set_diff({'hosts_file': self.LONG_TEXT}) tasks = [provider.action(name='validate').run() for provider in providers[:3]] +" ]
[ "error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() usr_id =", "Flask, render_template, redirect, url_for, jsonify, make_response, request from Frontend import application # Imports", "return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False,", "= request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE ################# sptfyApi", "print('An error occured getting user playlists, error code: '+str(req.status_code)) raise RequestError('An Error has", "}) if req.status_code != 200: raise RequestError('An Error has occured') req_Json = req.json()", "on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn })", "unexpected error has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes)", "\"Bearer \" + tkn }) if req.status_code != 200: print('An error occured getting", "from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET'])", "has occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else:", "as np from flask import Flask, render_template, redirect, url_for, jsonify, make_response, request from", "made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist',", "try: assert request.path == '/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn') mood", "from flask import Flask, render_template, redirect, url_for, jsonify, make_response, request from Frontend import", "methods = ['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method ==", "except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError", "except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET'])", "has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist'", "'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert", "+ tkn }) if req.status_code != 200: raise RequestError('An Error has occured') req_Json", "error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert request.path ==", "as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return", "= 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com',", "0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn }) if", "@application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method", "occured') req_Json = req.json() usr_id = req_Json['id'] ## Get user Playlists playlists =", "assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',')", "if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'],", "request has been made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error", "error has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url", "login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url", "playlists, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() for", "occured getting user id occured, error code: '+str(req.status_code)) raise RequestError('An Error has occured')", "secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4',", "assert request.method == 'GET' tkn = request.args.get('tkn') ## Get user_id req = requests.get(", "'%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome')", "occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except Exception:", "url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1',", "np from flask import Flask, render_template, redirect, url_for, jsonify, make_response, request from Frontend", "'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror", "occured, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() usr_id", "200: print('An error occured getting user id occured, error code: '+str(req.status_code)) raise RequestError('An", "i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has", "occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return", "'authorization': \"Bearer \" + tkn }) if req.status_code != 200: print('An error occured", "= requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code !=", "tkn = request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer", "## Get user Playlists playlists = [] i = 0 while(len(playlists)==i): req =", "occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert request.path == '/CheckMood' assert", "client_secret import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists',", "continue if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']})", "'message':\"An invalid request has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error", "= requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200:", "request from Frontend import application # Imports application details from a private file", "make_response, request from Frontend import application # Imports application details from a private", "= request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID", "headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200: raise RequestError('An", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None;", "jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has", "occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type of request has", "= SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID})", "of request has been made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected", "req.status_code != 200: raise RequestError('An Error has occured') req_Json = req.json() playlists =", "'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been", "= ['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method == 'GET'", "except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An", "secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust',", "domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify;", "'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on mood req", "i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except", "as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e:", "== '/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists", "domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True);", "request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE", "except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except Exception: return", "getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn')", "= url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index():", "raise RequestError('An Error has occured') req_Json = req.json() for lst in req_Json['items']: images", "== '/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ##", "made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods =", "req.json() for lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url =", "request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID =", "import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert request.path ==", "'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None,", "assert request.path == '/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn') ## Get", "HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q'", "= 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\"))", "return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist():", "== '/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn') ## Get user_id req", "= sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as", "= request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \"", "invalid type of request has been made\"}) except Exception as e: print(e) return", "has been made\"}) except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error", "from details import client_id, client_secret import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler", "request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') #######", "resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>',", "requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type of", "as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def login():", "request.path == '/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood')", "error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert request.path ==", "return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True);", "made\"}) except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"})", "invalid request has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has", "e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return", "jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected", "'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None,", "if req.status_code != 200: print('An error occured getting user id occured, error code:", "url_for, jsonify, make_response, request from Frontend import application # Imports application details from", "!= 200: print('An error occured getting user playlists, error code: '+str(req.status_code)) raise RequestError('An", "= request.args.get('mood') ## Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization':", "= i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"})", "= images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50", "has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url =", "while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code", "resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True);", "from a private file from details import client_id, client_secret import requests from Backend.RequestError", "occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist' assert", "client_id, client_secret import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig')", "+ tkn }) if req.status_code != 200: print('An error occured getting user playlists,", "import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists():", "return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public']", "request.path == '/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn') ## Get user_id", "domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure') return resp if", "req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code", "tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on mood req =", "\"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200: print('An", "= requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code !=", "request.method == 'GET' tkn = request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\",", "!= 200: print('An error occured getting user id occured, error code: '+str(req.status_code)) raise", "@application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2',", "redirect, url_for, jsonify, make_response, request from Frontend import application # Imports application details", "'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror", "print('An error occured getting user id occured, error code: '+str(req.status_code)) raise RequestError('An Error", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "'/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get", "'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None,", "checkMood(): try: assert request.path == '/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn')", "return jsonify({'ok':False, 'message':\"An invalid type of request has been made\"}) except Exception as", "createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn')", "= req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as", "jsonify({'ok':False, 'message':\"An invalid type of request has been made\"}) except Exception as e:", "Frontend import application # Imports application details from a private file from details", "error occured getting user id occured, error code: '+str(req.status_code)) raise RequestError('An Error has", "req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except", "\"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200: raise", "error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() for lst", "user id occured, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json =", "print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def login(): scopes =", "@application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method", "if req.status_code != 200: raise RequestError('An Error has occured') req_Json = req.json() playlists", "been made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"})", "= req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True})", "in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url", "request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on", "jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try:", "== 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on mood", "## Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \"", "RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e:", "Imports application details from a private file from details import client_id, client_secret import", "headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200: print('An error", "\"Bearer \" + tkn }) if req.status_code != 200: raise RequestError('An Error has", "domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True);", "['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method == 'GET' tkn", "make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3',", "# newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return", "'/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn') ## Get user_id req =", "req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True,", "AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except Exception: return jsonify({'ok':False,", "else: return jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has", "requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200: print('An", "Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/')", "if req.status_code != 200: print('An error occured getting user playlists, error code: '+str(req.status_code))", "has occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type of request", "scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url", "lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else:", "import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods", "Get user Playlists playlists = [] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i),", "methods = ['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method ==", "RequestError('An Error has occured') req_Json = req.json() for lst in req_Json['items']: images =", "secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure') return resp if __name__=='__main__': application.run()", "has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert request.path == '/CheckMood'", "occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index')", "'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None,", "type of request has been made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An", "Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods =", "from Frontend import application # Imports application details from a private file from", "playlists = [] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer", "def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url =", "= lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'],", "has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood',", "'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A", "def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com',", "assert request.path == '/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn') mood =", "Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn })", "resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com',", "application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists' assert", "}) if req.status_code != 200: print('An error occured getting user playlists, error code:", "['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123'", "user playlists, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json()", "images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return", "= request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD", "import application # Imports application details from a private file from details import", "AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type of request has been made\"})", "req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code !=", "Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def", "return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request", "request has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"})", "scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return", "getting user id occured, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json", "type of request has been made\"}) except Exception as e: print(e) return jsonify({'ok':False,", "'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure') return resp", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure') return resp if __name__=='__main__':", "has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except", "mood = request.args.get('mood') ## Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={", "'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True);", "e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False,", "assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') ## Get playlists", "= req.json() for lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url", "= make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "req_Json['id'] ## Get user Playlists playlists = [] i = 0 while(len(playlists)==i): req", "index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None,", "@application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "req_Json = req.json() usr_id = req_Json['id'] ## Get user Playlists playlists = []", "has occured') req_Json = req.json() for lst in req_Json['items']: images = lst['images'] if(len(images)==0):", "request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE ################# sptfyApi =", "SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except", "raise RequestError('An Error has occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return", "file from details import client_id, client_secret import requests from Backend.RequestError import RequestError from", "lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url,", "has been made\"}) except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error has", "return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has", "mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE #################", "jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return", "= '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url)", "been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods", "application details from a private file from details import client_id, client_secret import requests", "'message':\"A requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type", "url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp", "[] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" +", "of request has been made\"}) except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An", "image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists})", "if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i", "'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert", "user Playlists playlists = [] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={", "= request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on mood req = requests.get(", "resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com',", "redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def", "PUT BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ########################", "request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" +", "mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn }) if", "import numpy as np from flask import Flask, render_template, redirect, url_for, jsonify, make_response,", "req.status_code != 200: print('An error occured getting user id occured, error code: '+str(req.status_code))", "\" + tkn }) if req.status_code != 200: print('An error occured getting user", "def getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method == 'GET' tkn =", "= ['GET']) def createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method == 'GET'", "newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False,", "e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def login(): scopes", "been made\"}) except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected error has", "METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID =", "= images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except", "################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return", "'+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() usr_id = req_Json['id'] ##", "except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid type of request has been", "= ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope = '%20'.join(scopes) redirect_url = url_for('index') redirect_url = 'http://127.0.0.1:5000'+redirect_url url =", "['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists' assert request.method == 'GET' tkn", "getting user playlists, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json =", "assert request.path == '/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn') mood =", "occured') req_Json = req.json() for lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue", "['GET']) def checkMood(): try: assert request.path == '/CheckMood' assert request.method == 'GET' tkn", "def checkMood(): try: assert request.path == '/CheckMood' assert request.method == 'GET' tkn =", "code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() usr_id = req_Json['id']", "methods = ['GET']) def checkMood(): try: assert request.path == '/CheckMood' assert request.method ==", "user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn }) if", "= req.json() usr_id = req_Json['id'] ## Get user Playlists playlists = [] i", "def createPlaylist(): try: assert request.path == '/createPlaylist' assert request.method == 'GET' tkn =", "## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn", "Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def", "RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as", "image_url = images[1]['url'] else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i =", "except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as", "sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e:", "return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An", "req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code", "render_template, redirect, url_for, jsonify, make_response, request from Frontend import application # Imports application", "req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url =", "@application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert request.path == '/CheckMood' assert request.method", "resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None,", "req.status_code != 200: print('An error occured getting user playlists, error code: '+str(req.status_code)) raise", "e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def", "try: assert request.path == '/getPlaylists' assert request.method == 'GET' tkn = request.args.get('tkn') ##", "unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try: assert request.path", "'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except", "'message':\"An invalid type of request has been made\"}) except Exception as e: print(e)", "playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError", "redirect_url = 'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp =", "RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try:", "Error has occured') req_Json = req.json() for lst in req_Json['items']: images = lst['images']", "unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET']) def createPlaylist(): try: assert request.path", "flask import Flask, render_template, redirect, url_for, jsonify, make_response, request from Frontend import application", "'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror", "jsonify, make_response, request from Frontend import application # Imports application details from a", "a private file from details import client_id, client_secret import requests from Backend.RequestError import", "details from a private file from details import client_id, client_secret import requests from", "playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn", "= req_Json['id'] ## Get user Playlists playlists = [] i = 0 while(len(playlists)==i):", "import Flask, render_template, redirect, url_for, jsonify, make_response, request from Frontend import application #", "'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND", "samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "# Imports application details from a private file from details import client_id, client_secret", "numpy as np from flask import Flask, render_template, redirect, url_for, jsonify, make_response, request", "RequestError('An Error has occured') req_Json = req.json() usr_id = req_Json['id'] ## Get user", "from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert", "tkn = request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE", "for lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url']", "secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general',", "'/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists =", "RequestError('An Error has occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True,", "== 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood') playlists = request.args.get('playlistIDs').split(',') ####### PUT", "return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood():", "'message':\"An invalid type of request has been made\"}) except Exception as e: return", "newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError", "secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust',", "raise RequestError('An Error has occured') req_Json = req.json() usr_id = req_Json['id'] ## Get", "if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as e: return", "'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError", "= 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A", "request has been made\"}) except Exception as e: print(e) return jsonify({'ok':False, 'message':\"An unexpected", "req_Json = req.json() for lst in req_Json['items']: images = lst['images'] if(len(images)==0): continue if(len(images)>=2):", "playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return", "resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure') return", "'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False,", "SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert request.path == '/getPlaylists'", "domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None, secure=True);", "tkn }) if req.status_code != 200: raise RequestError('An Error has occured') req_Json =", "jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False, 'message':\"An invalid", "usr_id = req_Json['id'] ## Get user Playlists playlists = [] i = 0", "return jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"})", "RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid", "as e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods = ['GET'])", "images = lst['images'] if(len(images)==0): continue if(len(images)>=2): image_url = images[1]['url'] else: image_url = images[0]['url']", "i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn", "jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/CheckMood', methods = ['GET']) def checkMood(): try:", "e: return jsonify({'ok':False, 'message':\"An invalid type of request has been made\"}) except Exception", "sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True,", "BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## #", "secure=True); resp.set_cookie('cross-site-cookie', 'applicationadjust', domain='application.adjust.<EMAIL>', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'general', samesite=None, secure=True); resp.headers.add('Set-Cookie','cross-site-cookie=spotify; SameSite=None; Secure')", "occured getting user playlists, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json", "request.path == '/CheckMood' assert request.method == 'GET' tkn = request.args.get('tkn') mood = request.args.get('mood')", "'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'goadjust', domain='go.adjust.com', samesite=None,", "'GET' tkn = request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization':", "}) if req.status_code != 200: print('An error occured getting user id occured, error", "####### PUT BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists)", "'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError: return jsonify({'ok':False,", "requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200:", "'http://127.0.0.1:5000'+redirect_url url = 'https://accounts.spotify.com/authorize?client_id='+client_id+'&redirect_uri='+redirect_url+'&scope='+scope+'&response_type=token&state=123' return redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie',", "id occured, error code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json()", "= 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \" + tkn })", "private file from details import client_id, client_secret import requests from Backend.RequestError import RequestError", "jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"})", "details import client_id, client_secret import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import", "######################## # newPlaylistID = 'https://open.spotify.com/embed/playlist/7xB5RIoWhp2RHVCT43GwWg?si=9XxgO-g9QIS0v4GcIaCH9Q' return jsonify({'ok':True, 'newPlaylistID':newPlaylistID}) except RequestError as e: print(e)", "has occured') req_Json = req.json() usr_id = req_Json['id'] ## Get user Playlists playlists", "+ tkn }) if req.status_code != 200: print('An error occured getting user id", "import client_id, client_secret import requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler", "resp.set_cookie('cross-site-cookie', 'spotify2', domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com',", "except Exception as e: return jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/createPlaylist', methods", "tkn }) if req.status_code != 200: print('An error occured getting user playlists, error", "requests from Backend.RequestError import RequestError from Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods =", "playlists = request.args.get('playlistIDs').split(',') ####### PUT BACKEND CODE METHOD HERE ################# sptfyApi = SptfyApiHndler()", "images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True, 'playlists':playlists}) except RequestError:", "CODE METHOD HERE ################# sptfyApi = SptfyApiHndler() newPlaylistID = sptfyApi.filterPlaylists(client_id,tkn,mood,playlists) ######################## # newPlaylistID", "requesterror has occured\"}) except AssertionError: return jsonify({'ok':False, 'message':\"An invalid request has been made\"})", "redirect(url) @application.route('/welcome') def index(): resp = make_response(render_template(\"index.html\")) resp.set_cookie('cross-site-cookie', 'spotify1', domain='.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie',", "req.json() usr_id = req_Json['id'] ## Get user Playlists playlists = [] i =", "!= 200: raise RequestError('An Error has occured') req_Json = req.json() playlists = req_Json['playlists']['items']", "200: raise RequestError('An Error has occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5):", "Backend.SptfyApiHndler import SptfyApiHndler application.config.from_object('configurations.ProductionConfig') @application.route('/getPlaylists', methods = ['GET']) def getPlaylists(): try: assert request.path", "'authorization': \"Bearer \" + tkn }) if req.status_code != 200: raise RequestError('An Error", "\" + tkn }) if req.status_code != 200: raise RequestError('An Error has occured')", "jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A", "print(e) return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError as e: return jsonify({'ok':False,", "== 'GET' tkn = request.args.get('tkn') ## Get user_id req = requests.get( \"https://api.spotify.com/v1/me\", headers={", "jsonify({'ok':True, 'valid':True}) except RequestError as e: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except", "return jsonify({'ok':True, 'playlists':playlists}) except RequestError: return jsonify({'ok':False, 'message':\"A requesterror has occured\"}) except AssertionError:", "request.args.get('tkn') mood = request.args.get('mood') ## Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\",", "invalid type of request has been made\"}) except Exception as e: return jsonify({'ok':False,", "else: image_url = images[0]['url'] playlists.append({'id':lst['id'], 'isActive':False,'image_url':image_url, 'name':lst['name'], 'tracks':lst['tracks']['total']}) i = i+50 return jsonify({'ok':True,", "Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer \" +", "req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False}) else: return jsonify({'ok':True, 'valid':True}) except RequestError as e:", "requests.get( \"https://api.spotify.com/v1/me\", headers={ 'authorization': \"Bearer \" + tkn }) if req.status_code != 200:", "'+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() for lst in req_Json['items']:", "code: '+str(req.status_code)) raise RequestError('An Error has occured') req_Json = req.json() for lst in", "Error has occured') req_Json = req.json() usr_id = req_Json['id'] ## Get user Playlists", "as e: return jsonify({'ok':False, 'message':\"An invalid type of request has been made\"}) except", "request.args.get('mood') ## Get playlists on mood req = requests.get( \"https://api.spotify.com/v1/search?q=\"+mood+\"&type=playlist&limit=5\", headers={ 'authorization': \"Bearer", "tkn }) if req.status_code != 200: print('An error occured getting user id occured,", "return jsonify({'ok':False, 'message':\"An invalid request has been made\"}) except Exception: return jsonify({'ok':False, 'message':\"An", "try: assert request.path == '/createPlaylist' assert request.method == 'GET' tkn = request.args.get('tkn') mood", "200: print('An error occured getting user playlists, error code: '+str(req.status_code)) raise RequestError('An Error", "Playlists playlists = [] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization':", "= ['GET']) def checkMood(): try: assert request.path == '/CheckMood' assert request.method == 'GET'", "'message':\"An unexpected error has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope =", "application # Imports application details from a private file from details import client_id,", "domain='.accounts.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify3', domain='.community.spotify.com', samesite=None, secure=True); resp.set_cookie('cross-site-cookie', 'spotify4', domain='.www.spotify.com', samesite=None, secure=True);", "Error has occured') req_Json = req.json() playlists = req_Json['playlists']['items'] if(len(playlists)<5): return jsonify({'ok':True, 'valid':False})", "error occured getting user playlists, error code: '+str(req.status_code)) raise RequestError('An Error has occured')", "= [] i = 0 while(len(playlists)==i): req = requests.get(\"https://api.spotify.com/v1/users/\"+usr_id+\"/playlists?limit=\"+str(50)+\"&offset=\"+str(i), headers={ 'authorization': \"Bearer \"", "jsonify({'ok':False, 'message':\"An unexpected error has occured\"}) @application.route('/') def login(): scopes = ['user-read-private','user-read-email','playlist-read-private','playlist-read-collaborative','playlist-modify-public'] scope" ]
[ "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ]", "on 2020-01-16 17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice',", "2.1.15 on 2020-01-16 17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "<filename>timberr/core/migrations/0006_auto_20200116_1824.py # Generated by Django 2.1.15 on 2020-01-16 17:24 from django.db import migrations,", "Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice', name='invoice_id',", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations", "migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations = [", "Generated by Django 2.1.15 on 2020-01-16 17:24 from django.db import migrations, models class", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations =", "models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField(", "= [ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice', name='invoice_id', field=models.CharField(max_length=10, unique=True),", "17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20200116_1747'),", "by Django 2.1.15 on 2020-01-16 17:24 from django.db import migrations, models class Migration(migrations.Migration):", "dependencies = [ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice', name='invoice_id', field=models.CharField(max_length=10,", "[ ('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice', name='invoice_id', field=models.CharField(max_length=10, unique=True), ),", "Django 2.1.15 on 2020-01-16 17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "2020-01-16 17:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core',", "# Generated by Django 2.1.15 on 2020-01-16 17:24 from django.db import migrations, models", "('core', '0005_auto_20200116_1747'), ] operations = [ migrations.AlterField( model_name='invoice', name='invoice_id', field=models.CharField(max_length=10, unique=True), ), ]" ]
[ "task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in", "= self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1'", "cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1,", "range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert (", "host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name))", "self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) ==", "assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else:", "tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i in range(number)] def", ".tasks import exception_task, simple_task from .test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST", ".config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis", "cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) ==", "cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert", "== '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self): self._test_context_managers(10, simple_task)", "name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name),", "= cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert", "exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child", "cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name))", "__exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class", "BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class.", "self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1'", "self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self): self._test_context_managers(10,", "import BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager", "else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with", "self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task,", "manager tests.\"\"\" import redis from tasktiger import Worker from .tasks import exception_task, simple_task", "self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self):", "'0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) ==", "to track number of enter/exit calls \"\"\" def __init__(self, name): self.name = name", "self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager", "\"\"\" def __init__(self, name): self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True", "class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis to track number of", "from tasktiger import Worker from .tasks import exception_task, simple_task from .test_base import BaseTestCase", "REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis to track number", "name): self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0)", "is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self,", "test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self): self._test_context_managers(10, simple_task) self._test_context_managers(10, exception_task, should_fail=True)", "0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if", "'1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' )", "num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i", "+ str(i)) for i in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms =", "from .tasks import exception_task, simple_task from .test_base import BaseTestCase from .config import TEST_DB,", "exception_task, simple_task from .test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object):", "self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type", "exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context", "self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) ==", "manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i in range(number)]", "= name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0)", "= redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def", "should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num):", "i in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] =", "== '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1'", "def __init__(self, name): self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True )", "i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail:", "0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb):", "( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass", "context manager tests.\"\"\" import redis from tasktiger import Worker from .tasks import exception_task,", "test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name))", "import exception_task, simple_task from .test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST class", "( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def", "enter/exit calls \"\"\" def __init__(self, name): self.name = name self.conn = redis.Redis( host=REDIS_HOST,", "redis from tasktiger import Worker from .tasks import exception_task, simple_task from .test_base import", "decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self,", "db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def", "_test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for", "'1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self): self._test_context_managers(10, simple_task) self._test_context_managers(10,", "number): return [ContextManagerTester('cm' + str(i)) for i in range(number)] def _test_context_managers(self, num, task,", "should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0'", "exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def", "def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i in range(number)] def _test_context_managers(self,", "assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' )", "None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return", "return [ContextManagerTester('cm' + str(i)) for i in range(number)] def _test_context_managers(self, num, task, should_fail=False):", "if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) ==", "tasktiger import Worker from .tasks import exception_task, simple_task from .test_base import BaseTestCase from", "for i in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS']", "track number of enter/exit calls \"\"\" def __init__(self, name): self.name = name self.conn", "def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close()", "simple_task from .test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\"", "self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm'", "== '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert (", "'1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms =", "exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase):", "class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i))", "self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def", "TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis to track", "calls \"\"\" def __init__(self, name): self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB,", "[ContextManagerTester('cm' + str(i)) for i in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms", "self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0)", "'1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def", "Uses Redis to track number of enter/exit calls \"\"\" def __init__(self, name): self.name", "Redis to track number of enter/exit calls \"\"\" def __init__(self, name): self.name =", "assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name))", "number of enter/exit calls \"\"\" def __init__(self, name): self.name = name self.conn =", "def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert", "== '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms", "\"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i", "assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self):", "Dummy context manager class. Uses Redis to track number of enter/exit calls \"\"\"", "class. Uses Redis to track number of enter/exit calls \"\"\" def __init__(self, name):", "0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is", "\"\"\" Dummy context manager class. Uses Redis to track number of enter/exit calls", "redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self):", "in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms", "manager class. Uses Redis to track number of enter/exit calls \"\"\" def __init__(self,", "self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) ==", "from .test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy", "in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert", "def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True)", "self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name))", "'1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name))", "tests.\"\"\" import redis from tasktiger import Worker from .tasks import exception_task, simple_task from", "__enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None:", "Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1'", "pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task)", "TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for", "if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\"", "self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val,", "assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1,", "Worker from .tasks import exception_task, simple_task from .test_base import BaseTestCase from .config import", "context manager class. Uses Redis to track number of enter/exit calls \"\"\" def", "self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name))", "assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with cms:", "import redis from tasktiger import Worker from .tasks import exception_task, simple_task from .test_base", "_get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i in range(number)] def _test_context_managers(self, num,", "with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self):", "ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis to track number of enter/exit", "context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' + str(i)) for i in", "not None: self.conn.incr('cm:{}:exit_with_error'.format(self.name)) self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number):", "self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if should_fail: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '1' ) else: assert", "\"\"\"Child context manager tests.\"\"\" import redis from tasktiger import Worker from .tasks import", ") else: assert ( self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop()", "== '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name))", "== '1' assert self.conn.get('cm:{}:exit'.format(cms.name)) == '1' def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True)", ") self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name), 0) self.conn.set('cm:{}:exit_with_error'.format(self.name), 0) def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type,", "= self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task) Worker(self.tiger).run(once=True) for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name))", "import Worker from .tasks import exception_task, simple_task from .test_base import BaseTestCase from .config", "__init__(self, name): self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name),", ".test_base import BaseTestCase from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context", "def test_single_context_manager(self): self._test_context_managers(1, simple_task) self._test_context_managers(1, exception_task, should_fail=True) def test_multiple_context_managers(self): self._test_context_managers(10, simple_task) self._test_context_managers(10, exception_task,", "import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses Redis to", "self.conn.get('cm:{}:exit_with_error'.format(cms[i].name)) == '0' ) def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert", "for i in range(num): assert self.conn.get('cm:{}:enter'.format(cms[i].name)) == '1' assert self.conn.get('cm:{}:exit'.format(cms[i].name)) == '1' if", "range(number)] def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num) self.tiger.config['CHILD_CONTEXT_MANAGERS'] = cms self.tiger.delay(task)", ") def test_fixture(self): cms = self._get_context_managers(1).pop() with cms: pass assert self.conn.get('cm:{}:enter'.format(cms.name)) == '1'", "of enter/exit calls \"\"\" def __init__(self, name): self.name = name self.conn = redis.Redis(", "from .config import TEST_DB, REDIS_HOST class ContextManagerTester(object): \"\"\" Dummy context manager class. Uses", "self.name = name self.conn = redis.Redis( host=REDIS_HOST, db=TEST_DB, decode_responses=True ) self.conn.set('cm:{}:enter'.format(self.name), 0) self.conn.set('cm:{}:exit'.format(self.name),", "self.conn.close() class TestChildContextManagers(BaseTestCase): \"\"\"Child context manager tests.\"\"\" def _get_context_managers(self, number): return [ContextManagerTester('cm' +", "str(i)) for i in range(number)] def _test_context_managers(self, num, task, should_fail=False): cms = self._get_context_managers(num)", "def __enter__(self): self.conn.incr('cm:{}:enter'.format(self.name)) def __exit__(self, exc_type, exc_val, exc_tb): self.conn.incr('cm:{}:exit'.format(self.name)) if exc_type is not", "<reponame>timgates42/tasktiger \"\"\"Child context manager tests.\"\"\" import redis from tasktiger import Worker from .tasks" ]
[ "parameters are available # The file is written in to the same directory", "image to your local machine in GeoTiff format. \"\"\" import descarteslabs as dl", "download an image mosaic. Other parameters are available # The file is written", "scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\", cutline=box, save=True, outfile_basename=\"save_local\", resolution=60, )", "\"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to download an image mosaic.", "to the same directory as the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\",", "Create an aoi feature to clip imagery to box = { \"type\": \"Polygon\",", "your local machine in GeoTiff format. \"\"\" import descarteslabs as dl # Create", "# Two predefined image IDs for mosaic and download. These can be obtained", "available # The file is written in to the same directory as the", "image IDs for mosaic and download. These can be obtained through a Metadata", "obtained through a Metadata or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\",", "written in to the same directory as the script. raster_client = dl.Raster() raster_client.raster(", "Other parameters are available # The file is written in to the same", "\"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\", cutline=box, save=True, outfile_basename=\"save_local\", resolution=60,", "[-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], }", "API call to download an image mosaic. Other parameters are available # The", "GeoTIFF ================================================== This example demonstrates how to save an image to your local", "Raster API call to download an image mosaic. Other parameters are available #", "raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None],", "download. These can be obtained through a Metadata or Scenes API search images", "are available # The file is written in to the same directory as", "33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two predefined image IDs for mosaic", "] # The Raster API call to download an image mosaic. Other parameters", "format. \"\"\" import descarteslabs as dl # Create an aoi feature to clip", "bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\", cutline=box,", "mosaic and download. These can be obtained through a Metadata or Scenes API", "33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } #", "33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two predefined", "to save an image to your local machine in GeoTiff format. \"\"\" import", "} # Two predefined image IDs for mosaic and download. These can be", "for mosaic and download. These can be obtained through a Metadata or Scenes", "save an image to your local machine in GeoTiff format. \"\"\" import descarteslabs", "a Metadata or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] #", "to GeoTIFF ================================================== This example demonstrates how to save an image to your", "[-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two predefined image IDs for", "search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to", "predefined image IDs for mosaic and download. These can be obtained through a", "Two predefined image IDs for mosaic and download. These can be obtained through", "Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API", "dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500],", "IDs for mosaic and download. These can be obtained through a Metadata or", "in GeoTiff format. \"\"\" import descarteslabs as dl # Create an aoi feature", "import descarteslabs as dl # Create an aoi feature to clip imagery to", "# Create an aoi feature to clip imagery to box = { \"type\":", "an aoi feature to clip imagery to box = { \"type\": \"Polygon\", \"coordinates\":", "\"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343],", "raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500],", "These can be obtained through a Metadata or Scenes API search images =", "an image to your local machine in GeoTiff format. \"\"\" import descarteslabs as", "as the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0,", "\"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\", cutline=box, save=True,", "\"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719],", "[ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ],", "inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\",", "\"\"\" import descarteslabs as dl # Create an aoi feature to clip imagery", "is written in to the same directory as the script. raster_client = dl.Raster()", "\"\"\" ================================================== Save image to GeoTIFF ================================================== This example demonstrates how to save", "aoi feature to clip imagery to box = { \"type\": \"Polygon\", \"coordinates\": [", "= dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0,", "\"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066,", "box = { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221,", "to your local machine in GeoTiff format. \"\"\" import descarteslabs as dl #", "# The file is written in to the same directory as the script.", "GeoTiff format. \"\"\" import descarteslabs as dl # Create an aoi feature to", "= [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to download an", "file is written in to the same directory as the script. raster_client =", "to box = { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343],", "directory as the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"],", "the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500],", "demonstrates how to save an image to your local machine in GeoTiff format.", "dl # Create an aoi feature to clip imagery to box = {", "in to the same directory as the script. raster_client = dl.Raster() raster_client.raster( inputs=images,", "descarteslabs as dl # Create an aoi feature to clip imagery to box", "================================================== Save image to GeoTIFF ================================================== This example demonstrates how to save an", "can be obtained through a Metadata or Scenes API search images = [", "same directory as the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\",", "through a Metadata or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ]", "images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to download", "or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster", "and download. These can be obtained through a Metadata or Scenes API search", "feature to clip imagery to box = { \"type\": \"Polygon\", \"coordinates\": [ [", "[ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ]", "# The Raster API call to download an image mosaic. Other parameters are", "] ], } # Two predefined image IDs for mosaic and download. These", "as dl # Create an aoi feature to clip imagery to box =", "Metadata or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The", "], } # Two predefined image IDs for mosaic and download. These can", "[-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two", "local machine in GeoTiff format. \"\"\" import descarteslabs as dl # Create an", "an image mosaic. Other parameters are available # The file is written in", "to clip imagery to box = { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066,", "= { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719],", "================================================== This example demonstrates how to save an image to your local machine", "clip imagery to box = { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343],", "imagery to box = { \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221,", "33.58051349561343], ] ], } # Two predefined image IDs for mosaic and download.", "how to save an image to your local machine in GeoTiff format. \"\"\"", "image to GeoTIFF ================================================== This example demonstrates how to save an image to", "\"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to download an image mosaic. Other", "This example demonstrates how to save an image to your local machine in", "machine in GeoTiff format. \"\"\" import descarteslabs as dl # Create an aoi", "[ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call to download an image", "API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\", \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035036_20180602_20180602_01_RT_v1\", ] # The Raster API call", "33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two predefined image IDs", "[-108.64292971398066, 33.58051349561343], ] ], } # Two predefined image IDs for mosaic and", "mosaic. Other parameters are available # The file is written in to the", "\"blue\", \"alpha\"], scales=[[0, 5500], [0, 5500], [0, 5500], None], data_type=\"Byte\", cutline=box, save=True, outfile_basename=\"save_local\",", "be obtained through a Metadata or Scenes API search images = [ \"landsat:LC08:01:RT:TOAR:meta_LC08_L1TP_035037_20180602_20180602_01_RT_v1\",", "call to download an image mosaic. Other parameters are available # The file", "script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\", \"blue\", \"alpha\"], scales=[[0, 5500], [0,", "Save image to GeoTIFF ================================================== This example demonstrates how to save an image", "example demonstrates how to save an image to your local machine in GeoTiff", "The file is written in to the same directory as the script. raster_client", "image mosaic. Other parameters are available # The file is written in to", "The Raster API call to download an image mosaic. Other parameters are available", "the same directory as the script. raster_client = dl.Raster() raster_client.raster( inputs=images, bands=[\"red\", \"green\",", "{ \"type\": \"Polygon\", \"coordinates\": [ [ [-108.64292971398066, 33.58051349561343], [-108.27082685426221, 33.58051349561343], [-108.27082685426221, 33.83925599538719], [-108.64292971398066,", "[-108.27082685426221, 33.83925599538719], [-108.64292971398066, 33.83925599538719], [-108.64292971398066, 33.58051349561343], ] ], } # Two predefined image", "to download an image mosaic. Other parameters are available # The file is" ]
[ "with open('README.md', 'r') as f: long_description = f.read() with open('LICENSE', 'r') as f:", "chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text, author='<NAME>', author_email='<EMAIL>', url='https://github.com/MedleyLabs/DeepSomatics', packages=[],", "with open('LICENSE', 'r') as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental,", "<reponame>MedleyLabs/DeepAutonomic from setuptools import setup with open('README.md', 'r') as f: long_description = f.read()", "description='An experimental, chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text, author='<NAME>', author_email='<EMAIL>',", "therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text, author='<NAME>', author_email='<EMAIL>', url='https://github.com/MedleyLabs/DeepSomatics', packages=[], )", "as f: long_description = f.read() with open('LICENSE', 'r') as f: license_text = f.read()", "setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description,", "open('README.md', 'r') as f: long_description = f.read() with open('LICENSE', 'r') as f: license_text", "= f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing with", "'r') as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist", "version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text, author='<NAME>',", "experimental, chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text, author='<NAME>', author_email='<EMAIL>', url='https://github.com/MedleyLabs/DeepSomatics',", "f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic", "= f.read() with open('LICENSE', 'r') as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1',", "license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing", "f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing with biofeedback',", "setuptools import setup with open('README.md', 'r') as f: long_description = f.read() with open('LICENSE',", "name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for somatic experiencing with biofeedback', long_description=long_description, license=license_text,", "f.read() with open('LICENSE', 'r') as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An", "open('LICENSE', 'r') as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven", "long_description = f.read() with open('LICENSE', 'r') as f: license_text = f.read() setup( name='DeepSomatics',", "import setup with open('README.md', 'r') as f: long_description = f.read() with open('LICENSE', 'r')", "as f: license_text = f.read() setup( name='DeepSomatics', version='0.0.1', description='An experimental, chatbot-driven therapist for", "setup with open('README.md', 'r') as f: long_description = f.read() with open('LICENSE', 'r') as", "'r') as f: long_description = f.read() with open('LICENSE', 'r') as f: license_text =", "f: long_description = f.read() with open('LICENSE', 'r') as f: license_text = f.read() setup(", "from setuptools import setup with open('README.md', 'r') as f: long_description = f.read() with" ]
[ "parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\",", "action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\",", "import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from", "specified exec profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True ) )", "workflow output directory and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\",", "importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module)", "module that containes such a class. Please see the commandline help for details.", ") assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec profile module", "c2wl_rocket.execprofile or if using the commandline specify the name or path to a", "output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start", "a python file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" )", "is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible", "args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\")", "f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True", "args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location(", "= argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible CWL execution engine.'", "\"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\"", "for remote availablity within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text,", "isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec profile is invalid.", "executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def", "from inspect import isclass import importlib import functools import yaml ## get cwltool", "and a contained exec profile class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\").", "of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within the current network. \"\"\",", "\"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in the CWL document.\",", ") runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram", "\"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within", "= subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow given run input parameter.\"", "if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments", "yaml ## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def", "availablity within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port", "functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel", "import make_custom_tool from .log_handling import error_message from copy import copy import typing_extensions from", "job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments over to main exec function:", "inspect import isclass import importlib import functools import yaml ## get cwltool default", "class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\"", "has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile)", "intermediate workflow outputs to avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\",", "parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an", "= args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name", ". import worker from .tool_handling import make_custom_tool from .log_handling import error_message from copy", "is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message(", "to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\",", "default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args", "cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as", "cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from .", "exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args) if __name__ == \"__main__\":", "try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module", "cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is None: parser = argparse.ArgumentParser(", "containes such a class. Please see the commandline help for details. \"\"\", is_known=True", "args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\"", "directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to avoid", "import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors", "at c2wl_rocket.execprofile or if using the commandline specify the name or path to", "import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker from", "\"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if", "module and a contained exec profile class sperated by \\\":\\\" (e.g. the default", "= args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl)", "elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec,", "\\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path to a python file containing", "c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params", "recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output", "= args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir =", "\"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of", "either specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using the", "web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class", "note here class not # the path to the module is required outdir=os.path.abspath('.'),", "exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec", "remote availablity within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\"", "help=\"Move output files to the workflow output directory and delete \" \"intermediate output", "flexible CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ##", "args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args)", "arguments over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif", "see the commandline help for details. \"\"\", is_known=True ) assert \":\" in args.exec_profile,", "\\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert", "spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError(", "service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\"", "subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP", "parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text,", "directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output", "intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files", "be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\"", "containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a", "prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate", "\"\"\" The specified exec profile class does not inherit from ExecProfileBase at c2wl_rocket.execprofile.", "spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\"", ") exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the", "module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name),", "raise AssertionError( error_message( \"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could not", "cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content =", "c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs", ") args = parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message =", "subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow given", "to a module that containes such a class. Please see the commandline help", "subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser(", "import yaml ## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([])", "parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start", "of a CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging", "help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\",", "default=\"move\", help=\"Move output files to the workflow output directory and delete \" \"intermediate", "specify the full path to a python file containing an exec profile class", "workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context =", "Please specify the name to a python module and a contained exec profile", "parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text,", "details. \"\"\", is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0]", "exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile =", "workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" )", "the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver.", "no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and", "runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram =", "import copy import typing_extensions from inspect import isclass import importlib import functools import", "args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content", "a python module and a contained exec profile class sperated by \\\":\\\" (e.g.", "exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try:", "hand arguments over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context )", "output files to the workflow output directory and delete \" \"intermediate output directories", "error_message( \"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could not be imported.", "parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args()", "to the workflow output directory and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\"", "avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move", "cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments over", "float(\"inf\") # hand arguments over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context,", "the workflow output directory and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" )", ") assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1]", "default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is", "== \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please", "importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The specified exec profile module", "\"main\", \"\"\" The specified exec profile is invalid. Please either specify a class", "= functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if", "exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to avoid recomputing steps.\", default=\"\"", "exec profile is invalid. Please either specify a class inheriting from ExecProfileBase at", "\\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except:", ") parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group()", "launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow given run", "could not be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message(", "\\\"0.0.0.0\\\" for remote availablity within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\",", ") parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args =", "MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand", "args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert", "default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to avoid recomputing", "IP of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within the current network.", "ExecProfileBase at c2wl_rocket.execprofile or if using the commandline specify the name or path", "args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs", "\"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker", "help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution", "class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile,", "input_params:str, exec_profile=LocalToolExec, # please note here class not # the path to the", "files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy", "= importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec)", "): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug,", "delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave", "for details. \"\"\", is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name =", "ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec profile class does not inherit", "specify the name or path to a module that containes such a class.", "contained exec profile class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you", "from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document", "or \"leave\" debug=False ): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args", "point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix,", "if using the commandline specify the name or path to a module that", "CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile,", "or if using the commandline specify the name or path to a module", "to avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\",", "the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\",", "help=\"Directory to cache intermediate workflow outputs to avoid recomputing steps.\", default=\"\" ) exgroup", "using the commandline specify the name or path to a module that containes", "required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\" debug=False", "The specified exec profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True )", "Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document,", "action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the workflow output directory, don't", "a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML", "run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile',", "directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate", "exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\",", "assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in the CWL", "const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\",", "cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores =", "move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main API", "args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified", "\"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files", "if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec profile is", "parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible CWL execution", "class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using the commandline specify the", "start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\",", "else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments over to main", "main(args=None): if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket -", ") args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\",", "worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here", "parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text,", "the name to a python module and a contained exec profile class sperated", "\"\"\", is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name", "is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec", ") parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for remote", "current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\",", "exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The", "in the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial(", "exec profile class does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True )", "the commandline specify the name or path to a module that containes such", "except: raise AssertionError( error_message( \"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could", ") parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\",", "within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of", "Port of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand == \"launch\":", "exec profile. Please specify the name to a python module and a contained", "= yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in", "(e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" )", "(e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path to a", "loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\"", "\"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER,", "= cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores", "job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\")", ".exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker", "error_message( \"main\", \"\"\" The specified exec profile class does not inherit from ExecProfileBase", "default=\"move\", help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\",", "\"main\", \"No cwlVersion as specified in the CWL document.\", is_known=True ) workflow_metadata =", "= error_message( \"main\", \"\"\" The specified exec profile is invalid. Please either specify", "nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output", "or path to a module that containes such a class. Please see the", "const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the workflow output directory, don't delete", "{\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor", "specified in the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object =", "import absolute_import import os import argparse import cwltool.main import cwltool.argparser import cwltool.utils from", "## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None):", "== \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec", "output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in", "document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata", "copy import typing_extensions from inspect import isclass import importlib import functools import yaml", "the commandline help for details. \"\"\", is_known=True ) assert \":\" in args.exec_profile, \\", "workflow output directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand", "import argparse import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec", "the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path to a python", "default=\"5000\" ) args = parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message", "\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True", "cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context", "cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor", "def main(args=None): if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket", "and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\",", "run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class not # the path", "such a class. Please see the commandline help for details. \"\"\", is_known=True )", "CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand", "SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments over to main exec", ") elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str,", ") workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context", "exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start(", "= args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs =", "exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow", "is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name =", "with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message(", "Copy output files to the workflow output directory, don't delete intermediate output directories.", "help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify", "files to the workflow output directory and delete \" \"intermediate output directories (default).\",", "debug=False ): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace(", "class does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args =", "= args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl:", "Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir,", "cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix", "intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\",", "outputs to avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\",", "output files in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\"", "copy import copy import typing_extensions from inspect import isclass import importlib import functools", "= cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is None: parser =", "argparse import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from", "argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible CWL execution engine.' )", "class. Please see the commandline help for details. \"\"\", is_known=True ) assert \":\"", "exec profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True ) ) assert", "the full path to a python file containing an exec profile class (e.g.", "help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in", "exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module =", "= parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser( \"launch\",", "module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name)", "import MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling import make_custom_tool from .log_handling", "directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker", "exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has no", "import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor,", "= parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\",", "= args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document,", "specified exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile", "dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a", "exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory", "to the workflow output directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" )", ") ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec profile", "issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec profile class does not", "or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') )", "format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup =", "delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser(", "cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as", "error_message from copy import copy import typing_extensions from inspect import isclass import importlib", "name to a python module and a contained exec profile class sperated by", "subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow given run input parameter.\" )", "can specify the full path to a python file containing an exec profile", "not # the path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\",", "sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full", "import importlib import functools import yaml ## get cwltool default args: cwltool_ap =", "absolute_import import os import argparse import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile", "debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args) if __name__ ==", "get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if", "default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for", "\"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir", "is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata )", "exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else", "\"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note", "Alternatively you can specify the full path to a python file containing an", "a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host.", "a module that containes such a class. Please see the commandline help for", "= float(\"inf\") # hand arguments over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor,", "job_executor.max_cores = float(\"inf\") # hand arguments over to main exec function: cwltool.main.main( args=cwltool_args,", "current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate", "\"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" )", "# please note here class not # the path to the module is", "execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch:", "'--exec-profile', help=\"\"\"Specify an exec profile. Please specify the name to a python module", "default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide", "profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module,", "None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible CWL", "as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion", "help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver", "AssertionError( error_message( \"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could not be", "one of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main API entry point.", "type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand", "in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\",", "cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class not # the path to", "assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\"", "\"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\",", "error_message( \"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\".", ".log_handling import error_message from copy import copy import typing_extensions from inspect import isclass", "workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor()", "args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, #", "help=\"\"\" Port of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand ==", "hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has", "cache intermediate workflow outputs to avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group()", "to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand ==", "file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide", ") parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec", "outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\" debug=False ):", "import os import argparse import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import", "typing_extensions from inspect import isclass import importlib import functools import yaml ## get", "from .log_handling import error_message from copy import copy import typing_extensions from inspect import", "commandline help for details. \"\"\", is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message", "to a python file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\"", "python file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document',", "an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL", "worker from .tool_handling import make_custom_tool from .log_handling import error_message from copy import copy", ".tool_handling import make_custom_tool from .log_handling import error_message from copy import copy import typing_extensions", "directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a", "the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool,", "= importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message(", "from __future__ import absolute_import import os import argparse import cwltool.main import cwltool.argparser import", "help for details. \"\"\", is_known=True ) assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name", "worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify", "functools import yaml ## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args =", "loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor()", "type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to avoid recomputing steps.\", default=\"\" )", "type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to", "tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON format.\" )", "loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run(", "cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling import make_custom_tool from", "from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling import make_custom_tool", "\":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module", "commandline specify the name or path to a module that containes such a", ") parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify the name to a", "path to a python file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\",", "\\\"{exec_profile_module_name}\\\" could not be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\", "web_server_port=int(args.web_server_port) ) def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class not", "CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\"", "cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\",", "cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs", "\\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase),", ") cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir", "import typing_extensions from inspect import isclass import importlib import functools import yaml ##", "at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order =", "The specified exec profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True )", "CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or", "try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise", "in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module =", "output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to", "os import argparse import cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase,", "the path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one", "given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p',", "\" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output", "help=\"\"\" Copy output files to the workflow output directory, don't delete intermediate output", "exec_profile=LocalToolExec, # please note here class not # the path to the module", "parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow given run input", "help=\"Provide input parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory,", "type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text,", "isclass import importlib import functools import yaml ## get cwltool default args: cwltool_ap", "path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of", "directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the", "exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\" )", "ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling", "\"main\", \"\"\" The specified exec profile class does not inherit from ExecProfileBase at", "a contained exec profile class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively", "cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified", "(default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output", "assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec profile", "# one of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main API entry", ") exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX", "a class. Please see the commandline help for details. \"\"\", is_known=True ) assert", "default=\"move\", help=\"\"\" Copy output files to the workflow output directory, don't delete intermediate", "messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify the name to", "help=\"Start execution of a CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\",", "description='Customizable CWL Rocket - A highly flexible CWL execution engine.' ) subparser =", "by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path", "default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path to a python file", "imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The", "over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand", "= job_executor.max_cores = float(\"inf\") # hand arguments over to main exec function: cwltool.main.main(", "cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port)", "= {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args))", "parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the workflow output directory", "The specified exec profile is invalid. Please either specify a class inheriting from", "does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args)", "specify the name to a python module and a contained exec profile class", "\"copy\", or \"leave\" debug=False ): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\"", "parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters", "parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current", "\"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str):", "module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or", "# hand arguments over to main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context", "\"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile,", "= MultithreadedJobExecutor() if cwltool_args.parallel \\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") #", "# subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" )", "\"launch\", help=\"Start execution of a CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\",", "or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON format.\"", "the name or path to a module that containes such a class. Please", "input parameters in YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default", "prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly flexible CWL execution engine.' ) subparser", "except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except:", "profile. Please specify the name to a python module and a contained exec", "exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the workflow", "const=\"move\", default=\"move\", help=\"Move output files to the workflow output directory and delete \"", "import functools import yaml ## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args", "action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the workflow output directory and delete", "help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within the current", "\\ else SingleJobExecutor() job_executor.max_ram = job_executor.max_cores = float(\"inf\") # hand arguments over to", "the workflow output directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) #", "output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to", "Rocket - A highly flexible CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab", "webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile,", "to cache intermediate workflow outputs to avoid recomputing steps.\", default=\"\" ) exgroup =", "a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using the commandline specify", "= copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix =", "= subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\"", "directory, default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix", "highly flexible CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' )", "\"leave\" debug=False ): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args =", "subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\" ) parser_start_worker.add_argument(\"-H\",", "instance.\" ) parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for", "an exec profile. Please specify the name to a python module and a", "full path to a python file containing an exec profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\").", "that containes such a class. Please see the commandline help for details. \"\"\",", "exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec", "ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order", "default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\",", "engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch", "profile module \\\"{exec_profile_module_name}\\\" has no class \\\"{exec_profile_class_name}\\\". \"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module,", "The specified exec profile class does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\",", "profile class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify", ") # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service instance.\"", "invalid. Please either specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if", "tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\"", "cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(),", "path to a module that containes such a class. Please see the commandline", "class not # the path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\",", "intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs", "parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify the name to a python", "parser_start_worker.add_argument(\"-H\", \"--web_server_host\", type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity", "specified exec profile is invalid. Please either specify a class inheriting from ExecProfileBase", "Please see the commandline help for details. \"\"\", is_known=True ) assert \":\" in", "= parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the workflow output", "CWL Rocket - A highly flexible CWL execution engine.' ) subparser = parser.add_subparsers(", "= args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec =", "JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup", "of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main API entry point. Executes", "cwltool.main import cwltool.argparser import cwltool.utils from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import", "default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to", "output directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker:", "debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify the", "runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) ) def run( cwl_document:str,", "cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main", "Specify \\\"0.0.0.0\\\" for remote availablity within the current network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\",", "LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling import", "from .exec_profile import ExecProfileBase, LocalToolExec from cwltool.executors import MultithreadedJobExecutor, SingleJobExecutor from . import", "exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the workflow output directory,", "if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A", "a CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level", "from copy import copy import typing_extensions from inspect import isclass import importlib import", "\"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec profile", "entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir,", "exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX )", "mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No", "A highly flexible CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand'", "\\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params',", ") ## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a CWL", "SingleJobExecutor from . import worker from .tool_handling import make_custom_tool from .log_handling import error_message", "class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the", "= args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context =", "output files to the workflow output directory, don't delete intermediate output directories. \"\"\",", "of webserver. \"\"\", default=\"5000\" ) args = parser.parse_args() if args.subcommand == \"launch\": if", "\\ error_message( \"main\", \"\"\" The specified exec profile class does not inherit from", "inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using the commandline specify the name", "## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of a CWL workflow", "workflow outputs to avoid recomputing steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\",", "if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The", "exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The specified exec", "\"\"\", is_known=True ) args.exec_profile = getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\", "argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args) if __name__", "dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the workflow", "\"main\", \"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" could not be imported. \"\"\",", "help=\"Output directory, default current directory\", default=os.path.abspath('.') ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path", ") exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output files to the workflow output", "args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args))", "for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow", "cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object = functools.partial( make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor =", "\\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can specify the full path to", "sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch = subparser.add_parser( \"launch\", help=\"Start execution of", "directory and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\",", "= args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug =", "cwlVersion as specified in the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]}", "profile is invalid. Please either specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile", "cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is None: parser", "from ExecProfileBase at c2wl_rocket.execprofile or if using the commandline specify the name or", "is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir =", "MultithreadedJobExecutor, SingleJobExecutor from . import worker from .tool_handling import make_custom_tool from .log_handling import", "make_custom_tool, exec_profile_class=args.exec_profile, workflow_metadata=workflow_metadata ) runtime_context = cwltool.main.RuntimeContext(vars(cwltool_args)) job_executor = MultithreadedJobExecutor() if cwltool_args.parallel \\", "\"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs )", "dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output directories.\",", "cwltool_ap.parse_args([]) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL", "args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir", "cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug loading_context = cwltool.main.LoadingContext(vars(cwltool_args)) with", "dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker = subparser.add_parser( \"start_worker\", help=\"Start a worker service", "cwltool default args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args", "workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input parameters in YAML or JSON", "str): exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec profile is invalid. Please", "steps.\", default=\"\" ) exgroup = parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files", "exgroup.add_argument(\"--move-outputs\", action=\"store_const\", const=\"move\", default=\"move\", help=\"Move output files to the workflow output directory and", "output directory and delete \" \"intermediate output directories (default).\", dest=\"move_outputs\" ) exgroup.add_argument(\"--leave-outputs\", action=\"store_const\",", "input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify", ") def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class not #", "import isclass import importlib import functools import yaml ## get cwltool default args:", "import error_message from copy import copy import typing_extensions from inspect import isclass import", "args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host, web_server_port=int(args.web_server_port) )", "exec_profile_invalid_message = error_message( \"main\", \"\"\" The specified exec profile is invalid. Please either", "error_message( \"main\", \"No cwlVersion as specified in the CWL document.\", is_known=True ) workflow_metadata", "parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message( \"main\", \"\"\"", "getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified", "copy(cwltool_default_args) cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix", "not be imported. \"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\",", "args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug = args.debug", "not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow", "\"move\", \"copy\", or \"leave\" debug=False ): \"\"\" Main API entry point. Executes c2wl_rocket.__main__.main\"", "= cwltool_ap.parse_args([]) def main(args=None): if args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable", "don't delete intermediate output directories. \"\"\", dest=\"move_outputs\" ) # subcommand start_worker: parser_start_worker =", "in intermediate output directories.\", dest=\"move_outputs\" ) exgroup.add_argument(\"--copy-outputs\", action=\"store_const\", const=\"copy\", default=\"move\", help=\"\"\" Copy output", "exec profile class sperated by \\\":\\\" (e.g. the default \\\"c2wl_rocket.exec_profile:LocalToolExec\\\"). Alternatively you can", "= argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args) if", "specified exec profile class does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True", "is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", # one of \"move\", \"copy\", or \"leave\"", ") exgroup.add_argument(\"--leave-outputs\", action=\"store_const\", const=\"leave\", default=\"move\", help=\"Leave output files in intermediate output directories.\", dest=\"move_outputs\"", "args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name)", "args.exec_profile.split(\":\")[1] try: exec_profile_module = importlib.import_module(exec_profile_module_name) except: try: spec = importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name )", "API entry point. Executes c2wl_rocket.__main__.main\" \"\"\" args = argparse.Namespace( debug=debug, exec_profile=exec_profile, cwl_document=cwl_document, input_params=[input_params],", "webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within the current network. \"\"\", default=\"localhost\"", "from .tool_handling import make_custom_tool from .log_handling import error_message from copy import copy import", "execution of a CWL workflow given run input parameter.\" ) parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print", "profile class does not inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args", "here class not # the path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX,", "importlib import functools import yaml ## get cwltool default args: cwltool_ap = cwltool.argparser.arg_parser()", "yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in the", "host. Specify \\\"0.0.0.0\\\" for remote availablity within the current network. \"\"\", default=\"localhost\" )", ") subparser = parser.add_subparsers( help=\"CWLab sub-commands\", dest='subcommand' ) ## subcommand launch: parser_launch =", "please note here class not # the path to the module is required", "= importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The specified exec profile", "to a python module and a contained exec profile class sperated by \\\":\\\"", "\\ error_message( \"main\", f\"\"\" The specified exec profile module \\\"{exec_profile_module_name}\\\" has no class", "args = parser.parse_args() if args.subcommand == \"launch\": if isinstance(args.exec_profile, str): exec_profile_invalid_message = error_message(", "assert \":\" in args.exec_profile, \\ exec_profile_invalid_message exec_profile_module_name = args.exec_profile.split(\":\")[0] exec_profile_class_name = args.exec_profile.split(\":\")[1] try:", "help=\"\"\"Specify an exec profile. Please specify the name to a python module and", "specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using the commandline", "network. \"\"\", default=\"localhost\" ) parser_start_worker.add_argument(\"-P\", \"--web_server_port\", type=typing_extensions.Text, help=\"\"\" Port of webserver. \"\"\", default=\"5000\"", "\"\"\", is_known=True ) ) assert hasattr(exec_profile_module, exec_profile_class_name), \\ error_message( \"main\", f\"\"\" The specified", "is invalid. Please either specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or", ") exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache intermediate workflow outputs to avoid recomputing steps.\",", "type=typing_extensions.Text, help=\"\"\" IP of webserver host. Specify \\\"0.0.0.0\\\" for remote availablity within the", "from . import worker from .tool_handling import make_custom_tool from .log_handling import error_message from", "# the path to the module is required outdir=os.path.abspath('.'), tmp_outdir_prefix=cwltool.utils.DEFAULT_TMP_PREFIX, cachedir=\"\", move_outputs=\"move\", #", "you can specify the full path to a python file containing an exec", "\"\"\" The specified exec profile is invalid. Please either specify a class inheriting", "error_message( \"main\", \"\"\" The specified exec profile is invalid. Please either specify a", "args: cwltool_ap = cwltool.argparser.arg_parser() cwltool_default_args = cwltool_ap.parse_args([]) def main(args=None): if args is None:", "name or path to a module that containes such a class. Please see", "open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in cwl_content.keys(), error_message( \"main\",", "level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please specify the name", "help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\", type=typing_extensions.Text, help=\"Directory to cache", "def run( cwl_document:str, input_params:str, exec_profile=LocalToolExec, # please note here class not # the", "YAML or JSON format.\" ) parser_launch.add_argument(\"--outdir\", type=typing_extensions.Text, help=\"Output directory, default current directory\", default=os.path.abspath('.')", "__future__ import absolute_import import os import argparse import cwltool.main import cwltool.argparser import cwltool.utils", "cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir = args.cachedir cwltool_args.move_outputs = args.move_outputs cwltool_args.debug", "= getattr(exec_profile_module, exec_profile_class_name) assert isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The", "in cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in the CWL document.\", is_known=True", "make_custom_tool from .log_handling import error_message from copy import copy import typing_extensions from inspect", "inherit from ExecProfileBase at c2wl_rocket.execprofile. \"\"\", is_known=True ) cwltool_args = copy(cwltool_default_args) cwltool_args.workflow =", "\"No cwlVersion as specified in the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\":", "main exec function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\":", "python module and a contained exec profile class sperated by \\\":\\\" (e.g. the", "Please either specify a class inheriting from ExecProfileBase at c2wl_rocket.execprofile or if using", "= cwltool.main.LoadingContext(vars(cwltool_args)) with open(args.cwl_document, mode=\"r\") as cwl: cwl_content = yaml.load(cwl) assert \"cwlVersion\" in", "cwl_content.keys(), error_message( \"main\", \"No cwlVersion as specified in the CWL document.\", is_known=True )", ") parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or tool.\" ) parser_launch.add_argument('input_params', nargs=argparse.REMAINDER, help=\"Provide input", ") exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\", \"\"\" The specified", "isclass(args.exec_profile) and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec profile class", "and issubclass(args.exec_profile, ExecProfileBase), \\ error_message( \"main\", \"\"\" The specified exec profile class does", "action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile. Please", "import worker from .tool_handling import make_custom_tool from .log_handling import error_message from copy import", "args is None: parser = argparse.ArgumentParser( prog=\"C2WL-Rocket\", description='Customizable CWL Rocket - A highly", "profile class (e.g. \\\"/path/to/my/exec_profiles.py:CustomExec\\\"). \"\"\", default=\"c2wl_rocket.exec_profile:LocalToolExec\" ) parser_launch.add_argument('cwl_document', help=\"Provide a CWL workflow or", "parser_launch.add_argument(\"--debug\", action=\"store_true\", help=\"Print debugging level messages.\" ) parser_launch.add_argument('-p', '--exec-profile', help=\"\"\"Specify an exec profile.", "- A highly flexible CWL execution engine.' ) subparser = parser.add_subparsers( help=\"CWLab sub-commands\",", "cwl_document=cwl_document, input_params=[input_params], outdir=outdir, tmp_outdir_prefix=tmp_outdir_prefix, cachedir=cachedir, move_outputs=move_outputs ) main(args) if __name__ == \"__main__\": main()", "as specified in the CWL document.\", is_known=True ) workflow_metadata = {\"cwlVersion\": cwl_content[\"cwlVersion\"]} loading_context.construct_tool_object", "importlib.util.spec_from_file_location( \"exec_profile_module\", exec_profile_module_name ) exec_profile_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(exec_profile_module) except: raise AssertionError( error_message( \"main\",", "= parser_launch.add_mutually_exclusive_group() exgroup.add_argument(\"--tmp-outdir-prefix\", type=typing_extensions.Text, help=\"Path prefix for intermediate output directories\", default=cwltool.utils.DEFAULT_TMP_PREFIX ) exgroup.add_argument(\"--cachedir\",", "files to the workflow output directory, don't delete intermediate output directories. \"\"\", dest=\"move_outputs\"", "cwltool_args.workflow = args.cwl_document cwltool_args.job_order = args.input_params cwltool_args.outdir = args.outdir cwltool_args.tmp_outdir_prefix = args.tmp_outdir_prefix cwltool_args.cachedir", "function: cwltool.main.main( args=cwltool_args, executor=job_executor, loadingContext=loading_context, runtimeContext=runtime_context ) elif args.subcommand == \"start_worker\": worker.start( web_server_host=args.web_server_host," ]
[ "item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type =", "= [0] * 4 for idx, methods in enumerate(payment_list): for method in methods:", "name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))]", "* len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span()", "and span[1] <= pos[1]: borrower_type[idx] = 1 for name in lenders: main =", "= 0 interest_value = 0 interest_type = [0] * 4 for pattern, factor", "TODO: replace the interest? # 4. payment methods payment = [0] * 4", "'手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [],", "in enumerate(lender_pos): if span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx] = 1", "enumerate(payment_list): for method in methods: if method in main: payment[idx + 1] =", "(re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval =", "payment = [0] * 4 for idx, methods in enumerate(payment_list): for method in", "+ guarantee + [interest] + [ interest_value] + interest_type + payment + repayment", "= True borrowers = [] borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1))", "-*- coding: utf-8 -*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'),", "['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and legal", "120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36,", "subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0] *", "+ [interest] + [ interest_value] + interest_type + payment + repayment + agreement", "any(guarantee): guarantee[0] = 1 # 3. interest interest = 0 interest_value = 0", "idx, methods in enumerate(payment_list): for method in methods: if method in main: payment[idx", "'法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count =", "any(repayment): repayment[0] = 1 # 5. agreements agreement = [0] * 6 for", "and span[1] <= pos[1]: lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos): if", "guarantee = [0, 0, 0] if '抵押' in main: guarantee[1] = 1 if", "'凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1.", "* 3 if '已还款' in main: repayment[1] = 1 if '尚未还款' in main:", "for idx, methods in enumerate(payment_list): for method in methods: if method in main:", "# 3. interest interest = 0 interest_value = 0 interest_type = [0] *", "guarantee[1] or guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0] = 1 #", "0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同',", "idx = item.span()[1] lender_type = [0] * len(lenders) first = True borrowers =", "for name in lenders: main = main.replace('原告' + name, '原告').replace(name, '原告') for name", "if not any(repayment): repayment[0] = 1 # 5. agreements agreement = [0] *", "= main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type =", "guarantee[2] = 1 if not any(guarantee): guarantee[0] = 1 # 3. interest interest", "1 if not any(agreement): agreement[0] = 1 # TODO: concat info + main", "subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders = [] lender_pos = [] for", "lender_type = [0] * len(lenders) first = True borrowers = [] borrower_pos =", "in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0]))", "1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval in enumerate(interest_interval):", "if span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx] = 1 for idx,", "# TODO: replace the interest? # 4. payment methods payment = [0] *", "payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据',", "borrower_type + [borrower_count] + guarantee + [interest] + [ interest_value] + interest_type +", "1 for name in lenders: main = main.replace('原告' + name, '原告').replace(name, '原告') for", "lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos): if span[0] >= pos[0] and", "[lender_count] + borrower_type + [borrower_count] + guarantee + [interest] + [ interest_value] +", "'被告') for name in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type", "method in main: payment[idx + 1] = 1 break if not any(payment): payment[0]", "= 0 lenders = [] lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1))", "sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders = [] lender_pos", "<= pos[1]: borrower_type[idx] = 1 for name in lenders: main = main.replace('原告' +", "guarantee + [interest] + [ interest_value] + interest_type + payment + repayment +", "= [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']]", "for item in pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2)) * factor,", "text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx =", "= 1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval in", "item.span()[1] lender_type = [0] * len(lenders) first = True borrowers = [] borrower_pos", "item.span() for idx, pos in enumerate(lender_pos): if span[0] > pos[0] and span[1] <=", "= 1 if not any(guarantee): guarantee[0] = 1 # 3. interest interest =", "'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat =", "= max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval in enumerate(interest_interval): if interest_value", "[] borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0]))", "import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'),", "else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers)", "= 1 if not any(repayment): repayment[0] = 1 # 5. agreements agreement =", "<= pos[1]: lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos): if span[0] >=", "'抵押' in main: guarantee[1] = 1 if '担保' in main: guarantee[2] = 1", "interest interest = 0 interest_value = 0 interest_type = [0] * 4 for", "in main: repayment[2] = 1 if not any(repayment): repayment[0] = 1 # 5.", "for method in methods: if method in main: payment[idx + 1] = 1", "lender_type + [lender_count] + borrower_type + [borrower_count] + guarantee + [interest] + [", "main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type", "# 2. guarantee guarantee = [0, 0, 0] if '抵押' in main: guarantee[1]", "[] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos in", "in methods: if method in main: payment[idx + 1] = 1 break if", "span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx] = 1 for idx, pos", "# 1. Borrower, lender and legal representative info, main = text.split('\\n\\n') info =", "repayment[1] = 1 if '尚未还款' in main: repayment[2] = 1 if not any(repayment):", "'借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower,", "any(payment): payment[0] = 1 # 5. repayment repayment = [0] * 3 if", "= [0] * len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span", "span[1] <= pos[1]: lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos): if span[0]", "3 if '已还款' in main: repayment[1] = 1 if '尚未还款' in main: repayment[2]", "main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count] + guarantee + [interest] +", "interest_type = [0] * 4 for pattern, factor in interest_pat: for item in", "> pos[0] and span[1] <= pos[1]: lender_type[idx] = 1 for idx, pos in", "'聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and legal representative info, main =", "TODO: concat info + main ? return main.strip('\\n'), lender_type + [lender_count] + borrower_type", "interval: interest_type[3 - idx] = 1 break if interest == 0: interest_type[0] =", "represents.append(item.group(1)) span = item.span() for idx, pos in enumerate(lender_pos): if span[0] > pos[0]", "'原告').replace(name, '原告') for name in borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告')", "[ interest_value] + interest_type + payment + repayment + agreement # TODO: QuantileTransformer?", "* factor, 2)) for idx, interval in enumerate(interest_interval): if interest_value > interval: interest_type[3", "guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0] = 1 # TODO: concat", "repayment repayment = [0] * 3 if '已还款' in main: repayment[1] = 1", "0 interest_type = [0] * 4 for pattern, factor in interest_pat: for item", "utf-8 -*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'),", "enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1 for", "= [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx =", "item.span()[0])) idx = item.span()[1] lender_type = [0] * len(lenders) first = True borrowers", "interest? # 4. payment methods payment = [0] * 4 for idx, methods", "* 4 for pattern, factor in interest_pat: for item in pattern.finditer(main): interest =", "borrowers = [] borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first:", "1 # 5. repayment repayment = [0] * 3 if '已还款' in main:", "repayment[2] = 1 if not any(repayment): repayment[0] = 1 # 5. agreements agreement", "0 interest_value = 0 interest_type = [0] * 4 for pattern, factor in", "pos[1]: borrower_type[idx] = 1 for name in lenders: main = main.replace('原告' + name,", "lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info)))", "+ borrower_type + [borrower_count] + guarantee + [interest] + [ interest_value] + interest_type", "the interest? # 4. payment methods payment = [0] * 4 for idx,", "= 0 interest_type = [0] * 4 for pattern, factor in interest_pat: for", "idx = 0 lenders = [] lender_pos = [] for item in subject_pat['lender'].finditer(info):", "False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] *", "= 1 if not any(agreement): agreement[0] = 1 # TODO: concat info +", "+ main ? return main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count] +", "0: interest_type[0] = 1 # TODO: replace the interest? # 4. payment methods", "= { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent':", "any(agreement): agreement[0] = 1 # TODO: concat info + main ? return main.strip('\\n'),", "main = main.replace('原告' + name, '原告').replace(name, '原告') for name in borrowers: main =", "{ 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]')", "= [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) # 2. guarantee", "0, 0] if '抵押' in main: guarantee[1] = 1 if '担保' in main:", "break if not any(payment): payment[0] = 1 # 5. repayment repayment = [0]", "3. interest interest = 0 interest_value = 0 interest_type = [0] * 4", "1 if not any(repayment): repayment[0] = 1 # 5. agreements agreement = [0]", "guarantee[1] = 1 if '担保' in main: guarantee[2] = 1 if not any(guarantee):", "if interest == 0: interest_type[0] = 1 # TODO: replace the interest? #", "all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers)", "'微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺',", "= len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee = [0, 0, 0]", "= [0] * 3 if '已还款' in main: repayment[1] = 1 if '尚未还款'", "borrower_type[idx] = 1 for name in lenders: main = main.replace('原告' + name, '原告').replace(name,", "5. repayment repayment = [0] * 3 if '已还款' in main: repayment[1] =", "for method in methods: if method in main: agreement[idx + 1] = 1", "payment methods payment = [0] * 4 for idx, methods in enumerate(payment_list): for", "= 1 if '尚未还款' in main: repayment[2] = 1 if not any(repayment): repayment[0]", "enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx] = 1 break if interest", "2. guarantee guarantee = [0, 0, 0] if '抵押' in main: guarantee[1] =", "0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'],", "5. agreements agreement = [0] * 6 for idx, methods in enumerate(agreement_list): for", "= [0] * 6 for idx, methods in enumerate(agreement_list): for method in methods:", "len(lenders) first = True borrowers = [] borrower_pos = [] for item in", "span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1 for name in", "for name in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type =", "interest == 0: interest_type[0] = 1 # TODO: replace the interest? # 4.", "= [0] * len(lenders) first = True borrowers = [] borrower_pos = []", "coding: utf-8 -*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace':", "name in lenders: main = main.replace('原告' + name, '原告').replace(name, '原告') for name in", "max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval in enumerate(interest_interval): if interest_value >", "Borrower, lender and legal representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\", "(re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'],", "in main: payment[idx + 1] = 1 break if not any(payment): payment[0] =", "or guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0] = 1 # TODO:", "+ 1] = 1 break if not any(payment): payment[0] = 1 # 5.", "in interest_pat: for item in pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2))", "span[1] <= pos[1]: borrower_type[idx] = 1 for name in lenders: main = main.replace('原告'", "payment[idx + 1] = 1 break if not any(payment): payment[0] = 1 #", "+ name, '被告').replace(name, '被告') for name in represents: main = main.replace('法定代表人' + name,", "in enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx] = 1 break if", "1. Borrower, lender and legal representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace'].", "in pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for", "+ 1] = 1 break if guarantee[1] or guarantee[2]: agreement[4] = 1 if", "[borrower_count] + guarantee + [interest] + [ interest_value] + interest_type + payment +", "subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx", "1 break if not any(payment): payment[0] = 1 # 5. repayment repayment =", "for idx, pos in enumerate(lender_pos): if span[0] > pos[0] and span[1] <= pos[1]:", "re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12),", "interest_type[3 - idx] = 1 break if interest == 0: interest_type[0] = 1", "main: repayment[2] = 1 if not any(repayment): repayment[0] = 1 # 5. agreements", "main: guarantee[1] = 1 if '担保' in main: guarantee[2] = 1 if not", "main: agreement[idx + 1] = 1 break if guarantee[1] or guarantee[2]: agreement[4] =", "item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos in enumerate(lender_pos): if", "main ? return main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count] + guarantee", "and legal representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace'].", "pos in enumerate(lender_pos): if span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx] =", "= [0] * 4 for pattern, factor in interest_pat: for item in pattern.finditer(main):", "# -*- coding: utf-8 -*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace':", "method in methods: if method in main: payment[idx + 1] = 1 break", "'尚未还款' in main: repayment[2] = 1 if not any(repayment): repayment[0] = 1 #", "borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) # 2.", "if '已还款' in main: repayment[1] = 1 if '尚未还款' in main: repayment[2] =", "6 for idx, methods in enumerate(agreement_list): for method in methods: if method in", "repayment[0] = 1 # 5. agreements agreement = [0] * 6 for idx,", "= item.span() for idx, pos in enumerate(lender_pos): if span[0] > pos[0] and span[1]", "for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type", "['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信',", "if guarantee[1] or guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0] = 1", "interest = 1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval", "round(float(item.group(2)) * factor, 2)) for idx, interval in enumerate(interest_interval): if interest_value > interval:", "1 if '尚未还款' in main: repayment[2] = 1 if not any(repayment): repayment[0] =", "info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0", "info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:',", "main = main.replace('被告' + name, '被告').replace(name, '被告') for name in represents: main =", "'法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count", "if method in main: agreement[idx + 1] = 1 break if guarantee[1] or", "enumerate(agreement_list): for method in methods: if method in main: agreement[idx + 1] =", "not any(payment): payment[0] = 1 # 5. repayment repayment = [0] * 3", "'短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and legal representative info, main", "(re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ]", "item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents = [] for item", "lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders)", "first = True borrowers = [] borrower_pos = [] for item in subject_pat['borrower'].finditer(info):", "1 # TODO: replace the interest? # 4. payment methods payment = [0]", "main: guarantee[2] = 1 if not any(guarantee): guarantee[0] = 1 # 3. interest", "in main: repayment[1] = 1 if '尚未还款' in main: repayment[2] = 1 if", "idx, pos in enumerate(lender_pos): if span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx]", "0 lenders = [] lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if", "- idx] = 1 break if interest == 0: interest_type[0] = 1 #", "[0] * 3 if '已还款' in main: repayment[1] = 1 if '尚未还款' in", "if first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1]", "pos[0] and span[1] <= pos[1]: lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos):", "if not any(payment): payment[0] = 1 # 5. repayment repayment = [0] *", "1 if '担保' in main: guarantee[2] = 1 if not any(guarantee): guarantee[0] =", "1 break if guarantee[1] or guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0]", "1 break if interest == 0: interest_type[0] = 1 # TODO: replace the", "name, '原告').replace(name, '原告') for name in borrowers: main = main.replace('被告' + name, '被告').replace(name,", "'书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender", "['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and legal representative info,", "item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type", "[0] * 6 for idx, methods in enumerate(agreement_list): for method in methods: if", "representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace'].", "agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信',", "legal representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:',", "# TODO: concat info + main ? return main.strip('\\n'), lender_type + [lender_count] +", "in borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告') for name in represents:", "12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0]", "methods: if method in main: agreement[idx + 1] = 1 break if guarantee[1]", "[0, 0, 0] if '抵押' in main: guarantee[1] = 1 if '担保' in", "[] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1]", "all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee =", "int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) #", "= 1 # TODO: concat info + main ? return main.strip('\\n'), lender_type +", "'原告') for name in borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告') for", "re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12),", "interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10),", "(re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0] payment_list", "1 # 3. interest interest = 0 interest_value = 0 interest_type = [0]", "info + main ? return main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count]", "extract_features_and_replace(text): # 1. Borrower, lender and legal representative info, main = text.split('\\n\\n') info", "(re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账',", "methods in enumerate(agreement_list): for method in methods: if method in main: agreement[idx +", "'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"),", "repayment = [0] * 3 if '已还款' in main: repayment[1] = 1 if", "in enumerate(payment_list): for method in methods: if method in main: payment[idx + 1]", "interest_value > interval: interest_type[3 - idx] = 1 break if interest == 0:", "in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0]", "len(borrowers) # 2. guarantee guarantee = [0, 0, 0] if '抵押' in main:", "0] if '抵押' in main: guarantee[1] = 1 if '担保' in main: guarantee[2]", "12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval", "1 # 5. agreements agreement = [0] * 6 for idx, methods in", "1] = 1 break if guarantee[1] or guarantee[2]: agreement[4] = 1 if not", "= 1 break if not any(payment): payment[0] = 1 # 5. repayment repayment", "if interest_value > interval: interest_type[3 - idx] = 1 break if interest ==", "# 4. payment methods payment = [0] * 4 for idx, methods in", "replace the interest? # 4. payment methods payment = [0] * 4 for", "agreement = [0] * 6 for idx, methods in enumerate(agreement_list): for method in", "1 # TODO: concat info + main ? return main.strip('\\n'), lender_type + [lender_count]", "represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))]", "for idx, methods in enumerate(agreement_list): for method in methods: if method in main:", "re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower':", "interest_type[0] = 1 # TODO: replace the interest? # 4. payment methods payment", "agreement[0] = 1 # TODO: concat info + main ? return main.strip('\\n'), lender_type", "= text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx", "] interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'],", "[] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False", "= 1 # 5. agreements agreement = [0] * 6 for idx, methods", "agreement[4] = 1 if not any(agreement): agreement[0] = 1 # TODO: concat info", "= 1 break if interest == 0: interest_type[0] = 1 # TODO: replace", "= 1 # 5. repayment repayment = [0] * 3 if '已还款' in", "sub('原告:', info))) idx = 0 lenders = [] lender_pos = [] for item", "[int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count =", "'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') }", "[['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def", "= False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0]", "methods: if method in main: payment[idx + 1] = 1 break if not", "} interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"),", "'协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text):", "# 5. repayment repayment = [0] * 3 if '已还款' in main: repayment[1]", "for pattern, factor in interest_pat: for item in pattern.finditer(main): interest = 1 interest_value", "[['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条',", "interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for idx, interval in enumerate(interest_interval): if", "idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0] * len(lenders) first =", "span = item.span() for idx, pos in enumerate(lender_pos): if span[0] > pos[0] and", "sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders = [] lender_pos = []", "item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents =", "not any(repayment): repayment[0] = 1 # 5. agreements agreement = [0] * 6", "break if interest == 0: interest_type[0] = 1 # TODO: replace the interest?", "main: payment[idx + 1] = 1 break if not any(payment): payment[0] = 1", "len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for", "if not any(agreement): agreement[0] = 1 # TODO: concat info + main ?", "lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0] * len(lenders)", "for idx, pos in enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <= pos[1]:", "= 1 # TODO: replace the interest? # 4. payment methods payment =", "= subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders", "'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"),", "borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents = [] for item in", "lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0])) idx", "['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): #", "= [] borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx,", "10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付',", "first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx,", "= [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据',", "item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx,", "pos[1]: lender_type[idx] = 1 for idx, pos in enumerate(borrower_pos): if span[0] >= pos[0]", "= 1 if '担保' in main: guarantee[2] = 1 if not any(guarantee): guarantee[0]", "len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee = [0, 0, 0] if", "borrower_count = len(borrowers) # 2. guarantee guarantee = [0, 0, 0] if '抵押'", "for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos in enumerate(lender_pos):", "pattern, factor in interest_pat: for item in pattern.finditer(main): interest = 1 interest_value =", "= main.replace('原告' + name, '原告').replace(name, '原告') for name in borrowers: main = main.replace('被告'", "> interval: interest_type[3 - idx] = 1 break if interest == 0: interest_type[0]", "main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not", "[int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee", "interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']]", "'支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'],", "guarantee guarantee = [0, 0, 0] if '抵押' in main: guarantee[1] = 1", "borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告') for name in represents: main", "guarantee[0] = 1 # 3. interest interest = 0 interest_value = 0 interest_type", "-*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender':", "['银行转账', '手机银行'], ['现金']] agreement_list = [['合同', '协议'], ['收据', '凭据', '借条', '书面承诺', '承诺书'], ['流水'],", "\\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders = []", "in lenders: main = main.replace('原告' + name, '原告').replace(name, '原告') for name in borrowers:", "1 for idx, pos in enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <=", "interest_pat: for item in pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2)) *", "interval in enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx] = 1 break", "not any(guarantee): guarantee[0] = 1 # 3. interest interest = 0 interest_value =", "4 for idx, methods in enumerate(payment_list): for method in methods: if method in", "name in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not", "idx, interval in enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx] = 1", "= main.replace('被告' + name, '被告').replace(name, '被告') for name in represents: main = main.replace('法定代表人'", "= item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents = [] for", "concat info + main ? return main.strip('\\n'), lender_type + [lender_count] + borrower_type +", "= 1 for name in lenders: main = main.replace('原告' + name, '原告').replace(name, '原告')", "subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders =", "methods in enumerate(payment_list): for method in methods: if method in main: payment[idx +", "1) ] interest_interval = [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账',", "= [0, 0, 0] if '抵押' in main: guarantee[1] = 1 if '担保'", "idx, methods in enumerate(agreement_list): for method in methods: if method in main: agreement[idx", "enumerate(lender_pos): if span[0] > pos[0] and span[1] <= pos[1]: lender_type[idx] = 1 for", "'承诺书'], ['流水'], [], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and", "pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1 for name in lenders: main", "+ [ interest_value] + interest_type + payment + repayment + agreement # TODO:", "for name in borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告') for name", "in enumerate(agreement_list): for method in methods: if method in main: agreement[idx + 1]", "not any(agreement): agreement[0] = 1 # TODO: concat info + main ? return", "lenders: main = main.replace('原告' + name, '原告').replace(name, '原告') for name in borrowers: main", "lender_count = len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee = [0, 0,", "pos in enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx] =", "factor in interest_pat: for item in pattern.finditer(main): interest = 1 interest_value = max(interest_value,", "agreement[idx + 1] = 1 break if guarantee[1] or guarantee[2]: agreement[4] = 1", "= 1 break if guarantee[1] or guarantee[2]: agreement[4] = 1 if not any(agreement):", "return main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count] + guarantee + [interest]", "* 6 for idx, methods in enumerate(agreement_list): for method in methods: if method", "4 for pattern, factor in interest_pat: for item in pattern.finditer(main): interest = 1", "re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120),", "info))) idx = 0 lenders = [] lender_pos = [] for item in", ">= pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1 for name in lenders:", "methods payment = [0] * 4 for idx, methods in enumerate(payment_list): for method", "+ [lender_count] + borrower_type + [borrower_count] + guarantee + [interest] + [ interest_value]", "= [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type)), int(any(borrower_type))] lender_count = len(lenders) borrower_count", "= len(borrowers) # 2. guarantee guarantee = [0, 0, 0] if '抵押' in", "[] lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx, item.span()[0]))", "for idx, interval in enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx] =", "break if guarantee[1] or guarantee[2]: agreement[4] = 1 if not any(agreement): agreement[0] =", "payment[0] = 1 # 5. repayment repayment = [0] * 3 if '已还款'", "int(any(borrower_type))] lender_count = len(lenders) borrower_count = len(borrowers) # 2. guarantee guarantee = [0,", "if '抵押' in main: guarantee[1] = 1 if '担保' in main: guarantee[2] =", "[interest] + [ interest_value] + interest_type + payment + repayment + agreement #", "<reponame>Thesharing/lfesm # -*- coding: utf-8 -*- import re subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'),", "borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents", "# 5. agreements agreement = [0] * 6 for idx, methods in enumerate(agreement_list):", "+ name, '原告').replace(name, '原告') for name in borrowers: main = main.replace('被告' + name,", "'被告').replace(name, '被告') for name in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人')", "len(info))) borrower_type = [0] * len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info):", "subject_pat = { 'lender_replace': re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'),", "idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type = [0] * len(borrowers) represents = []", "[0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list =", "[ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1)", "method in methods: if method in main: agreement[idx + 1] = 1 break", "2)) for idx, interval in enumerate(interest_interval): if interest_value > interval: interest_type[3 - idx]", "factor, 2)) for idx, interval in enumerate(interest_interval): if interest_value > interval: interest_type[3 -", "name in borrowers: main = main.replace('被告' + name, '被告').replace(name, '被告') for name in", "[0] * 4 for idx, methods in enumerate(payment_list): for method in methods: if", "= item.span()[1] lender_type = [0] * len(lenders) first = True borrowers = []", "agreements agreement = [0] * 6 for idx, methods in enumerate(agreement_list): for method", "for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False else:", "? return main.strip('\\n'), lender_type + [lender_count] + borrower_type + [borrower_count] + guarantee +", "in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)),", "(re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24,", "= [] lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx: lender_pos.append((idx,", "item in pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2))", "+ [borrower_count] + guarantee + [interest] + [ interest_value] + interest_type + payment", "in main: agreement[idx + 1] = 1 break if guarantee[1] or guarantee[2]: agreement[4]", "True borrowers = [] borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if", "name, '被告').replace(name, '被告') for name in represents: main = main.replace('法定代表人' + name, '法定代表人').replace(name,", "1] = 1 break if not any(payment): payment[0] = 1 # 5. repayment", "1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 1) ] interest_interval = [0.36, 0.24, 0] payment_list =", "[0] * 4 for pattern, factor in interest_pat: for item in pattern.finditer(main): interest", "== 0: interest_type[0] = 1 # TODO: replace the interest? # 4. payment", "lender and legal representative info, main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:',", "re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [", "= [0.36, 0.24, 0] payment_list = [['微信转账', '微信支付', '支付宝'], ['银行转账', '手机银行'], ['现金']] agreement_list", "in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos in enumerate(lender_pos): if span[0]", "4. payment methods payment = [0] * 4 for idx, methods in enumerate(payment_list):", "lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0] * len(lenders) first = True", "first = False else: borrower_pos.append((idx, item.span()[0])) idx = item.span()[1] borrower_pos.append((idx, len(info))) borrower_type =", "pattern.finditer(main): interest = 1 interest_value = max(interest_value, round(float(item.group(2)) * factor, 2)) for idx,", "if '尚未还款' in main: repayment[2] = 1 if not any(repayment): repayment[0] = 1", "subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos in enumerate(lender_pos): if span[0] >", "[], ['微信', '短信', '聊天']] def extract_features_and_replace(text): # 1. Borrower, lender and legal representative", "re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1),", "'已还款' in main: repayment[1] = 1 if '尚未还款' in main: repayment[2] = 1", "in main: guarantee[1] = 1 if '担保' in main: guarantee[2] = 1 if", "= [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx, pos", "if span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1 for name", "idx, pos in enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx]", "borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first = False else: borrower_pos.append((idx, item.span()[0])) idx =", "= [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"), 1), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 10), (re.compile(r\"(年)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"),", "* 4 for idx, methods in enumerate(payment_list): for method in methods: if method", "in enumerate(borrower_pos): if span[0] >= pos[0] and span[1] <= pos[1]: borrower_type[idx] = 1", "= 1 for idx, pos in enumerate(borrower_pos): if span[0] >= pos[0] and span[1]", "lenders = [] lender_pos = [] for item in subject_pat['lender'].finditer(info): lenders.append(item.group(1)) if idx:", "if method in main: payment[idx + 1] = 1 break if not any(payment):", "= 1 # 3. interest interest = 0 interest_value = 0 interest_type =", "* len(lenders) first = True borrowers = [] borrower_pos = [] for item", "subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info))) idx = 0 lenders = [] lender_pos =", "in main: guarantee[2] = 1 if not any(guarantee): guarantee[0] = 1 # 3.", "represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span = item.span() for idx,", "borrower_pos = [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first", "interest_value = 0 interest_type = [0] * 4 for pattern, factor in interest_pat:", "if idx: lender_pos.append((idx, item.span()[0])) idx = item.span()[1] lender_type = [0] * len(lenders) first", "1 if not any(guarantee): guarantee[0] = 1 # 3. interest interest = 0", "interest = 0 interest_value = 0 interest_type = [0] * 4 for pattern,", "[0] * len(lenders) first = True borrowers = [] borrower_pos = [] for", "borrower_type = [0] * len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1))", "if '担保' in main: guarantee[2] = 1 if not any(guarantee): guarantee[0] = 1", "in methods: if method in main: agreement[idx + 1] = 1 break if", "method in main: agreement[idx + 1] = 1 break if guarantee[1] or guarantee[2]:", "main: repayment[1] = 1 if '尚未还款' in main: repayment[2] = 1 if not", "= [] for item in subject_pat['borrower'].finditer(info): borrowers.append(item.group(1)) if first: lender_pos.append((idx, item.span()[0])) first =", "'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'), 12), (re.compile(r\"(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)毛\"), 120), (re.compile(r\"(月)(\\d+(\\.\\d{1,2})?)%(利息|息|利率|利息率)\"), 12), (re.compile(r\"(年利息|年息|年利率|年利息率)按?(\\d+(\\.\\d{1,2})?)([%分])\"),", "idx] = 1 break if interest == 0: interest_type[0] = 1 # TODO:", "[0] * len(borrowers) represents = [] for item in subject_pat['legal_represent'].finditer(info): represents.append(item.group(1)) span =", "main = text.split('\\n\\n') info = subject_pat['legal_represent_replace']. \\ sub('法定代表人:', subject_pat['borrower_replace']. sub('被告:', subject_pat['lender_replace']. sub('原告:', info)))", "'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat = [ (re.compile(r'(月利息|月息|月利率|月利息率)按?(\\d+(\\.\\d{1,2})?)([%分])'),", "if not any(guarantee): guarantee[0] = 1 # 3. interest interest = 0 interest_value", "'担保' in main: guarantee[2] = 1 if not any(guarantee): guarantee[0] = 1 #", "main.replace('原告' + name, '原告').replace(name, '原告') for name in borrowers: main = main.replace('被告' +", "def extract_features_and_replace(text): # 1. Borrower, lender and legal representative info, main = text.split('\\n\\n')", "main.replace('被告' + name, '被告').replace(name, '被告') for name in represents: main = main.replace('法定代表人' +", "re.compile(r'原告(?!:)'), 'borrower_replace': re.compile(r'被告(?!:)'), 'legal_represent_replace': re.compile(r'法定代表人(?!:)'), 'lender': re.compile(r'原告:(.+?)[。|,]'), 'borrower': re.compile(r'被告:(.+?)[。|,]'), 'legal_represent': re.compile(r'法定代表人:(.+?)[。|,]') } interest_pat", "+ name, '法定代表人').replace(name, '法定代表人') lender_type = [int(not all(lender_type)), int(any(lender_type))] borrower_type = [int(not all(borrower_type))," ]
[ "enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len]", "in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col is", "x num_haplotypes) mask_dec = [] indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map", "# \"\"\" turn matrix with labels into one-hot encoding using the max number", "the max number of classes detected\"\"\" # original_mask_shape = mask.shape # mask =", "torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def", "target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id =", "[bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1,", "ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array()) representing row", "in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:]", "list of tensors (i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len x 2", "= [] # list of tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map", "column indices where mask has 1 entries target_pos_st = tindx[1][0] # give the", "# int, run number self.num_samples = len(self.partition_ids[:]) # int, number of docs in", "# ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm =", "# int, number of docs in the partition def __getitem__(self, indx): target_id =", "num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list of tensors, (N x num_haplotypes", "self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): #", "dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask =", "self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num):", "for now # to be used in dataloader object return [item for item", "from torch import nn from torch.utils.data import Dataset from tqdm import tqdm class", "= self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples,", "sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] #", "dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self,", "has 1 entries target_pos_st = tindx[1][0] # give the start of target base", "int, run number self.num_samples = len(self.partition_ids[:]) # int, number of docs in the", "return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor #", "(array(), array()) representing row and column indices where mask has 1 entries target_pos_st", "dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask,", "enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length", "one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): #", "of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self,", "mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype outcome", "[torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of sequences", "= {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2,", "used in dataloader object return [item for item in batch] def __getitem__(self, indx):", "representing row and column indices where mask has 1 entries target_pos_st = tindx[1][0]", "for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1])", "np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig", "sequence will be from 0:end of editable window indx for gr_name, gr_df in", "the partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples)", "for arr in target_prob] else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec =", "is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob", "base occurence in the sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) +", "for arr in target_conv] if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for", "partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def", "return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids,", "'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec,", "# list of tensors (i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len x", "indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): # pack batches", "indx): if self.target_prob is None: return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx],", "mask has 1 entries target_pos_st = tindx[1][0] # give the start of target", "the tensors we need # N is total number of input sequences print('Generating", "numpy as np import torch from torch import nn from torch.utils.data import Dataset", "enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return", "mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape)", "tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list of tensors", "import numpy as np import torch from torch import nn from torch.utils.data import", "= self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st =", "seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl", "int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig", "is length of haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate", "def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor`", "# dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len =", "C->T for CBE base editor # output sequence will be from 0:end of", "print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape)", "self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class", "return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is", "= indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): # pack", "sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig = self.seqconfig", "= np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask", "i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col", "= np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig =", "= torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot", "type (i.e. train, validation, test) self.run_num = run_num # int, run number self.num_samples", "= [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase]", "print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm", "# create the tensors we need # N is total number of input", "print('seqid:', seqid) def hap_collate(batch): # pack batches in a list for now #", "# enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return", "print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n',", "self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr", "mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:',", "x num_haplotypes x outp_sequence_len) target_conv = [] # list of tensors, (N x", "mask_enc = None mask_encdec = None # tensorize print('--- tensorizing ---') device_cpu =", "editor) # C->T for CBE base editor # output sequence will be from", "mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob,", "# N is total number of input sequences bsize, seq_len = enc_inp.shape #", "(N x num_haplotypes x outp_sequence_len x 2 x 1) target_prob = [] #", "seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st", "of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list of", "in target_prob] else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec", "{} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....]", "outcome_prop_col): # create the tensors we need # N is total number of", "in batch] def __getitem__(self, indx): if self.target_prob is None: return_target_prob = None else:", "[] indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]),", "= int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot", "editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in", "# one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) #", "return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we need", "of tensors, (N x num_haplotypes x outp_sequence_len) target_conv = [] # list of", "num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list of tensors (i.e. one-hot encoding),", "1) # if n_dims is None: # n_dims = int(torch.max(mask)) + 1 #", "# dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig", "sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask", "print('--- end ---') def hap_collate(self, batch): # pack batches in a list for", "PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor # instance of", "of sequence indices self.dsettype = dsettype # string, dataset type (i.e. train, validation,", "dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig =", "seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # # enc_mask =", "inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec", "mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape)", "# tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc =", "Xinp_enc = [] # tensor, (N x inp_sequence_len) Xinp_dec = [] # list", "self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0", "create the tensors we need # N is total number of input sequences", "tindx) # tindx (array(), array()) representing row and column indices where mask has", "arr in target_prob] else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec = mask_encdec", "to be used in dataloader object return [item for item in batch] def", "self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col is not None:", "target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc,", "is total number of input sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc", "self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec]", "if i < offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:]", "target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator", "# outcome_seq_len is length of haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len]", "target_prob = [] # list of tensors, (N x num_haplotypes) mask_dec = []", "dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def", "np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp =", "= dsettype # string, dataset type (i.e. train, validation, test) self.run_num = run_num", "of target base occurence in the sequence ew_seqlen = ewindow_end - (target_pos_st +", "(N x num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list of tensors (i.e.", "n_dims is None: # n_dims = int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0],", "Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape)", "x inp_sequence_len) Xinp_dec = [] # list of tensors, (N x num_haplotypes x", "sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen)", "N is total number of input sequences print('Generating tensors using sequence config:\\n', self.seqconfig)", "print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id]", "print('tindx:\\n', tindx) # tindx (array(), array()) representing row and column indices where mask", "mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None", "and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] =", "tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}'", "CBE base editor # output sequence will be from 0:end of editable window", "# print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc", "not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): #", "import nn from torch.utils.data import Dataset from tqdm import tqdm class SeqMaskGenerator(object): def", "#enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask", "__init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn", "# target base, conversion base (i.e. A->G for ABE base editor) # C->T", "encoding using the max number of classes detected\"\"\" # original_mask_shape = mask.shape #", "of docs in the partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id]", "one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the", "# mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig = self.seqconfig num_haplotypes", "int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot =", "tindx[1][0] # give the start of target base occurence in the sequence ew_seqlen", "self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N is", "[] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv = []", "self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self,", "indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}'", "mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist()", "create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N is total number of input", "end ---') def hap_collate(self, batch): # pack batches in a list for now", "if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is", "(N x inp_sequence_len) Xinp_dec = [] # list of tensors, (N x num_haplotypes", "and column indices where mask has 1 entries target_pos_st = tindx[1][0] # give", "tensors, (N x num_haplotypes x outp_sequence_len) target_conv = [] # list of tensors,", "\"\"\" turn matrix with labels into one-hot encoding using the max number of", "mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:',", "np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def", "mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec,", "= self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl #", "i in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i,", "Xinp_dec = [] # list of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase", "inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape =", "Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape)", "__getitem__(self, indx): if self.target_prob is None: return_target_prob = None else: return_target_prob = self.target_prob[indx]", "list of tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map = {} #", "= target_pos_st + ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if i <", "def __getitem__(self, indx): if self.target_prob is None: return_target_prob = None else: return_target_prob =", "from torch.utils.data import Dataset from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig):", "enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask", "docs in the partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def", "entries target_pos_st = tindx[1][0] # give the start of target base occurence in", "for item in batch] def __getitem__(self, indx): if self.target_prob is None: return_target_prob =", "1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes,", "cb_nucl = tb_cb_nucl # target base, conversion base (i.e. A->G for ABE base", "need # N is total number of input sequences print('Generating tensors using sequence", "if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec", "= [] # tensor, (N x inp_sequence_len) Xinp_dec = [] # list of", "x num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list of tensors (i.e. one-hot", "range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]", "tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1])", "self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def", "test) self.run_num = run_num # int, run number self.num_samples = len(self.partition_ids[:]) # int,", "return [item for item in batch] def __getitem__(self, indx): if self.target_prob is None:", "number self.num_samples = len(self.partition_ids[:]) # int, number of docs in the partition def", "seqid) def hap_collate(batch): # pack batches in a list for now # to", "the sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:',", "dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids =", "0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st #", "mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array()) representing", "partition_ids, dsettype, run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids", "indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype,", "torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec]", "'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:',", "of input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len,", "outcome_seq_len] # generate causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end", "axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen", "= enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] #", "import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp):", "= 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1]", "inp_sequence_len) Xinp_dec = [] # list of tensors, (N x num_haplotypes x outp_sequence_len)", "#dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask,", "dsettype, run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids #", "in the partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self):", "None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec,", "# 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx =", "in dataloader object return [item for item in batch] def __getitem__(self, indx): if", "Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc,", "'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot,", "give the start of target base occurence in the sequence ew_seqlen = ewindow_end", "1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len,", "inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1,", "def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1,", "ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen,", "__init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] #", "be used in dataloader object return [item for item in batch] def __getitem__(self,", "= np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def", "gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None # tensorize print('--- tensorizing ---') device_cpu", "return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid", "for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for", "k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset =", "= self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx])", "axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig # def", "mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples =", "list for now # to be used in dataloader object return [item for", "return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask", "tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(),", "x outp_sequence_len) target_conv = [] # list of tensors, (N x num_haplotypes x", "- (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen))", "mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base,", "ABE base editor) # C->T for CBE base editor # output sequence will", "self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase", "def hap_collate(self, batch): # pack batches in a list for now # to", "is total number of input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape =", "range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not", "self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot,", "i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1])", "# string, dataset type (i.e. train, validation, test) self.run_num = run_num # int,", "outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen,", "using sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N x inp_sequence_len) Xinp_dec", "dataset type (i.e. train, validation, test) self.run_num = run_num # int, run number", "one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) # return", "import Dataset from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig =", "x outp_sequence_len x 2 x 1) target_prob = [] # list of tensors,", "num_haplotypes x outp_sequence_len) target_conv = [] # list of tensors, (N x num_haplotypes", "= [] indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} #", "total number of input sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc =", "# return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we", "= np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len", "indices self.dsettype = dsettype # string, dataset type (i.e. train, validation, test) self.run_num", "# # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1,", "# original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is", "seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion base (i.e.", "arr in target_conv] if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr", "mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int,", "matrix with labels into one-hot encoding using the max number of classes detected\"\"\"", "dataloader object return [item for item in batch] def __getitem__(self, indx): if self.target_prob", "self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor", "# to be used in dataloader object return [item for item in batch]", "return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx],", "ewindow_end - (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen,", "range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc", "# enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len,", "inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1)", "indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1,", "return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc,", "if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape)", "= self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec,", "# enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask", "is None: # n_dims = int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1,", "= len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec =", "return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self,", "None # tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc", "#enc_inp = [N, inp_seq_len] # N is total number of input sequences bsize,", "= np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask =", "inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] #", "self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr", "# list of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] #", "= np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset) for", "len(self.partition_ids[:]) # int, number of docs in the partition def __getitem__(self, indx): target_id", "self.target_prob = None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for", "arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map =", "tensors we need # N is total number of input sequences print('Generating tensors", "self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of", "sequence indices self.dsettype = dsettype # string, dataset type (i.e. train, validation, test)", "validation, test) self.run_num = run_num # int, run number self.num_samples = len(self.partition_ids[:]) #", "def __getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm):", "conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None:", "HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): #", "target base, conversion base (i.e. A->G for ABE base editor) # C->T for", "num_haplotypes) mask_dec = [] indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map =", "axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase):", "# compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] =", "torch.utils.data import Dataset from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig", "outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len]", "of input sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc = [] #", "def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len]", "tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array()) representing row and", "self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in", "import torch from torch import nn from torch.utils.data import Dataset from tqdm import", "base (i.e. A->G for ABE base editor) # C->T for CBE base editor", "# enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1)", "seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end)", "# print('tindx:\\n', tindx) # tindx (array(), array()) representing row and column indices where", "-1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors", "enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen =", "ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st,", "else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu)", "dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape", "sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st +", "x 2 x 1) target_prob = [] # list of tensors, (N x", "create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype", "int, number of docs in the partition def __getitem__(self, indx): target_id = self.partition_ids[indx]", "self.seqconfig) Xinp_enc = [] # tensor, (N x inp_sequence_len) Xinp_dec = [] #", "= [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask =", "= dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset):", "0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx", "else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack batches in a", "a list for now # to be used in dataloader object return [item", "for i in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] = 0 else:", "in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in", "hap_collate(self, batch): # pack batches in a list for now # to be", "number of docs in the partition def __getitem__(self, indx): target_id = self.partition_ids[indx] return", "into one-hot encoding using the max number of classes detected\"\"\" # original_mask_shape =", "tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion base (i.e. A->G for ABE", "ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:,", "seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N is total number", "x outp_sequence_len) target_conv_onehot = [] # list of tensors (i.e. one-hot encoding), (N", "self.target_prob is None: return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc,", "in target_conv] if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in", "ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx)", "'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec", "[item for item in batch] def __getitem__(self, indx): if self.target_prob is None: return_target_prob", "seqconfig.ewindow_end # ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm", "# enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len,", "inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len),", "sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape',", "def __init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\"", "target_conv] if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob]", "dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset)", "proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we need # N is total", "num_haplotypes x outp_sequence_len x 2 x 1) target_prob = [] # list of", "= seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N is total", "tindx (array(), array()) representing row and column indices where mask has 1 entries", "self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0)", "#enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len,", "[] # list of tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map =", "= mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples", "of tensors (i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len x 2 x", "outp_sequence_len) target_conv_onehot = [] # list of tensors (i.e. one-hot encoding), (N x", "torch from torch import nn from torch.utils.data import Dataset from tqdm import tqdm", "= run_num # int, run number self.num_samples = len(self.partition_ids[:]) # int, number of", "tensor, (N x inp_sequence_len) Xinp_dec = [] # list of tensors, (N x", "input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len]", "None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id", "def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N is total number of", "in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1])", "# print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map)", "in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2)", "1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len", "seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N, inp_seq_len] # N", "arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col", "is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None:", "target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc", "num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self,", "None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob = None self.mask_enc", "# int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end", "6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool))", "if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid)", "# C->T for CBE base editor # output sequence will be from 0:end", "[torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec", "def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with labels into one-hot encoding", "turn matrix with labels into one-hot encoding using the max number of classes", "of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list of", "instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence indices self.dsettype =", "conversion base (i.e. A->G for ABE base editor) # C->T for CBE base", "one-hot encoding using the max number of classes detected\"\"\" # original_mask_shape = mask.shape", "window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:])", "2 x 1) target_prob = [] # list of tensors, (N x num_haplotypes)", "[] # list of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = []", "= np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples,", "offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape =", "be from 0:end of editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])):", "1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape =", "__init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids", "Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n',", "indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is", "self.run_num = run_num # int, run number self.num_samples = len(self.partition_ids[:]) # int, number", "in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute", "num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 #", "+ ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if i < offset: dec_causal_mask[i,", "of classes detected\"\"\" # original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) #", "haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig", "print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1,", "np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1,", "__len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor", "return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self):", "self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask =", "start of target base occurence in the sequence ew_seqlen = ewindow_end - (target_pos_st", "# N is total number of input sequences print('Generating tensors using sequence config:\\n',", "generate causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st,", "= [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in", "outp_sequence_len x 2 x 1) target_prob = [] # list of tensors, (N", "1) target_prob = [] # list of tensors, (N x num_haplotypes) mask_dec =", "= [1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len)) #", "Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for", "(N x num_haplotypes) mask_dec = [] indx_seqid_map = {} # dict, int_id:(seqid, target_seq)", "= partition_ids # list of sequence indices self.dsettype = dsettype # string, dataset", "seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize,", "# give the start of target base occurence in the sequence ew_seqlen =", "will be from 0:end of editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id',", "not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is", "= [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes,", "= one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create", "gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in", "[torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot", "bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask", "partition_ids # list of sequence indices self.dsettype = dsettype # string, dataset type", "mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not", "self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with", "'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) #", "self.partition_ids = partition_ids # list of sequence indices self.dsettype = dsettype # string,", "= seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13 # print('ewindow_st:', ewindow_st, 'ewindow_end:',", "max number of classes detected\"\"\" # original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1,", "outp_sequence_len) target_conv = [] # list of tensors, (N x num_haplotypes x outp_sequence_len)", "target_pos_st = tindx[1][0] # give the start of target base occurence in the", "mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id]", "= np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] #", "1, seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # # enc_mask", "list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot = [] # list", "in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map = indx_seqid_map", "= [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col is not None: self.target_prob", "as np import torch from torch import nn from torch.utils.data import Dataset from", "self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): # pack batches in", "object return [item for item in batch] def __getitem__(self, indx): if self.target_prob is", "class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp =", "occurence in the sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) + 1", "0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1,", "item in batch] def __getitem__(self, indx): if self.target_prob is None: return_target_prob = None", "= len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map", "n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self,", "self.dsettype = dsettype # string, dataset type (i.e. train, validation, test) self.run_num =", "target base occurence in the sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st)", "range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv =", "enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask =", "is None: return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx],", "def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob,", "sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0],", "= gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values)", "input sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor,", "self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec,", "else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx,", "editor # output sequence will be from 0:end of editable window indx for", "+ 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0)", "indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None #", "array()) representing row and column indices where mask has 1 entries target_pos_st =", "self.num_samples = len(self.partition_ids[:]) # int, number of docs in the partition def __getitem__(self,", "[N, inp_seq_len] # N is total number of input sequences bsize, seq_len =", "inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen),", "print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if", "None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob,", "= [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob = None self.mask_enc = mask_enc", "None mask_encdec = None # tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc", "= len(self.partition_ids[:]) # int, number of docs in the partition def __getitem__(self, indx):", "tensors (i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len x 2 x 1)", "# print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset) for i in", "# n_dims = int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1)", "# print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]]", "1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1)", "torch import nn from torch.utils.data import Dataset from tqdm import tqdm class SeqMaskGenerator(object):", "= np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): # dec_inp", "outcome_seq_len] # outcome_seq_len is length of haplotype outcome sequence # mask_targetbase = [num_haplotyptes,", "self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset):", "# one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col):", "dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig", "def create_dec_mask(self, mask_targetbase): # dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of", "1, seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask =", "output sequence will be from 0:end of editable window indx for gr_name, gr_df", "outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask,", "print('offset:',offset) for i in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] = 0", "0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask", "# def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with labels into one-hot", "seq_len = enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask =", "indx) print('seqid:', seqid) def hap_collate(batch): # pack batches in a list for now", "enc_mask = np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask", "= [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype outcome sequence # mask_targetbase", "# list of tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map = {}", "mask_dec = [] indx_seqid_map = {} # dict, int_id:(seqid, target_seq) inpseq_outpseq_map = {}", "tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list of tensors,", "ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13 # print('ewindow_st:',", "= None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx],", "seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not", "else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1]", "= [] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv =", "self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples)", "self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob = None self.mask_enc =", "= 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st", "bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples):", "= mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: # n_dims = int(torch.max(mask)) +", "print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx)", "= mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc) #", "run_num): self.dtensor = dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list", "enc_inp): #enc_inp = [N, inp_seq_len] # N is total number of input sequences", "list of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list", "_encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with labels into one-hot encoding using", "target_conv_onehot, target_prob, indx, seqid = elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if", "print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack batches", "total number of input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1,", "sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N x inp_sequence_len) Xinp_dec =", "SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion base", "outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob", "number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def", "np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset) for i", "n_dims=None): # \"\"\" turn matrix with labels into one-hot encoding using the max", "mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: # n_dims", "row and column indices where mask has 1 entries target_pos_st = tindx[1][0] #", "# pack batches in a list for now # to be used in", "= elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None:", "self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target", "mask, n_dims=None): # \"\"\" turn matrix with labels into one-hot encoding using the", "if self.target_prob is None: return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx],", "dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask", "= enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1,", "N is total number of input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape", "= dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence", "tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp", "num_classes=2) for arr in target_conv] if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu)", "original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None:", "is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1])", "np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1))", "nn from torch.utils.data import Dataset from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self,", "one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we need #", "base, conversion base (i.e. A->G for ABE base editor) # C->T for CBE", "tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0],", "using the max number of classes detected\"\"\" # original_mask_shape = mask.shape # mask", "# mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: # n_dims =", "0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return", "self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor,", "not None: print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n',", "= [] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot =", "x 1) target_prob = [] # list of tensors, (N x num_haplotypes) mask_dec", "outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec #", "num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen))", "not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1]))", "causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end", "labels into one-hot encoding using the max number of classes detected\"\"\" # original_mask_shape", "of editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i", "None: return_target_prob = None else: return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec,", "np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # #", "len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None", "range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] =", "outp_sequence_len) mask_inp_targetbase = [] # list of tensors, (N x num_haplotypes x outp_sequence_len)", "inpseq_outpseq_map = {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator =", "for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for", "= [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of", "base editor) # C->T for CBE base editor # output sequence will be", "mask_inp_targetbase = [] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv", "(i.e. train, validation, test) self.run_num = run_num # int, run number self.num_samples =", "create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen,", "inp_seq_len] # N is total number of input sequences bsize, seq_len = enc_inp.shape", "mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end #", "target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def", "1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0],", "= tindx[1][0] # give the start of target base occurence in the sequence", "dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig):", "= ewindow_end - (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask =", "i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) #", "None: # n_dims = int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask,", "mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: # n_dims = int(torch.max(mask)) + 1", "we need # N is total number of input sequences print('Generating tensors using", "for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot =", "detected\"\"\" # original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims", "0:end of editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for", "ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) #", "= torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu)", "= inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): # pack batches in a", "dsettype # string, dataset type (i.e. train, validation, test) self.run_num = run_num #", "= [1, 1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len)", "target_conv = [] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot", "# generate causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st, ewindow_end =", "# list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv = [] #", "dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len", "# output sequence will be from 0:end of editable window indx for gr_name,", "inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape = [bsize,", "tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self,", "[] # list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot = []", "x outp_sequence_len) mask_inp_targetbase = [] # list of tensors, (N x num_haplotypes x", "None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in", "#enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len))", "indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec,", "base editor # output sequence will be from 0:end of editable window indx", "in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is", "target_prob] else: self.target_prob = None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec =", "np.repeat(enc_mask, bsize, axis=0) enc_mask = np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self,", "enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask = np.repeat(enc_dec_mask, num_samples, axis=0) enc_dec_mask =", "for CBE base editor # output sequence will be from 0:end of editable", "# print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1])", "---') def hap_collate(self, batch): # pack batches in a list for now #", "hap_collate(batch): # pack batches in a list for now # to be used", "np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset", "for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if", "= self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) # enc_dec_mask", "< offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n',", "# if n_dims is None: # n_dims = int(torch.max(mask)) + 1 # one_hot", "1 entries target_pos_st = tindx[1][0] # give the start of target base occurence", "'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack batches in", "print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset) for i in range(ewindow_end+1):", "arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu),", "# print('offset:',offset) for i in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:] =", "# list of sequence indices self.dsettype = dsettype # string, dataset type (i.e.", "int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---')", "tb_cb_nucl # target base, conversion base (i.e. A->G for ABE base editor) #", "....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl =", "i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i", "offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask =", "mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13 #", "ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0", "= torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in", "# #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len,", "is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch):", "sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape) offset = target_pos_st", "self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc)", "of tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map = {} # dict,", "for ABE base editor) # C->T for CBE base editor # output sequence", "for arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map", "mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n',", "{} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len", "dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype outcome sequence #", "mask, 1) # one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df,", "seq_len, seq_len) # #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask,", "[torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col is not None: self.target_prob =", "(i.e. A->G for ABE base editor) # C->T for CBE base editor #", "target_conv_onehot = [] # list of tensors (i.e. one-hot encoding), (N x num_haplotypes", "print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind = np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] =", "= np.triu_indices(ew_seqlen, k=0) sub_mask[sub_mask_ind[0], sub_mask_ind[1]] = 0 dec_causal_mask = np.ones((ewindow_end+1,ewindow_end+1)) # print('dec_causal_mask.shape', dec_causal_mask.shape)", "seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen =", "tensors, (N x num_haplotypes) mask_dec = [] indx_seqid_map = {} # dict, int_id:(seqid,", "1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for", "__getitem__(self, indx): target_id = self.partition_ids[indx] return self.dtensor[target_id] def __len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc,", "length of haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal", "= [] # list of tensors (i.e. one-hot encoding), (N x num_haplotypes x", "print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else:", "self.num_samples = len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map =", "seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix", "(N x num_haplotypes x outp_sequence_len) target_conv = [] # list of tensors, (N", "of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence indices self.dsettype = dsettype", "= gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None # tensorize print('--- tensorizing ---')", "A->G for ABE base editor) # C->T for CBE base editor # output", "None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack", "outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig =", "if n_dims is None: # n_dims = int(torch.max(mask)) + 1 # one_hot =", "= [] # list of tensors, (N x num_haplotypes x outp_sequence_len) mask_inp_targetbase =", "mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: # n_dims = int(torch.max(mask))", "gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) #", "where mask has 1 entries target_pos_st = tindx[1][0] # give the start of", "1) # one_hot = one_hot.view(*original_mask_shape, -1) # return one_hot def generate_tensor_from_df(self, proc_df, tb_cb_nucl,", "for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if", "dtensor # instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence indices", "def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx, seqid =", "1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 #", "mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape) else: print('target_prob:None')", "device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec =", "mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig = self.seqconfig num_haplotypes =", "target_pos_st + ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if i < offset:", "def __len__(self): return(self.num_samples) class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor =", "ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if i < offset: dec_causal_mask[i, offset:]", "out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl", "if outcome_prop_col is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else:", "print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc =", "[] # tensor, (N x inp_sequence_len) Xinp_dec = [] # list of tensors,", "inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1 # enc_dec_mask = np.ones((1,1, outp_seqlen, inp_seqlen)) #", "'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for", "train, validation, test) self.run_num = run_num # int, run number self.num_samples = len(self.partition_ids[:])", "dec_causal_mask.shape) offset = target_pos_st + ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if", "inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch): # pack batches in a list", "indices where mask has 1 entries target_pos_st = tindx[1][0] # give the start", "= sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1,", "ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx", "return_target_prob = self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx],", "1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) # #enc_mask.shape", "run number self.num_samples = len(self.partition_ids[:]) # int, number of docs in the partition", "enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len]", "# dec_inp = [num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype outcome sequence", "= self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase =", "# #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1,", "gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None # tensorize print('---", "= [num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0]", "x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list of tensors, (N x", "= seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion base (i.e. A->G", "inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape = [1, 1,", "len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('---", "= seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with labels", "---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec", "is not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob =", "self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in mask_dec] self.num_samples = len(self.Xinp_enc) # int, number", "mask_dec] self.num_samples = len(self.Xinp_enc) # int, number of sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map", "# instance of :class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence indices self.dsettype", "offset = target_pos_st + ewindow_st # print('offset:',offset) for i in range(ewindow_end+1): if i", "tensors using sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N x inp_sequence_len)", "class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig # def _encode_to_one_hot(self, mask, n_dims=None):", "= np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array()) representing row and column", "in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv", "pack batches in a list for now # to be used in dataloader", "offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask)", "generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we need # N is", "inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None # tensorize print('--- tensorizing", "of haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] # generate causal mask", "[] # list of tensors (i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len", "now # to be used in dataloader object return [item for item in", "with labels into one-hot encoding using the max number of classes detected\"\"\" #", "SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def create_enc_mask(self, enc_inp): #enc_inp = [N,", "= 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] # print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1,", "sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N", "Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i", "print('mask_enc:\\n', mask_enc, 'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape)", "for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in", "np import torch from torch import nn from torch.utils.data import Dataset from tqdm", "= mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if n_dims is None: #", "mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if", "def generate_tensor_from_df(self, proc_df, tb_cb_nucl, outcome_prop_col): # create the tensors we need # N", "# list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv_onehot = [] #", "classes detected\"\"\" # original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1) # if", "(i.e. one-hot encoding), (N x num_haplotypes x outp_sequence_len x 2 x 1) target_prob", "dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0) return dec_causal_mask class", "batches in a list for now # to be used in dataloader object", "enc_dec_mask = np.full((num_samples, 1, outp_seqlen, inp_seqlen), 1) return enc_dec_mask def create_dec_mask(self, mask_targetbase): #", "torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu) self.Xinp_enc = self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for", "print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None:", "sequences self.indx_seqid_map = indx_seqid_map self.inpseq_outpseq_map = inpseq_outpseq_map print('--- end ---') def hap_collate(self, batch):", "'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not None: print('target_prob:\\n',target_prob, 'shape:',target_prob.shape)", "seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion base (i.e. A->G for", "= tb_cb_nucl # target base, conversion base (i.e. A->G for ABE base editor)", "encoding), (N x num_haplotypes x outp_sequence_len x 2 x 1) target_prob = []", "[1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1, seq_len, seq_len)) # #enc_mask.shape", "Xinp_dec.append(gr_df[[f'Outp_B{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}'", "self.target_prob[indx] return(self.Xinp_enc[indx], self.Xinp_dec[indx], self.mask_enc, self.mask_dec[indx], self.mask_encdec, self.mask_inp_targetbase[indx], self.target_conv_onehot[indx], return_target_prob, indx, self.indx_seqid_map[indx], self.inpseq_outpseq_map[indx]) def", "self.Xinp_enc.reshape(self.Xinp_enc.shape[0], 1, self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu)", "elm print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n',", "(target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind", "= SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl, cb_nucl = tb_cb_nucl # target base, conversion", "[1, 1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1, 1, seq_len, seq_len) #", "n_dims = int(torch.max(mask)) + 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) #", "tb_cb_nucl, outcome_prop_col): # create the tensors we need # N is total number", "list of sequence indices self.dsettype = dsettype # string, dataset type (i.e. train,", "print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack batches in a list for", "run_num # int, run number self.num_samples = len(self.partition_ids[:]) # int, number of docs", "[num_haplotypes, outcome_seq_len] # outcome_seq_len is length of haplotype outcome sequence # mask_targetbase =", "gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}' for i in range(1,seq_len+1)]].values[0,:]) Xinp_dec.append(gr_df[[f'Outp_B{i}' for i", "seq_len)) # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # # enc_mask = enc_mask.reshape(1,", "print('dec_causal_mask:\\n', dec_causal_mask) #dec_causal_mask.shape = [1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask", "Dataset from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig", "= mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array())", "print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N x", "target_conv.append(conv) if outcome_prop_col is not None: target_prob.append(gr_df[outcome_prop_col].values) # print(target_prob[-1]) # compute mask_enc and", "number of input sequences print('Generating tensors using sequence config:\\n', self.seqconfig) Xinp_enc = []", "from 0:end of editable window indx for gr_name, gr_df in tqdm(proc_df.groupby(by=['seq_id', 'Inp_seq'])): Xinp_enc.append(gr_df[[f'Inp_B{i}'", "config:\\n', self.seqconfig) Xinp_enc = [] # tensor, (N x inp_sequence_len) Xinp_dec = []", "batch): # pack batches in a list for now # to be used", "seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen = self.seqconfig.ewindow_end+1", "= None mask_encdec = None # tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu')", ":class:`HaplotypeDataTensor` self.partition_ids = partition_ids # list of sequence indices self.dsettype = dsettype #", "print('target_prob:None') print('indx:', indx) print('seqid:', seqid) def hap_collate(batch): # pack batches in a list", "enc_inp.shape # #enc_mask.shape = [1, 1, inp_seq_len, inp_seq_len] # enc_mask = np.ones((1, 1,", "= None # tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc = torch.tensor(Xinp_enc).long().to(device_cpu)", "[torch.from_numpy(arr).long().to(device_cpu) for arr in mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv]", "number of input sequences bsize, seq_len = enc_inp.shape # #enc_mask.shape = [1, 1,", "batch] def __getitem__(self, indx): if self.target_prob is None: return_target_prob = None else: return_target_prob", "= gr_name inpseq_outpseq_map[inpseq_id] = gr_df['Outp_seq'].values.tolist() mask_enc = None mask_encdec = None # tensorize", "mask_encdec = None # tensorize print('--- tensorizing ---') device_cpu = torch.device('cpu') self.Xinp_enc =", "x num_haplotypes x outp_sequence_len x 2 x 1) target_prob = [] # list", "the start of target base occurence in the sequence ew_seqlen = ewindow_end -", "mask_inp_targetbase] self.target_conv_onehot = [torch.nn.functional.one_hot(torch.from_numpy(arr).long().to(device_cpu), num_classes=2) for arr in target_conv] if outcome_prop_col is not", "[1, 0:ewindow_end+1, 0:ewindow_end+1] dec_causal_mask = dec_causal_mask.reshape(1, dec_causal_mask.shape[0], dec_causal_mask.shape[1]) dec_causal_mask = np.repeat(dec_causal_mask, num_haplotypes, axis=0)", "(N x num_haplotypes x outp_sequence_len) mask_inp_targetbase = [] # list of tensors, (N", "'shape:',mask_enc.shape) print('mask_dec:\\n',mask_dec, 'shape:',mask_dec.shape) if mask_encdec is not None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:',", "+ 1 # one_hot = torch.zeros(mask.shape[0], n_dims).scatter_(1, mask, 1) # one_hot = one_hot.view(*original_mask_shape,", "ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask", "# print('ewindow_st:', ewindow_st, 'ewindow_end:', ewindow_end) tm = mask_targetbase[:, ewindow_st:ewindow_end+1] tindx = np.where(tm.astype(np.bool)) #", "in the sequence ew_seqlen = ewindow_end - (target_pos_st + ewindow_st) + 1 #", "not None: self.target_prob = [torch.from_numpy(arr).float().to(device_cpu) for arr in target_prob] else: self.target_prob = None", "self.Xinp_enc.shape[1]) self.Xinp_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr in Xinp_dec] self.mask_inp_targetbase = [torch.from_numpy(arr).long().to(device_cpu) for arr", "= {} # dict([]), int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig)", "= mask_targetbase.shape[0] ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end # ewindow_st = 0 # 6-13", "# tindx (array(), array()) representing row and column indices where mask has 1", "# tensor, (N x inp_sequence_len) Xinp_dec = [] # list of tensors, (N", "+ ewindow_st) + 1 # print('ew_seqlen:', ew_seqlen) sub_mask = np.ones((ew_seqlen, ew_seqlen)) sub_mask_ind =", "number of classes detected\"\"\" # original_mask_shape = mask.shape # mask = mask.type(torch.LongTensor).view(-1, 1)", "__len__(self): return(self.num_samples) def print_data_example(elm): Xinp_enc, Xinp_dec, mask_enc, mask_dec, mask_encdec, mask_targetbase_enc, target_conv_onehot, target_prob, indx,", "None: print('mask_encdec:\\n', mask_encdec, 'shape:',mask_encdec.shape) print('mask_targetbase_enc:\\n', mask_targetbase_enc,'shape:', mask_targetbase_enc.shape) print('target_conv_onehot:\\n',target_conv_onehot, 'shape:',target_conv_onehot.shape) if target_prob is not", "mask_inp_targetbase.append(gr_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1]) conv = gr_df[[f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]].values[:,0:seqconfig.ewindow_end+1] target_conv.append(conv)", "in a list for now # to be used in dataloader object return", "= None self.mask_enc = mask_enc self.mask_encdec = mask_encdec self.mask_dec = [torch.from_numpy(arr).long().to(device_cpu) for arr", "[num_haplotyptes, outcome_seq_len] # generate causal mask seqconfig = self.seqconfig num_haplotypes = mask_targetbase.shape[0] ewindow_st,", "def hap_collate(batch): # pack batches in a list for now # to be", "from tqdm import tqdm class SeqMaskGenerator(object): def __init__(self, seqconfig): self.seqconfig = seqconfig def", "= [N, inp_seq_len] # N is total number of input sequences bsize, seq_len", "num_haplotypes, axis=0) return dec_causal_mask class HaplotypeDataTensor(Dataset): def __init__(self, seqconfig): self.seqconfig = seqconfig #", "string, dataset type (i.e. train, validation, test) self.run_num = run_num # int, run", "class PartitionDataTensor(Dataset): def __init__(self, dtensor, partition_ids, dsettype, run_num): self.dtensor = dtensor # instance", "int_id:[outp_seq1, out_seq2, ....] seqconfig = self.seqconfig mask_generator = SeqMaskGenerator(seqconfig) seq_len = seqconfig.seq_len tb_nucl,", "list of tensors, (N x num_haplotypes x outp_sequence_len) target_conv = [] # list", "# #enc_mask.shape = [bsize, 1, inp_seq_len, inp_seq_len] # enc_mask = np.repeat(enc_mask, bsize, axis=0)", "np.full((bsize,1, seq_len, seq_len), 1) return enc_mask def create_enc_dec_mask(self, num_samples): inp_seqlen = self.seqconfig.seq_len outp_seqlen", "np.where(tm.astype(np.bool)) # print('tindx:\\n', tindx) # tindx (array(), array()) representing row and column indices", "one-hot encoding), (N x num_haplotypes x outp_sequence_len x 2 x 1) target_prob =", "compute mask_enc and mask_dec # print(mask_targetbase[-1]) mask_dec.append(mask_generator.create_dec_mask(mask_inp_targetbase[-1])) inpseq_id = len(indx_seqid_map) indx_seqid_map[inpseq_id] = gr_name", "print('Xinp_enc:\\n', Xinp_enc, 'shape:', Xinp_enc.shape) print('Xinp_dec:\\n',Xinp_dec, 'shape:',Xinp_dec.shape) if mask_enc is not None: print('mask_enc:\\n', mask_enc,", "seqconfig # def _encode_to_one_hot(self, mask, n_dims=None): # \"\"\" turn matrix with labels into", "i < offset: dec_causal_mask[i, offset:] = 0 else: dec_causal_mask[i, offset:] = sub_mask[i-offset,:] #", "outcome_seq_len is length of haplotype outcome sequence # mask_targetbase = [num_haplotyptes, outcome_seq_len] #" ]
[ "nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() out_heat =", "or H != getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step =", "h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name)", "= self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 =", "def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg),", "feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs,", "return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor,", "stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1", "reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image,", "wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0],", "topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() # (batch, topk).", "down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]]", "fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2,", "UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for", "0) & (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h", "1], \\ bboxes[:, 2], bboxes[:, 3] areas = (y_max - y_min + 1)", "F from mmcv.cnn import normal_init, kaiming_init, constant_init import math import numpy as np", "for i, kernel_size in enumerate(kernel_sizes): inc = in_channels if i == 0 else", "0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) # collide_b1", "larger boxes have lower priority than small boxes. for k in range(boxes_ind.shape[0]): cls_id", "- x, w_radius + 1) top, bottom = min(y, h_radius), min(height - y,", "min(y, h_radius), min(height - y, h_radius + 1) masked_heatmap = heatmap[y - top:y", "padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers,", "kernel), stride=1, padding=pad) keep = (hmax == heat).float() out_heat = heat if out_heat", "1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1,", "cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1,", "1) if idx == 0: wh_filter = area >= self.b1_min_length ** 2 /", "self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes):", "nn import torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init, constant_init import math", "return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2,", "** 2 / 2 elif idx == 1: wh_filter = area <= self.b2_max_length", "import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack(", "self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs", "(scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img =", "(feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:,", "-1), topk) topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch,", "* h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1):", "xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch, topk, 1) * down_ratio wh", "scores = scores.view(batch, topk, 1) bboxes = torch.cat([ xs - wh[..., [0]], ys", "bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img", "gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=>", "clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes =", "b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')):", "(kernel_size - 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding))", "h_radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x", "y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3]", "gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1,", "= wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds)", "height, width = heatmap.shape[0:2] left, right = min(x, w_radius), min(width - x, w_radius", "for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp =", "wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes,", "self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def", "std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats):", "stride=1, padding=pad) keep = (hmax == heat).float() out_heat = heat if out_heat is", "soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0)", "image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap:", "topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses,", "= pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to filter", "build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i", "t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1,", "build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1))", "= list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids:", "+ 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H - 1) *", "+ wh[..., 0] + 1) * (wh[..., 3] + wh[..., 1] + 1)", "topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind /", "left, right = min(x, w_radius), min(width - x, w_radius + 1) top, bottom", "img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] =", "h, w). reg_weight: tensor, (batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape =", "w). reg_weight: tensor, (batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0]", "dim=0)) # (2, h, w) # (batch, h, w, 4) pred_boxes = torch.cat((getattr(self,", "topk_xs = (topk_inds % width).int().float() # (batch, topk). select topk from 80*topk topk_score,", "for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x + shortcuts[i]", "= torch.cat([ xs - wh[..., [0]], ys - wh[..., [1]], xs + wh[...,", "xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 =", "loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta)", "is None else out_heat return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min,", "-1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log,", "down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num", "bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2", "heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx],", "= nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1 > 0) & (heat_b2", "== heat).float() out_heat = heat if out_heat is None else out_heat return out_heat", "+ 1, -n:n + 1] h = np.exp(-(x * x / (2 *", "gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2)", "- left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius -", "__init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1,", "same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg", "self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num", "gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes,", "self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4,", "- 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y,", "h, w = 2 * h_radius + 1, 2 * w_radius + 1", "- top:h_radius + bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape) > 0", "base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H - 1) * base_step +", "reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2,", "self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else:", "(num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img, (80, h, w). box_target:", "len(inplanes) == 4 and len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes =", "not in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter", "* h_radius + 1, 2 * w_radius + 1 sigma_x = w /", "import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry", "3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0]", "box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=>", "'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1,", "for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules():", "dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws", "self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm,", "conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes) == 3 and", "y * y / (2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps *", "simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel - 1) // 2 hmax =", "bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0,", "ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls,", "output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1))", "bboxes = bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif", "hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 -", "& (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h *", "class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = []", "self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes -", "tensor, (batch, 80, h, w). box_target: tensor, (batch, 4, h, w). reg_weight: tensor,", "clses, ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) * down_ratio", "y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2", ">= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx", "b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel -", "= inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg =", "TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256,", "r_b2 = [ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2, r_b1,", "[(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m", "connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2,", "top:y + bottom, x - left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius", "self).__init__() assert len(inplanes) == 4 and len(planes) == 3 and len(shortcut_cfg) == 3", "inp = planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1,", "box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 =", "base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name,", "self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch,", "1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None", "boxes have lower priority than small boxes. for k in range(boxes_ind.shape[0]): cls_id =", "= area >= self.b1_min_length ** 2 / 2 elif idx == 1: wh_filter", "feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img, (80, h, w). box_target: tensor,", "* sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_truncate_gaussian(self,", "output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2,", "self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers =", "bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1],", "+ pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2, 3,", "k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels,", "2, 3, 1) boxes = box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H,", "= gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2))", "= heatmap.shape[0:2] left, right = min(x, w_radius), min(width - x, w_radius + 1)", "torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) # (batch,", "(torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) /", "= (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2)", "cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6)", "= down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num =", "planes): wh_layers, wh2_layers, hm_layers = [], [], [] inp = planes for i", "= nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1],", "kernel_size in enumerate(kernel_sizes): inc = in_channels if i == 0 else out_channels padding", "= [ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2]", "gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes =", "w_radius - left:w_radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0:", "padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1 >", "constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01)", "keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:,", "output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1", "shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x =", "= torch.arange( 0, (W - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device)", "0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def", "topk, 1) * down_ratio ys = ys.view(batch, topk, 1) * down_ratio wh =", "- 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha =", "shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w)", "class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4,", "self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg,", "= head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 =", "if i == 0 else out_channels padding = (kernel_size - 1) // 2", "x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i,", "pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2,", "[0]], ys - wh[..., [1]], xs + wh[..., [2]], ys + wh[..., [3]]", "def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100)", "xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) * down_ratio ys =", "self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx],", "feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1))", "norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes) == 3 and len(shortcut_cfg)", "= in_channels if i == 0 else out_channels padding = (kernel_size - 1)", "self.beta = beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length", "= gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1,", "(batch, topk). select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses", "self.beta).int() # larger boxes have lower priority than small boxes. for k in", "= norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def", "ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2,", "r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 =", "topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0] + 1)", "self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas):", "+ wh[..., 1] + 1) if idx == 0: wh_filter = area >=", "(height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float()", "get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height, width = pred_hm.size() pred_hm", "down_ratio, topk, idx=0): batch, cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh", "pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 =", "for wh in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m,", "= boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2)", "sigma_y=1): m, n = [(ss - 1.) / 2. for ss in shape]", "wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1)", "wh = wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds =", "h_radius + 1, 2 * w_radius + 1 sigma_x = w / 6", "pred_wh.detach() # used maxpool to filter the max score heat = self.simple_nms(pred_hm) #", "= wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[...,", "= mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor", "multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer,", "heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1 > 0) &", "min(height - y, h_radius + 1) masked_heatmap = heatmap[y - top:y + bottom,", "# collide_heat = ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] # collide_heat =", "self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if", "filter the max score heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses,", "self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap", "= gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1))", "- left:w_radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap,", "constant_init import math import numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from", "mask = wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss(", "getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0, (W - 1) *", "Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor <=> img,", "- 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is", "out_heat = heat if out_heat is None else out_heat return out_heat * keep", "= clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores =", "down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16.,", "conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1", "mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head", "box_target: tensor, tensor <=> img, (4, h, w). reg_weight: tensor, same as box_target", "= down_ratio shifts_x = torch.arange( 0, (W - 1) * base_step + 1,", "hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes - 1 self.shortcut_cfg", "topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys,", "# collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01)", "* self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if self.alpha != self.beta:", "- 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale:", "shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) # (batch, h,", "2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]],", "def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256,", "output_h, output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] =", "else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1,", "= topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def", "reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel", "scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img", "def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1,", "'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2}", "focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4", "from ..registry import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels,", "wh[..., 1] + 1) if idx == 0: wh_filter = area >= self.b1_min_length", "ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor),", "heat, kernel=3, out_heat=None): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d(", "3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2, 3, 1) mask =", "import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init,", "# larger boxes have lower priority than small boxes. for k in range(boxes_ind.shape[0]):", "0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] +", "3] + wh[..., 1] + 1) if idx == 0: wh_filter = area", "wh[..., 0] + 1) * (wh[..., 3] + wh[..., 1] + 1) if", "= self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2)", "image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h, w). box_target: tensor,", "+ 1) if idx == 0: wh_filter = area >= self.b1_min_length ** 2", "torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0,", "2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]]", "ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer(", "output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2))", "avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1,", "w). \"\"\" y, shortcuts = [], [] x = feats[-1] for i, shortcut_layer", "= xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch, topk, 1) * down_ratio", "keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2],", "min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap,", "collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01) if", "scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:,", "clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1)", "constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch,", "elif 'b1' not in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses =", "height, width = scores.size() # (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat,", "'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert", "= img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2]", "self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\", "boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2,", "i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels", "conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size in enumerate(kernel_sizes): inc =", "(feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int() #", "result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch:", "/= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int()", "+ wh[..., [3]] ], dim=2) return heat, inds, clses, scores, bboxes, xs, ys,", "gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. *", "nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0,", "shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x =", "gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id],", "bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls", "return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\"", "deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample:", "heat if out_heat is None else out_heat return out_heat * keep def bbox_areas(self,", "= bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01,", "base_step = down_ratio shifts_x = torch.arange( 0, (W - 1) * base_step +", "* sigma_x) + y * y / (2 * sigma_y * sigma_y))) h[h", "dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H - 1) * base_step + 1,", "gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,).", "tensor, (batch, 4, h, w). reg_weight: tensor, (batch, 1, h, w). \"\"\" with", "= None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers =", "inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i <", "sigma_x) + y * y / (2 * sigma_y * sigma_y))) h[h <", "is None or H != getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]:", "min(width - x, w_radius + 1) top, bottom = min(y, h_radius), min(height -", "padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if", "self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2,", "F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def", "dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0] + 1) *", "center, h_radius, w_radius, k=1): h, w = 2 * h_radius + 1, 2", "b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel - 1)", "getattr(self, base_loc_name) is None or H != getattr(self, base_loc_name).shape[ 1] or W !=", "y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas =", "fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha", "gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel,", "included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1])", "1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh =", "from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule)", "inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 )", "[h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1,", "img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1,", "as nn import torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init, constant_init import", "+ wh[..., [2]], ys + wh[..., [3]] ], dim=2) return heat, inds, clses,", "if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids =", "masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian", "2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax ==", "loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat,", "self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d):", "in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x)", "have lower priority than small boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k]", "focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls", "pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2'))", "!= getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0, (W - 1)", "= gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2))", "tensor, (batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1,", "base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0, (W - 1) * base_step", "output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind]", "must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm", "img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes,", "box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0", "gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx", "= clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1) bboxes = torch.cat([ xs", "(topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() # (batch, topk). select topk", "(batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self,", "gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape) >", "gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80,", "= bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas = (y_max", "else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers =", "gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for", "wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append(", "wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1,", "normal_init, kaiming_init, constant_init import math import numpy as np from mmdet.ops import ModulatedDeformConvPack,", "m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh", "cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas)", "heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1", "'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height, width = scores.size() #", "torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1]", "wh = pred_wh.detach() # used maxpool to filter the max score heat =", "= (wh[..., 2] + wh[..., 0] + 1) * (wh[..., 3] + wh[...,", "wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh,", "self.alpha = alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2", "= conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled =", "wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes", "def _topk(self, scores, topk): batch, cat, height, width = scores.size() # (batch, 80,", "0 else out_channels padding = (kernel_size - 1) // 2 if conv_cfg: layers.append(", "x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256,", "wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2,", "3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'],", "planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp", "loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1',", "w) # (batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0,", "2] + wh[..., 0] + 1) * (wh[..., 3] + wh[..., 1] +", "1] h = np.exp(-(x * x / (2 * sigma_x * sigma_x) +", "= (hmax == heat).float() out_heat = heat if out_heat is None else out_heat", "+ 1) * (wh[..., 3] + wh[..., 1] + 1) if idx ==", "if self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0] + 1) * (wh[...,", "= self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1,", "mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss,", "feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h, w). wh:", "= F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2", "as F from mmcv.cnn import normal_init, kaiming_init, constant_init import math import numpy as", "pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1,", "h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x,", "= 0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w", "topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1,", "np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x / (2", "or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0, (W", "zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must be included.\" self.shortcut_layers.append(", "unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return", "shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta = beta", "self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws / 2.", "i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1]", "tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img, (80,", "h = np.exp(-(x * x / (2 * sigma_x * sigma_x) + y", "= boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx", "in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(),", "if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds =", "if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m,", "wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2]", "reg_weight: tensor, (batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] //", "local_heatmap / ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\"", "ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg,", "(labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels =", "+ bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape)", "kaiming_init, constant_init import math import numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms", "== 3 and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1", "wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack):", "gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log()", "assert layer_num > 0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3]", "x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas", "labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap,", "x + shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4))", "feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] -", "in_channels if i == 0 else out_channels padding = (kernel_size - 1) //", "topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1,", "3]], min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1],", "topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int() topk_ind =", "output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels", "gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length", "h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w = 2 *", "conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled = False", "bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0]", "x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x", "= clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes = bboxes_b2", "'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height,", "stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True))", "gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2", "inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1,", "heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor", "normal_init(m, std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self,", "feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]],", "# (2, h, w) # (batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name)", "self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else:", "if idx == 0: wh_filter = area >= self.b1_min_length ** 2 / 2", "torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1)", "y, h_radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x -", "scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes", "if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns:", "output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1,", "= torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img,", "* self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int() # larger boxes have", "planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels", "dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls", "super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers", "collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) # collide_b1 = collide_heat.gather(-1,", "H, W) avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask,", "= \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2,", "boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes", "int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, w_radius), min(width - x,", "gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) *", "heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w =", "return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor,", "wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3,", "idx == 0: wh_filter = area >= self.b1_min_length ** 2 / 2 elif", "= [] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes", "+ 1, 2 * w_radius + 1 sigma_x = w / 6 sigma_y", "1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H - 1) * base_step", "if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2,", "giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1',", "self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t,", "= wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0),", "output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind", "] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None):", "ys - wh[..., [1]], xs + wh[..., [2]], ys + wh[..., [3]] ],", "= topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk)", "wh2_layers, hm_layers = [], [], [] inp = planes for i in range(self.wh_head_conv_num[0]):", "0] + 1) * (wh[..., 3] + wh[..., 1] + 1) if idx", "torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float()", "m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if", "- 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] -", "= num_classes self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1", "draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w = 2 * h_radius +", "reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes,", "self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp,", "min(x, w_radius), min(width - x, w_radius + 1) top, bottom = min(y, h_radius),", "head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None", "return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad", "0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] =", "if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0],", "(topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk)", "kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers", "in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m,", "self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta", "ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer(", "= (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img", "1] + gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs /", "bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor =", "def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel - 1) // 2 hmax", "self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 =", "(img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1,", "unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img", "self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return", "3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int()", "[output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx],", "== 0: wh_filter = area >= self.b1_min_length ** 2 / 2 elif idx", "loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height, width = scores.size() # (batch,", "(2 * sigma_x * sigma_x) + y * y / (2 * sigma_y", "soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img", "and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1", "= beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length =", "= inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels =", "box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2,", "bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /=", "no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers =", "inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels", "1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1)", "[] x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for", "= bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten", "- y_min + 1) * (x_max - x_min + 1) if keep_axis: return", "1) * (wh[..., 3] + wh[..., 1] + 1) if idx == 0:", "list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h,", "base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0))", "/ 2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if self.alpha", "right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius + right]", "hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None,", "= torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img =", "1] or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0,", "self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2,", "import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'),", "self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers", "feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t", "wh = wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float() scores = scores.view(batch,", "(num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor,", "gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def", "= (feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int()", "hm: list(tensor), (batch, 80, h, w). wh: list(tensor), (batch, 4, h, w). \"\"\"", "rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1,", "img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2,", "100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1,", "1) boxes = box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H, W) avg_factor", "1) * down_ratio ys = ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0,", "(W - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange(", "r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel - 1) //", "def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h,", "if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset,", "= labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for", "in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if", "1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor", "inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg", "], dim=2) return heat, inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2',", "// 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax", "box_target_inds] = local_heatmap / ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels,", "wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes = bboxes_b2 scores =", "= labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img =", "wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(),", "self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers", "down_ratio ys = ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0, 2, 3,", "std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m,", "len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module", "= scores.view(batch, topk, 1) bboxes = torch.cat([ xs - wh[..., [0]], ys -", "<=> img, (4, h, w). reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1,", "+ y * y / (2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps", "= torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor", "device=heatmap.device) shifts_y = torch.arange( 0, (H - 1) * base_step + 1, base_step,", "pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to filter the max", "= torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2],", "128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2,", "padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3,", "y, shortcuts = [], [] x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers):", "[1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:,", "= (feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int()", "gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]),", "out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg,", "for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut", "gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor,", "wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128,", "soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils", "gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,).", "boxes = box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H, W) avg_factor =", "self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64),", "upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4)", "loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels,", "topk) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float()", "scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] =", "H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls =", "2), stride=2) # collide_heat = ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] #", "self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes,", "base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H - 1)", "sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width =", "* down_ratio ys = ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0, 2,", "bboxes = torch.cat([ xs - wh[..., [0]], ys - wh[..., [1]], xs +", "feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:,", "b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1,", "in enumerate(kernel_sizes): inc = in_channels if i == 0 else out_channels padding =", "/ (2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0", "= getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 =", "> 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds]", "sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap,", "ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w", "if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <=", "self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [], [] inp =", "'b1' not in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses = clses_b2", "= area <= self.b2_max_length ** 2 * 2 wh = wh.view(batch, topk, 4)", "= scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2],", "(2, 2), stride=2) # collide_heat = ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0]", "width).int().float() topk_xs = (topk_inds % width).int().float() # (batch, topk). select topk from 80*topk", "gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach()", "cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls", "= self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1])", "and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self,", "min=0, max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if", "* wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2,", "h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t in [h_b1,", "return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max =", "clses = clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1) bboxes = torch.cat([", "stride=2) # collide_heat = ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] # collide_heat", "2. * self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int() # larger boxes", "sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def", "= down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num =", "bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1,", "padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3,", "w = 2 * h_radius + 1, 2 * w_radius + 1 sigma_x", "-n:n + 1] h = np.exp(-(x * x / (2 * sigma_x *", "np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius,", "self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes - 1 self.shortcut_cfg =", "boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1,", "1: wh_filter = area <= self.b2_max_length ** 2 * 2 wh = wh.view(batch,", "= gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape)", "max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length", "ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h", "scores.size() # (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds", "wh in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001)", "x, w_radius + 1) top, bottom = min(y, h_radius), min(height - y, h_radius", "+ right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius +", "h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1,", "# (batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]],", "80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds %", "2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >=", "tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel =", "padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers =", "in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter =", "2 elif idx == 1: wh_filter = area <= self.b2_max_length ** 2 *", "+ 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x,", "= self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch,", "[0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes", "topk, idx=0): batch, cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh =", "'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk =", "self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores,", "numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32", "build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1))", "1) * (x_max - x_min + 1) if keep_axis: return areas[:, None] return", "self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers =", "1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for", "-1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape,", "self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area", "clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in", "w_radius), min(width - x, w_radius + 1) top, bottom = min(y, h_radius), min(height", "device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2,", "kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01)", "/ width).int().float() topk_xs = (topk_inds % width).int().float() # (batch, topk). select topk from", "self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp", "1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor']", "return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg),", "from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from", "wh_filter = area <= self.b2_max_length ** 2 * 2 wh = wh.view(batch, topk,", "in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if isinstance(m,", "wh_layers, wh2_layers, hm_layers = [], [], [] inp = planes for i in", "feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor", "self.b2_max_length ** 2 * 2 wh = wh.view(batch, topk, 4) clses = clses.view(batch,", "bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx =", "= scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2]", "3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers,", "mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from", "Returns: heatmap: tensor, tensor <=> img, (80, h, w). box_target: tensor, tensor <=>", "img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h, w). box_target: tensor, (batch, 4,", "gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels:", "in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must be included.\"", "= b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms =", "maxpool to filter the max score heat = self.simple_nms(pred_hm) # (batch, topk) scores,", "4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor", "feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:,", "list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx", "[self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m", "score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape", "[] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers)", "shifts_y = torch.arange( 0, (H - 1) * base_step + 1, base_step, dtype=torch.float32,", "-1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 =", "scores, inds, clses, ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1)", "heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2,", "def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt,", "2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha =", "range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg:", "heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys, xs = self._topk(heat,", "pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W =", "r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2,", "1, 2 * w_radius + 1 sigma_x = w / 6 sigma_y =", "// self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2,", "isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for", "box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2,", "= max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length =", "fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div", "range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item())", "wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule(", "self.b1_min_length ** 2 / 2 elif idx == 1: wh_filter = area <=", "self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length", "0.01) if 'b2' not in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses", "= planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg))", "loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None or", "<=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h, w). box_target:", "out_heat is None else out_heat return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False):", "self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2", "torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3]", "in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1,", "np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses", "<=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns:", "3, 1) boxes = box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H, W)", "[3]] ], dim=2) return heat, inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1',", "bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls", "padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3,", "labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor,", "sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2]", "gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2,", "batch, cat, height, width = scores.size() # (batch, 80, topk) topk_scores, topk_inds =", "head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes)", "0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg))", "scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1,", "bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten ==", "inc = in_channels if i == 0 else out_channels padding = (kernel_size -", "\"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel,", "and len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes =", "alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2", "layers = [] for i, kernel_size in enumerate(kernel_sizes): inc = in_channels if i", "collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not", "5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id)", "4, 3, padding=1)) inp = planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp,", "bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d):", "@force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk", "h_radius), min(height - y, h_radius + 1) masked_heatmap = heatmap[y - top:y +", "clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1,", "= shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg =", "gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *=", "list(tensor), (batch, 80, h, w). wh: list(tensor), (batch, 4, h, w). \"\"\" y,", "scores = scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in", "topk, 1).float() scores = scores.view(batch, topk, 1) bboxes = torch.cat([ xs - wh[...,", "if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m)", "used maxpool to filter the max score heat = self.simple_nms(pred_hm) # (batch, topk)", "heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2,", "inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk,", "= topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs =", "k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k],", "self.num_classes = num_classes self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 =", "r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat,", "min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1)", "in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if", "self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers =", "kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for", "self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m,", "/ 2 elif idx == 1: wh_filter = area <= self.b2_max_length ** 2", "self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0] + 1) * (wh[..., 3]", "inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg,", "- wh[..., [1]], xs + wh[..., [2]], ys + wh[..., [3]] ], dim=2)", "0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w =", "3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws =", "local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap", "- 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep", ") else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]):", "boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx =", "= box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H, W) avg_factor = mask.sum()", "topk) topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1,", "self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [],", "m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args:", "h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap, center,", "box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2", "kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for", "class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels,", "inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if", "fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:,", "h, w). box_target: tensor, (batch, 4, h, w). reg_weight: tensor, (batch, 1, h,", "bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self,", "img, (80, h, w). box_target: tensor, tensor <=> img, (4, h, w). reg_weight:", "1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox", "isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0)", "reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1],", "gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1) /", "w_radius, k=1): h, w = 2 * h_radius + 1, 2 * w_radius", "!= getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x", "topk) scores, inds, clses, ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk,", "1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1,", "self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm,", "1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes =", "tensor <=> img, (80, h, w). box_target: tensor, tensor <=> img, (4, h,", "h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1", "pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1':", "wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers", "+ gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2.", "self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers)", "gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor).", "img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 =", "HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False):", "base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange(", "2])) for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x +", "wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0] +", "feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1]", "bottom, x - left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom,", "0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] -", "feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints", "for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap,", "self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single(", "r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1,", "bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids", "focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter", "padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self,", "output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log,", "self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else:", "clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1) bboxes = torch.cat([ xs -", "if 'b2' not in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses =", "wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1,", "for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1]", "None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [],", "= h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian)", "from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn", "padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for i", "b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta", "b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def", "upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4", "hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers)", "<=> img, (num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns:", "'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg,", "topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs", "m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in", "(wh[..., 2] + wh[..., 0] + 1) * (wh[..., 3] + wh[..., 1]", "in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4 =", "gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length **", "pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1,", "== 0 else out_channels padding = (kernel_size - 1) // 2 if conv_cfg:", "= fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap /", "gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1", "self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx],", "width = scores.size() # (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1),", "= gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 =", ".anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn =", "img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:,", "% (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds %", "+ gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1)", "self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws", "i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x + shortcuts[i] y.append(x)", "topk, 1) * down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0),", "torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0,", "np.exp(-(x * x / (2 * sigma_x * sigma_x) + y * y", "pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 =", "result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta):", "bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def", "= getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes = bboxes_b1 scores", "init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in", "def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64,", "self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self,", "== 4 and len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes = inplanes", "loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W", "gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length", "h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h,", "= 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds]", "boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >=", "loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height, width = scores.size()", "tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape:", "nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg)", "0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp(", "local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap, box_target,", "self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return", "= self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return", "= (topk_inds % width).int().float() # (batch, topk). select topk from 80*topk topk_score, topk_ind", "boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2,", "self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if", "math import numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import", "enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x", "(topk_inds % width).int().float() # (batch, topk). select topk from 80*topk topk_score, topk_ind =", "= pred_wh.detach() # used maxpool to filter the max score heat = self.simple_nms(pred_hm)", "-1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter =", "h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2. *", "heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm", "UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in", "/ 2. * self.beta).int() # larger boxes have lower priority than small boxes.", "< np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_truncate_gaussian(self, heatmap, center, h_radius,", "tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h, w).", "loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1,", "for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules():", "not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg):", "= torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] =", "def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m", "focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg", "torch.cat([ xs - wh[..., [0]], ys - wh[..., [1]], xs + wh[..., [2]],", "self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp =", "topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2)", "nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1 > 0) & (heat_b2 >", "[], [] x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2]))", "fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 =", "wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height, width =", "return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128,", "= local_heatmap / ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape):", "= pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to filter the max score", "for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\"", "in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules():", "+ 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls,", "= wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float() scores = scores.view(batch, topk,", "inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 )", "3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1])", "h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_()", "<= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0]", "x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x,", "y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, w_radius),", "80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int() topk_ind", "0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight,", "= ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn)", "(y_max - y_min + 1) * (x_max - x_min + 1) if keep_axis:", "bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\", "hm_layers = [], [], [] inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append(", "m, n = [(ss - 1.) / 2. for ss in shape] y,", "= nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() out_heat", "dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i", "b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None,", "= gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0,", "(kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() out_heat = heat if", "labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio,", "6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y =", "Returns: heatmap: tensor, (batch, 80, h, w). box_target: tensor, (batch, 4, h, w).", "* -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2", "wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape']", "/ 6 sigma_y = h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y)", "bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls)", "masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log,", "h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 =", "** 2 * 2 wh = wh.view(batch, topk, 4) clses = clses.view(batch, topk,", "* x / (2 * sigma_x * sigma_x) + y * y /", "pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to filter the max score heat", "self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp,", "4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2,", "= int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, w_radius), min(width", "= clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] -", "wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses", "if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]:", "= scores.size() # (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk)", "self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats: list(tensor).", "torch.arange( 0, (W - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y", "max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes) == 3", "= feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:,", "// self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply(", "hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3,", "width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to", "boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self,", "cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id]", "'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2,", "dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1,", "2, 3, 1) mask = wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4", "(batch, 4, h, w). \"\"\" y, shortcuts = [], [] x = feats[-1]", "else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses =", "<reponame>mrsempress/mmdetection import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn", "* (wh[..., 3] + wh[..., 1] + 1) if idx == 0: wh_filter", "ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None]", "= self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) )", "in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]),", "torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return", "wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3,", "return heat, inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2'))", "x = upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4 = y[-1] hm", "inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk,", "(batch, h * w) # collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr", "if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x):", "self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2,", "heat, inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def", "y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x *", "- top:y + bottom, x - left:x + right] masked_gaussian = gaussian[h_radius -", "self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg", "inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes) ==", "for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m", "<= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx],", "1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append(", "pred_wh, down_ratio, topk, idx=0): batch, cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_()", "# (batch, topk) scores, inds, clses, ys, xs = self._topk(heat, topk=topk) xs =", "clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes = bboxes_b2 scores", "gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1,", "layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__()", "/ 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha", "- pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3,", "return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk):", "= planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg))", "\"\"\" y, shortcuts = [], [] x = feats[-1] for i, shortcut_layer in", "collide_heat = ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0),", "left:w_radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian", "output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1", "None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k]", "1) mask = wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4 loss_bbox =", "inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__()", "1) bboxes = torch.cat([ xs - wh[..., [0]], ys - wh[..., [1]], xs", "xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2,", "1, h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] //", "heat).float() out_heat = heat if out_heat is None else out_heat return out_heat *", "= wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg", "= wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area =", "nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def", "pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2", "self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if", "256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2),", "list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts = [], [] x =", "/ 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n", "wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch", "__init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size", "boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap, box_target, reg_weight def ttf_target_single(self,", "[2, 3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2, 3, 1) mask", "shortcuts = [], [] x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i", "ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) * down_ratio ys", "= torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:,", "hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1],", "> 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target,", "kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) -", "self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter = wh_filter_b1", "beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None or H != getattr(self, base_loc_name).shape[", "conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding))", ") ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers)", "Returns: hm: list(tensor), (batch, 80, h, w). wh: list(tensor), (batch, 4, h, w).", "outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must", "topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds", "topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss -", "= labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh,", "topk_inds = topk_inds % (height * width) topk_ys = (topk_inds / width).int().float() topk_xs", "__init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64),", "self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0", "(heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h * w)", "scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1)", "topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs", "dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not", "unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1),", "if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size,", "= self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if", "ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from", "reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0))", "(2, h, w) # (batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) -", "n = [(ss - 1.) / 2. for ss in shape] y, x", "height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool", "output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4,", "= planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels =", "bottom = min(y, h_radius), min(height - y, h_radius + 1) masked_heatmap = heatmap[y", "out_heat return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max", "- 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else:", "min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0,", "y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 =", "@force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas,", "+ 1 sigma_x = w / 6 sigma_y = h / 6 gaussian", "b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1,", "self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp,", "= y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4))", "> 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap", "wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep]", "r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3,", "= planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg))", "r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2", "'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1,", "= (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3])", "pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta)", "torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init, constant_init import math import numpy", "heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2),", "top:h_radius + bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape) > 0 and", "if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1],", "w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap,", "inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None", "3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat =", "(2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return", "pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel),", "down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1)", "wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule(", "* w) # collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg,", "1) * down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1,", "reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=>", "gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio", "area >= self.b1_min_length ** 2 / 2 elif idx == 1: wh_filter =", "w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) +", "bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1' not", "layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must be", "== 3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 =", "force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob,", "import normal_init, kaiming_init, constant_init import math import numpy as np from mmdet.ops import", "hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2", "import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import", "h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t in", "= [] for i, kernel_size in enumerate(kernel_sizes): inc = in_channels if i ==", "\\ bboxes[:, 2], bboxes[:, 3] areas = (y_max - y_min + 1) *", "than small boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap", "self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms", "w_radiuses_beta = (feat_ws / 2. * self.beta).int() # larger boxes have lower priority", "(H - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x =", "= torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds % (height * width) topk_ys", "= nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num >", "dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1,", "= collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) # collide_b1 = collide_heat.gather(-1, )", "= labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight,", "\"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1,", "2 * h_radius + 1, 2 * w_radius + 1 sigma_x = w", "feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0])", "b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2", "output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels,", "wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img", "heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2,", "self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy())))", "heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right =", "down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16.,", "* y / (2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()]", "- 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h -", "tensor, tensor <=> img, (80, h, w). box_target: tensor, tensor <=> img, (4,", "wh[..., [0]], ys - wh[..., [1]], xs + wh[..., [2]], ys + wh[...,", "(feat_ws / 2. * self.beta).int() # larger boxes have lower priority than small", "= torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]):", "layers = [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2))", "2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels,", "self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1", "scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls =", ") else: hm_layers.append(nn.Conv2d(self.hm_head_channels, self.num_fg, 3, padding=1)) wh_layers = nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers", "y / (2 * sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] =", "4 and len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes", "topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys =", "h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws / 2. *", "h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1,", "(4, h, w). reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2", "> 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) #", "+ 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x +", "layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers", "forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h, w).", "= wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs =", "clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores", "h * w) # collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr =", "{'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch,", "= (kernel_size - 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size,", "= upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4 = y[-1] hm =", "topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n =", "ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer(", "** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0]", "kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size in enumerate(kernel_sizes): inc", "self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg", "setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) # (batch, h, w,", "inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] +", "4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes", "W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm,", "(80, h, w). box_target: tensor, tensor <=> img, (4, h, w). reg_weight: tensor,", "wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True,", "layer_num > 0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] *", "wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] + wh[...,", "scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep]", "out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind,", "tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple.", "/ topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys", "= (feat_ws / 2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs", "bboxes[:, 3] areas = (y_max - y_min + 1) * (x_max - x_min", "2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if self.alpha !=", "import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head import", "scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for", "wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append(", "= gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes", "dim=2) return heat, inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1',", "self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1,", "width).int().float() # (batch, topk). select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1),", "= torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds", "torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1)", "2 / 2 elif idx == 1: wh_filter = area <= self.b2_max_length **", "not in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter", "if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes,", "def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [], [] inp = planes", "idx=0): batch, cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach()", "1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x)", "area <= self.b2_max_length ** 2 * 2 wh = wh.view(batch, topk, 4) clses", "= gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1,", "wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3,", "boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_()", "x = x + shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1", "= None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers,", "(batch, 80, h, w). box_target: tensor, (batch, 4, h, w). reg_weight: tensor, (batch,", "shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True,", "= focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg =", "= collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2'", "(batch, 80, h, w). wh: list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts", "idx == 1: wh_filter = area <= self.b2_max_length ** 2 * 2 wh", "topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch,", "idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2,", "torch.nn as nn import torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init, constant_init", "h, w). \"\"\" y, shortcuts = [], [] x = feats[-1] for i,", "heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes:", "out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size in enumerate(kernel_sizes):", "> 0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num,", "@HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8,", "torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img", "self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter = wh_filter_b2", "bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes =", "return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape,", "focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) ==", "= 2 * h_radius + 1, 2 * w_radius + 1 sigma_x =", "heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx],", "keep = (hmax == heat).float() out_heat = heat if out_heat is None else", "ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None or H !=", "return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat,", "= bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def", "hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5.,", "( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head import AnchorHead", "clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img =", "= fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha !=", "bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:,", "import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer,", "= nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers =", "self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0],", "assert len(inplanes) == 4 and len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes", "<=> img, (80, h, w). box_target: tensor, tensor <=> img, (4, h, w).", "(gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor,", "ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:,", "self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2", "* (x_max - x_min + 1) if keep_axis: return areas[:, None] return areas", "* sigma_x * sigma_x) + y * y / (2 * sigma_y *", "h, w). wh: list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts = [],", "nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m,", "y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) *", "getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0,", "b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2,", "loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2,", "h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1,", "4) clses = clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1) bboxes =", "build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1))", "= bboxes_b1 scores = scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1'", "3 and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1 =", "= self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys, xs = self._topk(heat, topk=topk)", "4, h, w). reg_weight: tensor, (batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape", "layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if", "norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg):", "3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2", "min=0, max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:,", "sigma_y = h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian =", "self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap", "self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1],", "self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num", "base_loc_name) is None or H != getattr(self, base_loc_name).shape[ 1] or W != getattr(self,", "w). reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape", "def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w = 2 * h_radius", "Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image,", "torch.arange( 0, (H - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y,", "bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter", "tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict).", "self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d):", "= inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool)", "self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2,", "= [] layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers,", "r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1,", "unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in", "topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch,", "= min(x, w_radius), min(width - x, w_radius + 1) top, bottom = min(y,", "def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss - 1.) / 2.", "self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp =", "wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5.,", "labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes,", "1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds,", "= gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1,", "(batch, 4, h, w). reg_weight: tensor, (batch, 1, h, w). \"\"\" with torch.no_grad():", "getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes = bboxes_b1 scores =", "2], bboxes[:, 3] areas = (y_max - y_min + 1) * (x_max -", "= wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2", "F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk,", "wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False):", "self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta", "bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:,", "= shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta =", "[ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ]", "= torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]),", "/ (2 * sigma_x * sigma_x) + y * y / (2 *", "if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module):", "= fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap", ") ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for i in", "layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules():", "from mmcv.cnn import normal_init, kaiming_init, constant_init import math import numpy as np from", "* 2 wh = wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float() scores", "* sigma_y * sigma_y))) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h", "list(dict). Returns: heatmap: tensor, (batch, 80, h, w). box_target: tensor, (batch, 4, h,", "base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1", "self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter", "(batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds", "[output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes,", "= np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x /", "0) def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80,", "[] for i, kernel_size in enumerate(kernel_sizes): inc = in_channels if i == 0", "for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers):", "= scores_b1 clses = clses_b1 wh_filter = wh_filter_b1 elif 'b1' not in self.inf_branch:", "1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor)", "wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4,", "ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4).", "\"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4). gt_labels: tensor, tensor <=>", "[1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h - 1) feat_hs, feat_ws", "gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target(", "self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2", "gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single(", "= heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right", "h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad =", "gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes /", "4, h, w). \"\"\" y, shortcuts = [], [] x = feats[-1] for", "h, w). reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 =", "bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas = (y_max - y_min +", "def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num,", "heatmap_b1, heatmap_b2, box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args:", "# (batch, topk). select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk)", "gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss - 1.) / 2. for", "top, bottom = min(y, h_radius), min(height - y, h_radius + 1) masked_heatmap =", "* layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in", "= np.exp(-(x * x / (2 * sigma_x * sigma_x) + y *", "= (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() # (batch, topk). select", "= topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1,", "down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num", "self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled", "fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] =", "norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def", "heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio):", "bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:,", "<= self.b2_max_length ** 2 * 2 wh = wh.view(batch, topk, 4) clses =", "self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2,", "padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3,", "else self.focal_loss_beta) loss_cls_b2, loss_bbox_b2 = self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2',", "gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w", "else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls =", "self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection must be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp,", "in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in", "gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2,", "kernel_size, padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def", "self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape)", "= torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) #", "box_target.permute(0, 2, 3, 1) mask = wh_weight.view(-1, H, W) avg_factor = mask.sum() +", "h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel", "tensor <=> img, (4, h, w). reg_weight: tensor, same as box_target \"\"\" output_h_b1,", "3, 1) mask = wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4 loss_bbox", "for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp =", "/ down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws /", "w). wh: list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts = [], []", "topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return", "self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels = hm_head_channels self.wh_head_channels", "out_channels padding = (kernel_size - 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc,", "self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1],", "conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1", "self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int() # larger boxes have lower", "shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes) == 4 and", "self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height,", "self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only", "w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id =", "topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds % (height *", "topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds % (height", "box_target_b1, box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor).", "2. * self.beta).int() # larger boxes have lower priority than small boxes. for", "cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx],", "if getattr(self, base_loc_name) is None or H != getattr(self, base_loc_name).shape[ 1] or W", "cat, height, width = scores.size() # (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch,", "2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1,", "in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for", "local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap, box_target, reg_weight", "3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4,", "for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img", "down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4,", "fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta:", ">= self.b1_min_length ** 2 / 2 elif idx == 1: wh_filter = area", "self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only", "small boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1 fake_heatmap =", "ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if", "m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in self.modules(): if", "0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas = (y_max - y_min", "0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div", "scores = scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1,", "dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter =", "self.wh_b2]: for m in wh.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001) for m in", "1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2])", "inds, clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self,", "std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m in wh.modules():", "i, kernel_size in enumerate(kernel_sizes): inc = in_channels if i == 0 else out_channels", "topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1,", "[3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m", "gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1,", "wh_filter_b1 elif 'b1' not in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses", "w) # collide_b1 = collide_heat.gather(-1, ) result_list = [] score_thr = getattr(cfg, 'score_thr',", "shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h,", "scores = torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1,", "= img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else:", "= w / 6 sigma_y = h / 6 gaussian = self.gaussian_2d((h, w),", "torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds % (height * width) topk_ys =", "from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import", "\"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=>", "/ down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w -", "[], [], [] inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp,", "build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head import AnchorHead class", "= torch.cat([scores_b1, scores_b2], dim=1) clses = torch.cat([clses_b1, clses_b2], dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2],", "in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h =", "1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch,", "xs + wh[..., [2]], ys + wh[..., [3]] ], dim=2) return heat, inds,", "'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height, width =", "= torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img =", "nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128,", "pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used maxpool to filter the", "getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\", "1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep =", "self.inplanes = inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2 = down_ratio_b2 self.hm_head_channels", "labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx =", "for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat((", "** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length", "in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2,", "box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1,", "self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:,", "layers.append(mdcn) if norm_cfg: layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class", "batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img >", "'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1", "norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList()", "box_target: tensor, (batch, 4, h, w). reg_weight: tensor, (batch, 1, h, w). \"\"\"", "- 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m +", "torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log", "+ shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) *", "'b2' not in self.inf_branch: bboxes = bboxes_b1 scores = scores_b1 clses = clses_b1", "== cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx]", "1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead):", "wh[..., [3]] ], dim=2) return heat, inds, clses, scores, bboxes, xs, ys, wh_filter", "xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas,", "if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg, kernel_size=3, padding=1 ) ) else: hm_layers.append(nn.Conv2d(self.hm_head_channels,", "forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64, 128, 256, 512),", "\"\"\" Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h, w). wh: list(tensor),", "labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target,", "nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self):", "% width).int().float() # (batch, topk). select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch,", "i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return", "'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg,", "return h def draw_truncate_gaussian(self, heatmap, center, h_radius, w_radius, k=1): h, w = 2", "else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for i in range(self.hm_head_conv_num): hm_layers.append(", "= wh_weight.view(-1, H, W) avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes,", "= torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx =", "getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x =", "_init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers(", "self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys, xs = self._topk(heat, topk=topk) xs", "= scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img", "- y, h_radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x", "in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1)", "boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area:", "math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else: gt_b1_idx =", "self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1,", "collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) # collide_b1 = collide_heat.gather(-1, ) result_list", "= False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [], []", "6 sigma_y = h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian", "2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2. *", "beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None,", "h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2,", "-1, 1).gather(1, topk_ind).view(batch, topk) topk_xs = topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score,", "iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels))", "= gt_labels[k] - 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] =", "0, (W - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y =", "(hmax == heat).float() out_heat = heat if out_heat is None else out_heat return", "out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels,", "masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius + right] if", "y_min + 1) * (x_max - x_min + 1) if keep_axis: return areas[:,", "width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() # (batch,", "nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([", "= nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2],", "wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs = max_objs", "else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append(", "avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) *", "topk). select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses =", "_topk(self, scores, topk): batch, cat, height, width = scores.size() # (batch, 80, topk)", "max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name)", "ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap =", "= ((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1)", "2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1',", "w). box_target: tensor, tensor <=> img, (4, h, w). reg_weight: tensor, same as", "self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4,", "3, padding=1)) inp = planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels,", "img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels,", "self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1':", "def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i,", "cat, -1), topk) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds", "+ 1] h = np.exp(-(x * x / (2 * sigma_x * sigma_x)", "shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 = F.relu(self.wh_b1(y_s4)) * self.wh_scale_factor_b1", "score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes = bboxes_b1", "shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg", "= self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind]", "pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2,", "use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg", "= heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian =", "min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self,", "nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) #", "(feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if", "list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas:", "w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width", "boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:,", "* self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int()", "bboxes[:, 2], bboxes[:, 3] areas = (y_max - y_min + 1) * (x_max", "pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1,", "normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m in wh.modules(): if", "select topk from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind", "bottom, w_radius - left:w_radius + right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) >", "scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5))", "def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2,", "planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp", "2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2))", "scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1)", "nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0],", "pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) *", "cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() # used", "for t in [h_b1, h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2,", "bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:, 3] areas = (y_max -", "topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss - 1.)", "_init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [], [] inp = planes for", ") result_list = [] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not in", "= level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only =", "topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1):", "topk, 4) clses = clses.view(batch, topk, 1).float() scores = scores.view(batch, topk, 1) bboxes", "feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in", "pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height, width = pred_hm.size() pred_hm =", "# heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2,", "1, -n:n + 1] h = np.exp(-(x * x / (2 * sigma_x", "3, padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1],", "= num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2", "= gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 =", "= nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self, inplanes=(64,", "- 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0,", "wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img =", "left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius - left:w_radius", "r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1,", "wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter", "x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1], \\ bboxes[:, 2], bboxes[:,", "b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2':", "num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64,", "4, 3, padding=1)) inp = planes for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp,", "pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) #", "norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self,", "self.alpha).int() w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta", "i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x", "topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1", "= min(y, h_radius), min(height - y, h_radius + 1) masked_heatmap = heatmap[y -", "ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for", "down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds", "max score heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys, xs", "1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right]", "h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id", "wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area =", "heatmap.shape[0:2] left, right = min(x, w_radius), min(width - x, w_radius + 1) top,", "1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:,", "boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length ** 2) else:", "feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:,", "-1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_xs =", "pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else", "= \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3),", "= (y_max - y_min + 1) * (x_max - x_min + 1) if", "topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2,", "right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k,", "loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2': loss_bbox_b2} def _topk(self, scores, topk): batch, cat, height, width", "- feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2, (gt_boxes[:,", "scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) #", "labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1)", "0, (H - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x", "h, w) # (batch, h, w, 4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:,", "topk_xs.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self,", "fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes =", "shape, sigma_x=1, sigma_y=1): m, n = [(ss - 1.) / 2. for ss", "3] areas = (y_max - y_min + 1) * (x_max - x_min +", "img, (4, h, w). reg_weight: tensor, same as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2,", "labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,))", "= self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) )", "loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1,", "[0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1,", "1] + 1) if idx == 0: wh_filter = area >= self.b1_min_length **", "base_loc_name, torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) # (batch, h, w, 4)", "scores, topk): batch, cat, height, width = scores.size() # (batch, 80, topk) topk_scores,", "pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2, 3, 1)", "self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2", "wh_filter = area >= self.b1_min_length ** 2 / 2 elif idx == 1:", "= hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes - 1", "None else out_heat return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min,", "b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 def simple_nms(self,", "cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id,", "self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def", "topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch,", "output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2))", "UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ])", "else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True))", "self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers()", "sigma_x * sigma_x) + y * y / (2 * sigma_y * sigma_y)))", "right = min(x, w_radius), min(width - x, w_radius + 1) top, bottom =", "pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta)", "<=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img, (80, h,", "2 * w_radius + 1 sigma_x = w / 6 sigma_y = h", "as box_target \"\"\" output_h_b1, output_w_b1, output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1", "2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32,", "heatmap: tensor, (batch, 80, h, w). box_target: tensor, (batch, 4, h, w). reg_weight:", "img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten", "k=1): h, w = 2 * h_radius + 1, 2 * w_radius +", "self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg", "self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num", "topk): batch, cat, height, width = scores.size() # (batch, 80, topk) topk_scores, topk_inds", "fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single(", "r_b2 def simple_nms(self, heat, kernel=3, out_heat=None): pad = (kernel - 1) // 2", "gt_boxes.new_zeros((1, output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2", "as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from", "((heat_b1 > 0) & (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) #", "i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0]", "hm_weight_factor if getattr(self, base_loc_name) is None or H != getattr(self, base_loc_name).shape[ 1] or", "feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) /", "b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms", "nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls =", "heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float() out_heat = heat", "gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1',", "reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img,", "gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2,", "wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch,", "loss_bbox_b1 = self.loss_single( pred_hm_b1, pred_wh_b1, h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4", "mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return", "fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds", "= bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0,", "output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) * -1 reg_weight_b1 = gt_boxes.new_zeros((1, output_h_b1, output_w_b1))", "gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1,", "ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2,", "return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n", "= soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes),", "multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = [", "= wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1 =", "* down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3))", "giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS", "0] + gt_boxes[:, 2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2],", "(inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert layer_num > 0, \"Shortcut connection", "xs - wh[..., [0]], ys - wh[..., [1]], xs + wh[..., [2]], ys", "sigma_x=1, sigma_y=1): m, n = [(ss - 1.) / 2. for ss in", "build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential):", "hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes", "for i in range(self.wh_head_conv_num[1]): wh2_layers.append( ConvModule( inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp =", "down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha = (feat_ws / 2.", "topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1,", "= alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 =", "// 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc,", "math.log(self.b2_max_length ** 2) else: gt_b1_idx = gt_boxes.max(-1)[0] >= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <=", "to filter the max score heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds,", "= F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio,", "box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log", "output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2", "w_radius + 1 sigma_x = w / 6 sigma_y = h / 6", "if self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta =", "priority than small boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] - 1", "torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp(", "0: wh_filter = area >= self.b1_min_length ** 2 / 2 elif idx ==", "wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers", "= nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2)", "for m in self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for", "ConvModule) from ..registry import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self,", "torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if", "reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2],", "shift_y), dim=0)) # (2, h, w) # (batch, h, w, 4) pred_boxes =", "img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels: list(tensor). tensor", "areas = (y_max - y_min + 1) * (x_max - x_min + 1)", "+ 1) top, bottom = min(y, h_radius), min(height - y, h_radius + 1)", "level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead,", "1) top, bottom = min(y, h_radius), min(height - y, h_radius + 1) masked_heatmap", "ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self):", "(gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs", "* self.wh_scale_factor_b1 wh_b2 = F.relu(self.wh_b2(y_s4)) * self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self,", "(feat_ws / 2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs /", "with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2,", "beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length", "torch.stack((shift_x, shift_y), dim=0)) # (2, h, w) # (batch, h, w, 4) pred_boxes", "padding=1)) inp = planes for i in range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3,", "in self.inf_branch: bboxes = bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter =", "score heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys, xs =", "# heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat = ((heat_b1 > 0)", "super(AnchorHead, self).__init__() assert len(inplanes) == 4 and len(planes) == 3 and len(shortcut_cfg) ==", "3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4,", "heatmap: tensor, tensor <=> img, (80, h, w). box_target: tensor, tensor <=> img,", "output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 =", "wh_filter = wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2],", "range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) &", "pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1,", "len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes = planes self.down_ratio_b1 = down_ratio_b1 self.down_ratio_b2", "heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian = gaussian[h_radius", "/ 2. * self.beta).int() w_radiuses_beta = (feat_ws / 2. * self.beta).int() # larger", "64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54, hm_weight=1.,", ") else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for i in range(self.hm_head_conv_num):", "]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:], self.planes, self.shortcut_cfg): assert", "= wh_filter_b2 else: bboxes = torch.cat([bboxes_b1, bboxes_b2], dim=1) scores = torch.cat([scores_b1, scores_b2], dim=1)", "down_ratio shifts_x = torch.arange( 0, (W - 1) * base_step + 1, base_step,", "self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num) in zip(self.inplanes[::-1][1:],", "= gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx =", "\"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] //", "ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh =", "topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss - 1.) /", "def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H,", "output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1", "4) pred_boxes = torch.cat((getattr(self, base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:,", "// self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1,", "= wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area = (wh[..., 2] + wh[..., 0]", "labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp( min=0, max=img_shape[1]", "2]) / 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int)", "out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1)", "*= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap, box_target, reg_weight def", "out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:,", "enumerate(self.upsample_layers): x = upsampling_layer(x) x = x + shortcuts[i] y.append(x) y_s4 = y[-1]", "inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1,", "gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor <=> image, (gt_num, 4). gt_labels:", "2 * 2 wh = wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float()", "no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection,", "torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i]", "= (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints =", "be included.\" self.shortcut_layers.append( ShortcutConnection(inp, outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm =", "reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 =", "list(tensor). Returns: hm: list(tensor), (batch, 80, h, w). wh: list(tensor), (batch, 4, h,", "isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls = bias_init_with_prob(0.01) for m in self.hm.modules(): if isinstance(m, nn.Conv2d):", "box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape", "= (feat_ws / 2. * self.beta).int() # larger boxes have lower priority than", "= hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes =", "dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls,", "box_target_b2, reg_weight_b1, reg_weight_b2 def ttf_target(self, gt_boxes, gt_labels, img_metas): \"\"\" Args: gt_boxes: list(tensor). tensor", "(batch, 1, h, w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1]", "if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img,", "* base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H -", "self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1", "len(planes) == 3 and len(shortcut_cfg) == 3 self.inplanes = inplanes self.planes = planes", "pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None): h_b1, h_b2, b_b1, b_b2, r_b1,", "wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False,", "self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[0], self.planes[1], norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers", "self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1 ) ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp", "import numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply,", "> 0) & (heat_b2 > 0)).max(1)[0] # collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch,", "reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1, heatmap_b2, box_target_b1,", "self).__init__() layers = [] for i, kernel_size in enumerate(kernel_sizes): inc = in_channels if", "output_h_b2, output_w_b2 = feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1", "normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m in", "tensor, tensor <=> img, (4, h, w). reg_weight: tensor, same as box_target \"\"\"", "self.hm.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1,", "b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single( pred_hm_b1,", "wh_head_conv_num self.num_classes = num_classes self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1", "heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx], gt_labels[gt_b2_idx], boxes_ind[gt_b2_idx], [output_h_b2, output_w_b2], self.down_ratio_b2) return heatmap_b1,", "labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm,", "box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div =", "2 wh = wh.view(batch, topk, 4) clses = clses.view(batch, topk, 1).float() scores =", "base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1) boxes = box_target.permute(0, 2,", "= giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2',", "gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx],", "..registry import HEADS from .anchor_head import AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels,", "= b2_max_length self.level_base_area = level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta =", "- 2])) for i, upsampling_layer in enumerate(self.upsample_layers): x = upsampling_layer(x) x = x", "in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = [] layers.append(mdcn) if norm_cfg:", "* keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0],", "soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels = labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls =", "= bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img", "[2]], ys + wh[..., [3]] ], dim=2) return heat, inds, clses, scores, bboxes,", "= labels_int_flatten.new_zeros((0,)) for cls_id in unique_cls_ids: cls_id_idx = (labels_int_flatten == cls_id) soft_bboxes, ori_idx", "= gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log =", "if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap)", ") ) else: wh_layers.append(nn.Conv2d(self.wh_head_channels[0], 4, 3, padding=1)) inp = planes for i in", "-1) # (batch, h * w) # collide_b1 = collide_heat.gather(-1, ) result_list =", "* base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self,", "Args: feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h, w). wh: list(tensor), (batch,", "planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1,", "fake_heatmap > 0 box_target[:, box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap =", "= ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0, 2, 3, 1).contiguous() wh", "lower priority than small boxes. for k in range(boxes_ind.shape[0]): cls_id = gt_labels[k] -", "self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m,", "num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha", "64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3),", "wh_weight_b1 self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area", "+ 1) * (x_max - x_min + 1) if keep_axis: return areas[:, None]", "x / (2 * sigma_x * sigma_x) + y * y / (2", "= wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes = num_classes self.num_fg =", "1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha", "wh[..., [2]], ys + wh[..., [3]] ], dim=2) return heat, inds, clses, scores,", "int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left, right = min(x, w_radius), min(width -", "128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2,", "range(self.hm_head_conv_num): hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg:", "reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes", "min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return", "level_base_area self.inf_branch = inf_branch self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only", "out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers)", "+ bottom, x - left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius +", "ys = ys.view(batch, topk, 1) * down_ratio wh = wh.permute(0, 2, 3, 1).contiguous()", "= wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img", "shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x", "wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep", "dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img =", ">= self.b1_min_length gt_b2_idx = gt_boxes.max(-1)[0] <= self.b2_max_length heatmap_b1, box_target_b1, reg_weight_b1 = self.ttf_target_single_single( heatmap_b1,", "heatmap, center, h_radius, w_radius, k=1): h, w = 2 * h_radius + 1,", "hm_layers.append( ConvModule( inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append(", "inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk),", "= pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4) loss_cls = ct_focal_loss(pred_hm, heatmap,", "512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81,", "mmcv.cnn import normal_init, kaiming_init, constant_init import math import numpy as np from mmdet.ops", "AnchorHead class UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels,", "if out_heat is None else out_heat return out_heat * keep def bbox_areas(self, bboxes,", "hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers(", "UpsamplingLayers(nn.Sequential): def __init__(self, in_channels, out_channels, norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3,", "boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx", "= bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else: bboxes", "clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0)", "boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind = torch.topk(boxes_areas_log, boxes_areas_log.size(0)) gt_boxes = gt_boxes[boxes_ind] gt_labels =", "= heat if out_heat is None else out_heat return out_heat * keep def", "= inf_branch_filter self.conv_cfg = conv_cfg self.norm_cfg = norm_cfg self.base_loc_b1 = None self.base_loc_b2 =", "1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if", "b_b1, b_b2, r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2,", "loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes,", "r_b1, r_b2 = [ torch.stack(t, dim=0).detach() for t in [h_b1, h_b2, b_b1, b_b2,", "else out_channels padding = (kernel_size - 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg,", "self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch, topk,", "max=img_shape[0] - 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms:", "= (labels_int_flatten == cls_id) soft_bboxes, ori_idx = soft_nms(torch.cat(( bboxes_per_img[cls_id_idx], scores_per_img[cls_id_idx]), dim=1), iou_thr=0.6) unique_labels", "max=output_h - 1) feat_hs, feat_ws = (feat_gt_boxes[:, 3] - feat_gt_boxes[:, 1], feat_gt_boxes[:, 2]", "= local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return heatmap,", "- wh[..., [0]], ys - wh[..., [1]], xs + wh[..., [2]], ys +", "2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n +", "* width) topk_ys = (topk_inds / width).int().float() topk_xs = (topk_inds % width).int().float() #", "- 1 fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_alpha[k].item(), w_radiuses_alpha[k].item()) heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap)", "in_channels, out_channels, kernel_sizes, conv_cfg): super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size in", "3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels, self.num_fg,", "(3, 3), stride=1, padding=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (2, 2), stride=2) # collide_heat", "inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 )", "torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds =", "width = heatmap.shape[0:2] left, right = min(x, w_radius), min(width - x, w_radius +", "wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height, width", "# collide_heat = collide_heat.view(collide_heat.size(0), -1) # (batch, h * w) # collide_b1 =", "topk, 1) bboxes = torch.cat([ xs - wh[..., [0]], ys - wh[..., [1]],", "= self.loss_single( pred_hm_b2, pred_wh_b2, h_b2, b_b2, r_b2, self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return", "layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self, in_channels, out_channels,", "gaussian = heatmap.new_tensor(gaussian) x, y = int(center[0]), int(center[1]) height, width = heatmap.shape[0:2] left,", "get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1,", "wh.permute(0, 2, 3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1),", "tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img,", "topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m, n = [(ss", "import torch.nn.functional as F from mmcv.cnn import normal_init, kaiming_init, constant_init import math import", "labels_int_flatten[cls_id_idx][ori_idx] bboxes_per_img_per_cls = torch.cat((bboxes_per_img_per_cls, soft_bboxes), dim=0) labels_per_img_per_cls = torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls", "topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds = topk_inds % (height * width)", "ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes:", "img, (num_gt,). feat_shape: tuple. Returns: heatmap: tensor, tensor <=> img, (80, h, w).", "dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep =", "feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp( feat_gt_boxes[:, [0,", "nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers =", "// self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single, gt_boxes, gt_labels,", "h_b2, b_b1, b_b2, r_b1, r_b2] ] return h_b1, h_b2, b_b1, b_b2, r_b1, r_b2", "torch.cat((labels_per_img_per_cls, unique_labels)) bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img))", "self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 = multi_apply( self.ttf_target_single,", "wh[..., [1]], xs + wh[..., [2]], ys + wh[..., [3]] ], dim=2) return", "# (batch, h * w) # collide_b1 = collide_heat.gather(-1, ) result_list = []", "= topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk) topk_ys = topk_ys.view(batch, -1, 1).gather(1, topk_ind).view(batch, topk)", "batch, cat, height, width = pred_hm.size() pred_hm = pred_hm.detach().sigmoid_() wh = pred_wh.detach() #", "wh_scale_factor_b2 self.alpha = alpha self.beta = beta self.max_objs = max_objs self.wh_weight_b1 = wh_weight_b1", "= focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter =", "inp, self.wh_head_channels[1], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg,", "nn.Conv2d): normal_init(m, std=0.01) normal_init(self.hm[-1], std=0.01, bias=bias_cls) for wh in [self.wh_b1, self.wh_b2]: for m", "box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm =", "in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if", "gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1, output_w_b1)) *", "padding = (kernel_size - 1) // 2 if conv_cfg: layers.append( build_conv_layer(conv_cfg, inc, out_channels,", "from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import", "wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:] pred_hm = torch.clamp(pred_hm.sigmoid_(), min=1e-4, max=1 - 1e-4)", "(wh[..., 3] + wh[..., 1] + 1) if idx == 0: wh_filter =", "self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4,", "80, h, w). box_target: tensor, (batch, 4, h, w). reg_weight: tensor, (batch, 1,", "img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img', 100) heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1,", "= ct_focal_loss(pred_hm, heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None or H", "False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers, hm_layers = [], [], [] inp", "bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten =", "* self.beta).int() # larger boxes have lower priority than small boxes. for k", "x - left:x + right] masked_gaussian = gaussian[h_radius - top:h_radius + bottom, w_radius", "inds, clses, ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch, topk, 1) *", "w). box_target: tensor, (batch, 4, h, w). reg_weight: tensor, (batch, 1, h, w).", "feat_shape, down_ratio): output_h, output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0,", "dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y), dim=0)) #", "import math import numpy as np from mmdet.ops import ModulatedDeformConvPack, soft_nms from mmdet.core", "= torch.cat([bboxes_per_img, scores_per_img], dim=1) else: labels_int_flatten = labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls =", "= fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap > 0 box_target[:, box_target_inds]", "isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for m in self.shortcut_layers.modules(): if isinstance(m, nn.Conv2d): kaiming_init(m) bias_cls", "gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log", "= x + shortcuts[i] y.append(x) y_s4 = y[-1] hm = self.hm(y_s4) wh_b1 =", "- 1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img", "= (topk_ind / topk).int() topk_ind = topk_ind.unsqueeze(2) topk_inds = topk_inds.view(batch, -1, 1).gather(1, topk_ind).view(batch,", "self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length ** 2) gt_b2_idx = boxes_area_topk_log <= math.log(self.b2_max_length", "self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg = head_conv_cfg self.inf_branch_filter = inf_branch_filter self.conv_cfg", "feats: list(tensor). Returns: hm: list(tensor), (batch, 80, h, w). wh: list(tensor), (batch, 4,", "!= self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item()) box_target_inds = fake_heatmap >", "self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1)", "'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2, img_metas, cfg, rescale=False): topk = getattr(cfg, 'max_per_img',", "shifts_x = torch.arange( 0, (W - 1) * base_step + 1, base_step, dtype=torch.float32,", "h, w). box_target: tensor, tensor <=> img, (4, h, w). reg_weight: tensor, same", "box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2", "self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg, self.hm_head_channels,", "clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1)", "heatmap[cls_id] = torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k],", "4, kernel_size=3, padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes", "(gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch, 80, h, w). box_target: tensor, (batch,", "torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(), w_radiuses_beta[k].item())", "feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] //", "idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2, wh_filter_b2 = \\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2,", "tuple. Returns: heatmap: tensor, tensor <=> img, (80, h, w). box_target: tensor, tensor", "h_b1, b_b1, r_b1, self.down_ratio_b1, 'base_loc_b1', self.hm_weight_b1, self.wh_weight_b1, 4 if self.focal_b2_only else self.focal_loss_beta) loss_cls_b2,", "!= self.beta: h_radiuses_beta = (feat_hs / 2. * self.beta).int() w_radiuses_beta = (feat_ws /", "topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1, padding=1) # heat_b2 =", "bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm, pred_wh_b1, pred_wh_b2,", "- 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class", "[0, 2]] = torch.clamp( feat_gt_boxes[:, [0, 2]], min=0, max=output_w - 1) feat_gt_boxes[:, [1,", "self.hm_head_channels = hm_head_channels self.wh_head_channels = wh_head_channels self.hm_head_conv_num = hm_head_conv_num self.wh_head_conv_num = wh_head_conv_num self.num_classes", "use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False, shortcut_conv_cfg=None, head_conv_cfg=None, inf_branch_filter=False, max_objs=128, conv_cfg=None, norm_cfg=dict(type='BN')): super(AnchorHead, self).__init__() assert len(inplanes)", "/ 2, (gt_boxes[:, 1] + gt_boxes[:, 3]) / 2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha", "kernel=3, out_heat=None): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat,", "topk) return topk_score, topk_inds, topk_clses, topk_ys, topk_xs def gaussian_2d(self, shape, sigma_x=1, sigma_y=1): m,", "def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max, y_max = bboxes[:, 0], bboxes[:, 1],", "dim=1) wh_filter = torch.cat([wh_filter_b1, wh_filter_b2], dim=1) for batch_i in range(bboxes.shape[0]): scores_per_img = scores[batch_i]", "\\ self.get_bboxes_single(pred_hm_b2, pred_wh_b2, self.down_ratio_b2, topk, idx=1) # heat_b2 = nn.functional.max_pool2d(heat_b2, (3, 3), stride=1,", "in self.modules(): if isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats:", "inp, self.hm_head_channels, 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.hm_head_channels if self.head_conv_cfg: hm_layers.append( build_conv_layer( self.head_conv_cfg,", "self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def __init__(self,", "torch.max(masked_heatmap, masked_gaussian * k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap,", "self.wh_weight_b2 = wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch", "# (batch, 80, topk) topk_scores, topk_inds = torch.topk(scores.view(batch, cat, -1), topk) topk_inds =", "* hm_weight_factor if getattr(self, base_loc_name) is None or H != getattr(self, base_loc_name).shape[ 1]", "+ right] if min(masked_gaussian.shape) > 0 and min(masked_heatmap.shape) > 0: torch.max(masked_heatmap, masked_gaussian *", "self.down_ratio_b2, 'base_loc_b2', self.hm_weight_b2, self.wh_weight_b2, self.focal_loss_beta) return {'losses/ttfnetv2_loss_hm_b1': loss_cls_b1, 'losses/ttfnetv2_loss_wh_b1': loss_bbox_b1, 'losses/ttfnetv2_loss_hm_b2': loss_cls_b2, 'losses/ttfnetv2_loss_wh_b2':", "wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54, beta=0.54,", "= multi_apply( self.ttf_target_single, gt_boxes, gt_labels, feat_shape=feat_shape) h_b1, h_b2, b_b1, b_b2, r_b1, r_b2 =", "-1), topk) topk_inds = topk_inds % (height * width) topk_ys = (topk_inds /", "self.use_simple_nms = use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg", "ct_div = local_heatmap.sum() local_heatmap *= boxes_area_topk_log[k] reg_weight[cls_id, box_target_inds] = local_heatmap / ct_div return", "norm_cfg=dict(type='BN'), no_upsample=False): mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers", "= (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1,", "planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp", "topk=topk) xs = xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch, topk, 1)", "outp, [3] * layer_num, self.shortcut_conv_cfg)) self.wh_b1, self.wh_b2, self.hm = self._init_branch_layers(self.planes[-1]) def init_weights(self): for", "boxes, mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def", "3, 1).contiguous() wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh", "= feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i - 2])) for i, upsampling_layer", "bboxes_per_img = bboxes_per_img_per_cls labels_per_img = labels_per_img_per_cls.float() labels_per_img = labels_per_img.squeeze(-1) result_list.append((bboxes_per_img, labels_per_img)) return result_list", "xs = xs.view(batch, topk, 1) * down_ratio ys = ys.view(batch, topk, 1) *", "elif idx == 1: wh_filter = area <= self.b2_max_length ** 2 * 2", "b_b1, b_b2, r_b1, r_b2 = self.ttf_target( gt_bboxes, gt_labels, img_metas) loss_cls_b1, loss_bbox_b1 = self.loss_single(", "hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2, wh_head_conv_num=(2, 2), num_classes=81, shortcut_cfg=(1, 2, 3), wh_scale_factor_b1=16., wh_scale_factor_b2=16., alpha=0.54,", "w_radius + 1) top, bottom = min(y, h_radius), min(height - y, h_radius +", "= wh_weight_b2 self.b1_min_length = b1_min_length self.b2_max_length = b2_max_length self.level_base_area = level_base_area self.inf_branch =", "img, (num_gt, 4). gt_labels: tensor, tensor <=> img, (num_gt,). feat_shape: tuple. Returns: heatmap:", "self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1) for", "= nn.Sequential(*wh_layers) wh2_layers = nn.Sequential(*wh2_layers) hm_layers = nn.Sequential(*hm_layers) return wh_layers, wh2_layers, hm_layers def", "= [(ss - 1.) / 2. for ss in shape] y, x =", "- feat_gt_boxes[:, 1], feat_gt_boxes[:, 2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] +", "4). gt_labels: list(tensor). tensor <=> image, (gt_num,). img_metas: list(dict). Returns: heatmap: tensor, (batch,", "def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes, gt_labels, boxes_ind, feat_shape, down_ratio): output_h,", "& wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape =", "= torch.max(heatmap[cls_id], fake_heatmap) if self.alpha != self.beta: fake_heatmap = fake_heatmap.zero_() self.draw_truncate_gaussian(fake_heatmap, ct_ints[k], h_radiuses_beta[k].item(),", "80, h, w). wh: list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts =", "inds.size(1), wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter:", "= gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum() local_heatmap", "ys + wh[..., [3]] ], dim=2) return heat, inds, clses, scores, bboxes, xs,", "/ ct_div return heatmap, box_target, reg_weight def ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args:", "mask, avg_factor=avg_factor) * wh_weight_factor return loss_cls, loss_bbox @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def loss(self,", "= self.ttf_target_single_single( heatmap_b1, box_target_b1, reg_weight_b1, fake_heatmap_b1, boxes_area_topk_log[gt_b1_idx], gt_boxes[gt_b1_idx], gt_labels[gt_b1_idx], boxes_ind[gt_b1_idx], [output_h_b1, output_w_b1], self.down_ratio_b1)", "W) avg_factor = mask.sum() + 1e-4 loss_bbox = giou_loss( pred_boxes, boxes, mask, avg_factor=avg_factor)", "W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio shifts_x = torch.arange( 0, (W -", "= feat_shape heatmap_channel = self.num_fg heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1,", "layers.append(build_norm_layer(norm_cfg, out_channels)[1]) layers.append(nn.ReLU(inplace=True)) if not no_upsample: layers.append(nn.UpsamplingBilinear2d(scale_factor=2)) super(UpsamplingLayers, self).__init__(*layers) class ShortcutConnection(nn.Module): def __init__(self,", "scores[batch_i] wh_filter_per_img = wh_filter[batch_i] scores_keep = (scores_per_img > score_thr).squeeze(-1) & wh_filter_per_img scores_per_img =", "import ModulatedDeformConvPack, soft_nms from mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss", "[] score_thr = getattr(cfg, 'score_thr', 0.01) if 'b2' not in self.inf_branch: bboxes =", "* self.wh_scale_factor_b2 return hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0):", "1) if rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img =", "None self.base_loc_b2 = None self.fp16_enabled = False self._init_layers() def _init_branch_layers(self, planes): wh_layers, wh2_layers,", "bboxes = bboxes_b2 scores = scores_b2 clses = clses_b2 wh_filter = wh_filter_b2 else:", "= use_simple_nms self.focal_loss_beta = focal_loss_beta self.focal_b2_only = focal_b2_only self.shortcut_conv_cfg = shortcut_conv_cfg self.head_conv_cfg =", "area = (wh[..., 2] + wh[..., 0] + 1) * (wh[..., 3] +", "padding=pad) keep = (hmax == heat).float() out_heat = heat if out_heat is None", "None or H != getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step", "def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height, width = pred_hm.size()", "scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2,", "else out_heat return out_heat * keep def bbox_areas(self, bboxes, keep_axis=False): x_min, y_min, x_max,", "[1]], xs + wh[..., [2]], ys + wh[..., [3]] ], dim=2) return heat,", "inplanes=(64, 128, 256, 512), planes=(256, 128, 64), down_ratio_b1=8, down_ratio_b2=4, hm_head_channels=256, wh_head_channels=(64, 64), hm_head_conv_num=2,", "wh = wh.view(wh.size(0), -1, wh.size(3)) inds = inds.unsqueeze(2).expand(inds.size(0), inds.size(1), wh.size(2)) wh = wh.gather(1,", "out_heat=None): pad = (kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel,", "/ 2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta = (feat_hs / 2.", "heatmap_b1 = gt_boxes.new_zeros((heatmap_channel, output_h_b1, output_w_b1)) fake_heatmap_b1 = gt_boxes.new_zeros((output_h_b1, output_w_b1)) box_target_b1 = gt_boxes.new_ones((4, output_h_b1,", "= self._init_branch_layers(self.planes[-1]) def init_weights(self): for m in self.upsample_layers.modules(): if isinstance(m, nn.BatchNorm2d): constant_init(m, 1)", "* k, out=masked_heatmap) return heatmap def ttf_target_single_single(self, heatmap, box_target, reg_weight, fake_heatmap, boxes_area_topk_log, gt_boxes,", "= [], [], [] inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule(", "alpha=0.54, beta=0.54, hm_weight=1., wh_weight_b1=5., wh_weight_b2=5., b1_min_length=32, b2_max_length=64, level_base_area=True, inf_branch=['b1', 'b2'], use_simple_nms=True, focal_loss_beta=4, focal_b2_only=False,", "w). \"\"\" with torch.no_grad(): feat_shape = (img_metas[0]['pad_shape'][0] // self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0]", "from 80*topk topk_score, topk_ind = torch.topk(topk_scores.view(batch, -1), topk) topk_clses = (topk_ind / topk).int()", "wh_layers, wh2_layers, hm_layers def _init_layers(self): self.upsample_layers = nn.ModuleList([ UpsamplingLayers( self.inplanes[-1], self.planes[0], norm_cfg=self.norm_cfg), UpsamplingLayers(", "ct_focal_loss, giou_loss from mmdet.models.utils import ( build_conv_layer, build_norm_layer, bias_init_with_prob, ConvModule) from ..registry import", "labels_per_img.int() unique_cls_ids = list(set(list(labels_int_flatten.cpu().numpy()))) bboxes_per_img_per_cls = bboxes_per_img.new_zeros((0, 5)) labels_per_img_per_cls = labels_int_flatten.new_zeros((0,)) for cls_id", "result_list.append((bboxes_per_img, labels_per_img)) return result_list def loss_single(self, pred_hm, pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name,", "= torch.arange( 0, (H - 1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device)", "mdcn = ModulatedDeformConvPack( in_channels, out_channels, 3, stride=1, padding=1, dilation=1, deformable_groups=1) layers = []", "wh.size(2)) wh = wh.gather(1, inds) wh_filter = wh.new_ones((batch, topk), dtype=torch.bool) if self.inf_branch_filter: area", "enumerate(kernel_sizes): inc = in_channels if i == 0 else out_channels padding = (kernel_size", "norm_cfg=self.norm_cfg), UpsamplingLayers( self.planes[1], self.planes[2], norm_cfg=self.norm_cfg) ]) self.shortcut_layers = nn.ModuleList() for (inp, outp, layer_num)", "* w_radius + 1 sigma_x = w / 6 sigma_y = h /", "1 sigma_x = w / 6 sigma_y = h / 6 gaussian =", "= gt_boxes[boxes_ind] gt_labels = gt_labels[boxes_ind] if self.level_base_area: gt_b1_idx = boxes_area_topk_log >= math.log(self.b1_min_length **", "sigma_x = w / 6 sigma_y = h / 6 gaussian = self.gaussian_2d((h,", "rescale: scale_factor = img_metas[batch_i]['scale_factor'] bboxes_per_img /= bboxes_per_img.new_tensor(scale_factor) if self.use_simple_nms: bboxes_per_img = torch.cat([bboxes_per_img, scores_per_img],", "base_loc_name) - pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2,", "output_h_b1, output_w_b1)) heatmap_b2 = gt_boxes.new_zeros((heatmap_channel, output_h_b2, output_w_b2)) fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 =", "super(ShortcutConnection, self).__init__() layers = [] for i, kernel_size in enumerate(kernel_sizes): inc = in_channels", "1, base_step, dtype=torch.float32, device=heatmap.device) shift_y, shift_x = torch.meshgrid(shifts_y, shifts_x) setattr(self, base_loc_name, torch.stack((shift_x, shift_y),", "w_radiuses_alpha = (feat_ws / 2. * self.alpha).int() if self.alpha != self.beta: h_radiuses_beta =", "bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2,", "* -1 reg_weight_b2 = gt_boxes.new_zeros((1, output_h_b2, output_w_b2)) boxes_areas_log = self.bbox_areas(gt_boxes).log() boxes_area_topk_log, boxes_ind =", "max=img_shape[1] - 1) bboxes_per_img[:, 1::2] = bboxes_per_img[:, 1::2].clamp( min=0, max=img_shape[0] - 1) if", "isinstance(m, ModulatedDeformConvPack): constant_init(m.conv_offset, 0) def forward(self, feats): \"\"\" Args: feats: list(tensor). Returns: hm:", "2], dim=1) / down_ratio).to(torch.int) h_radiuses_alpha = (feat_hs / 2. * self.alpha).int() w_radiuses_alpha =", "clses, scores, bboxes, xs, ys, wh_filter @force_fp32(apply_to=('pred_hm_b1', 'pred_hm_b2', 'pred_wh_b1', 'pred_wh_b2')) def get_bboxes(self, pred_hm,", "padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes) - 1:", "pred_wh[:, [0, 1]], getattr(self, base_loc_name) + pred_wh[:, [2, 3]]), dim=1).permute(0, 2, 3, 1)", "i == 0 else out_channels padding = (kernel_size - 1) // 2 if", "fake_heatmap_b2 = gt_boxes.new_zeros((output_h_b2, output_w_b2)) box_target_b2 = gt_boxes.new_ones((4, output_h_b2, output_w_b2)) * -1 reg_weight_b2 =", "self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2 = wh_scale_factor_b2 self.alpha = alpha self.beta", "the max score heat = self.simple_nms(pred_hm) # (batch, topk) scores, inds, clses, ys,", "heatmap, beta=focal_loss_beta) * hm_weight_factor if getattr(self, base_loc_name) is None or H != getattr(self,", "# used maxpool to filter the max score heat = self.simple_nms(pred_hm) # (batch,", "h_radius, w_radius, k=1): h, w = 2 * h_radius + 1, 2 *", "out_channels, kernel_size, padding=padding)) else: layers.append( nn.Conv2d(inc, out_channels, kernel_size, padding=padding)) if i < len(kernel_sizes)", "== 1: wh_filter = area <= self.b2_max_length ** 2 * 2 wh =", "layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x) @HEADS.register_module class TTFLevelHead(AnchorHead): def", "w / 6 sigma_y = h / 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x,", "> score_thr).squeeze(-1) & wh_filter_per_img scores_per_img = scores_per_img[scores_keep] bboxes_per_img = bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1)", "(batch, topk) scores, inds, clses, ys, xs = self._topk(heat, topk=topk) xs = xs.view(batch,", "padding=1 ) ) else: wh2_layers.append(nn.Conv2d(self.wh_head_channels[1], 4, 3, padding=1)) inp = planes for i", "wh: list(tensor), (batch, 4, h, w). \"\"\" y, shortcuts = [], [] x", "2] - feat_gt_boxes[:, 0]) ct_ints = (torch.stack([(gt_boxes[:, 0] + gt_boxes[:, 2]) / 2,", "[], [] inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0],", "self.down_ratio_b1, img_metas[0]['pad_shape'][1] // self.down_ratio_b1, img_metas[0]['pad_shape'][0] // self.down_ratio_b2, img_metas[0]['pad_shape'][1] // self.down_ratio_b2) h_b1, h_b2, b_b1,", "output_w_b1], self.down_ratio_b1) heatmap_b2, box_target_b2, reg_weight_b2 = self.ttf_target_single_single( heatmap_b2, box_target_b2, reg_weight_b2, fake_heatmap_b2, boxes_area_topk_log[gt_b2_idx], gt_boxes[gt_b2_idx],", "pred_wh, heatmap, box_target, wh_weight, down_ratio, base_loc_name, hm_weight_factor, wh_weight_factor, focal_loss_beta): H, W = pred_hm.shape[2:]", "\\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1, topk, idx=0) heat_b2, inds_b2, clses_b2, scores_b2, bboxes_b2, xs_b2, ys_b2,", "(kernel - 1) // 2 hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad)", "1) * base_step + 1, base_step, dtype=torch.float32, device=heatmap.device) shifts_y = torch.arange( 0, (H", "'pred_wh_b1', 'pred_wh_b2')) def loss(self, pred_hm_b1, pred_hm_b2, pred_wh_b1, pred_wh_b2, gt_bboxes, gt_labels, img_metas, cfg, gt_bboxes_ignore=None):", "box_target_inds] = gt_boxes[k][:, None] cls_id = 0 local_heatmap = fake_heatmap[box_target_inds] ct_div = local_heatmap.sum()", "H != getattr(self, base_loc_name).shape[ 1] or W != getattr(self, base_loc_name).shape[2]: base_step = down_ratio", "num_classes self.num_fg = num_classes - 1 self.shortcut_cfg = shortcut_cfg self.wh_scale_factor_b1 = wh_scale_factor_b1 self.wh_scale_factor_b2", "1).float() scores = scores.view(batch, topk, 1) bboxes = torch.cat([ xs - wh[..., [0]],", "output_w = feat_shape feat_gt_boxes = gt_boxes / down_ratio feat_gt_boxes[:, [0, 2]] = torch.clamp(", "torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import normal_init,", "heat_b1, inds_b1, clses_b1, scores_b1, bboxes_b1, xs_b1, ys_b1, wh_filter_b1 = \\ self.get_bboxes_single(pred_hm_b1, pred_wh_b1, self.down_ratio_b1,", "= bboxes[batch_i][scores_keep] labels_per_img = clses[batch_i][scores_keep].squeeze(-1) img_shape = img_metas[batch_i]['pad_shape'] bboxes_per_img[:, 0::2] = bboxes_per_img[:, 0::2].clamp(", "hmax = nn.functional.max_pool2d( heat, (kernel, kernel), stride=1, padding=pad) keep = (hmax == heat).float()", "mmdet.core import multi_apply, force_fp32 from mmdet.models.losses import ct_focal_loss, giou_loss from mmdet.models.utils import (", "= [], [] x = feats[-1] for i, shortcut_layer in enumerate(self.shortcut_layers): shortcuts.append(shortcut_layer(feats[-i -", "hm, wh_b1, wh_b2 def get_bboxes_single(self, pred_hm, pred_wh, down_ratio, topk, idx=0): batch, cat, height,", "conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg: wh_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[0], 4, kernel_size=3, padding=1", "< len(kernel_sizes) - 1: layers.append(nn.ReLU(inplace=True)) self.layers = nn.Sequential(*layers) def forward(self, x): return self.layers(x)", "ttf_target_single(self, gt_boxes, gt_labels, feat_shape): \"\"\" Args: gt_boxes: tensor, tensor <=> img, (num_gt, 4).", "[] inp = planes for i in range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3,", "/ 6 gaussian = self.gaussian_2d((h, w), sigma_x=sigma_x, sigma_y=sigma_y) gaussian = heatmap.new_tensor(gaussian) x, y", "range(self.wh_head_conv_num[0]): wh_layers.append( ConvModule( inp, self.wh_head_channels[0], 3, padding=1, conv_cfg=self.conv_cfg)) inp = self.wh_head_channels[0] if self.head_conv_cfg:", "scores.view(batch, topk, 1) bboxes = torch.cat([ xs - wh[..., [0]], ys - wh[...,", "= self.wh_head_channels[1] if self.head_conv_cfg: wh2_layers.append( build_conv_layer( self.head_conv_cfg, self.wh_head_channels[1], 4, kernel_size=3, padding=1 ) )", "max=output_w - 1) feat_gt_boxes[:, [1, 3]] = torch.clamp( feat_gt_boxes[:, [1, 3]], min=0, max=output_h" ]