file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
api_views.py | import logging
from django.db.models.query_utils import Q
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg import openapi
from drf_yasg.openapi import Parameter
from drf_yasg.utils import no_body, swagger_auto_schema
from notifications.signals import notify
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.decorators import parser_classes as dparser_classes
from rest_framework.parsers import FormParser, JSONParser, MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework_extensions.mixins import DetailSerializerMixin, NestedViewSetMixin
from looking_for_group.mixins import AutoPermissionViewSetMixin, ParentObjectAutoPermissionViewSetMixin
from . import models, serializers
from .signals import player_kicked, player_left
logger = logging.getLogger("api")
parent_lookup_game__slug = Parameter(
name="parent_lookup_game__slug",
in_="path",
type="string",
format=openapi.FORMAT_SLUG,
description="Slug of related game object.",
)
parent_lookup_session__slug = Parameter(
name="parent_lookup_session__slug",
in_="path",
type="string",
format=openapi.FORMAT_SLUG,
description="Slug of related session object.",
)
parent_lookup_session__game__slug = Parameter(
name="parent_lookup_session__game__slug",
in_="path",
type="string",
format=openapi.FORMAT_SLUG,
description="Slug of related game object.",
)
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="List Games",
operation_description="Fetch a list of game records. **NOTE**: You will probably want to filter by status at least.",
),
)
@method_decorator(
name="create",
decorator=swagger_auto_schema(
operation_summary="Game: Create",
operation_description="Create a new game posting.",
request_body=serializers.GameDataSerializer,
responses={201: serializers.GameDataSerializer},
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Game: Details",
operation_description="Fetch the details for the given game. **NOTE**: If you are not a member of the game, only a subset of the available information will be displayed.",
responses={
200: serializers.GameDataSerializer,
403: "You are not authorized to view this game.",
},
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Game: Update",
operation_description="Update the details of this game. (Only available to GM)",
request_body=serializers.GameDataSerializer,
responses={
200: serializers.GameDataSerializer,
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Game: Update",
operation_description="Update the details of this game. (Only available to GM)",
request_body=serializers.GameDataSerializer,
responses={
200: serializers.GameDataSerializer,
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Game: Delete",
operation_description="Delete the given game. (Only available to GM.)",
request_body=no_body,
responses={204: "Game was deleted.", 403: "You are not the GM of this game."},
),
)
@method_decorator(
name="leave",
decorator=swagger_auto_schema(
operation_summary="Game: Leave",
operation_description="Leave the current game. (Players only.)",
request_body=no_body,
reponses={
204: "You have successfully left the game.",
400: "You are not a member of this game.",
403: "You are the GM and cannot leave.",
},
),
)
@method_decorator(
name="apply",
decorator=swagger_auto_schema(
operation_summary="Game: Apply",
operation_description="Apply to join this game.",
request_body=serializers.GameApplicationSerializer,
responses={
201: serializers.GameApplicationSerializer,
400: "You are already a member of this game.",
403: "You are not permitted to apply to this game either due to your access rights or the game's status.",
},
),
)
class GamePostingViewSet(
AutoPermissionViewSetMixin,
DetailSerializerMixin,
NestedViewSetMixin,
viewsets.ModelViewSet,
):
"""
A view set that allows the retrieval and manipulation of posted game data.
"""
permission_classes = (IsAuthenticated,)
parser_classes = [FormParser, MultiPartParser]
model = models.GamePosting
lookup_field = "slug"
lookup_url_kwarg = "slug"
serializer_class = serializers.GameDataListSerializer
serializer_detail_class = serializers.GameDataSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = [
"published_game",
"game_system",
"published_module",
"status",
"game_type",
"game_mode",
]
permission_type_map = {
**AutoPermissionViewSetMixin.permission_type_map,
"apply": "apply",
"leave": "leave",
}
def get_queryset(self):
gamer = self.request.user.gamerprofile
friends = gamer.friends.all()
communities = [f.id for f in gamer.communities.all()]
game_player_ids = [
obj.game.id
for obj in models.Player.objects.filter(gamer=gamer).select_related("game")
]
q_gm = Q(gm=gamer)
q_gm_is_friend = Q(gm__in=friends) & Q(privacy_level="community")
q_isplayer = Q(id__in=game_player_ids)
q_community = Q(communities__id__in=communities) & Q(privacy_level="community")
q_public = Q(privacy_level="public")
qs = models.GamePosting.objects.filter(
q_gm | q_public | q_gm_is_friend | q_isplayer | q_community
).distinct()
return qs
def create(self, request, *args, **kwargs):
self.serializer_class = serializers.GameDataSerializer
return super().create(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
if not request.user.has_perm("game.is_member", self.get_object()):
logger.debug(
"User is not a member of game, swtiching serializer to list view mode."
)
self.serializer_detail_class = serializers.GameDataListSerializer
return super().retrieve(request, *args, **kwargs)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def apply(self, request, *args, **kwargs):
obj = self.get_object()
logger.debug("Retrieved game object of {}".format(obj))
if request.user.has_perm("game.is_member", obj):
return Response(
data={"errors": "You are already in this game..."},
status=status.HTTP_400_BAD_REQUEST,
)
new_application = serializers.GameApplicationSerializer(
data=request.data, context={"request": request}
)
if not new_application.is_valid():
return Response(
data=new_application.errors, status=status.HTTP_400_BAD_REQUEST
)
app = models.GamePostingApplication.objects.create(
game=obj,
gamer=request.user.gamerprofile,
message=new_application.validated_data["message"],
status="pending",
)
notify.send(
request.user.gamerprofile,
recipient=obj.gm.user,
verb="submitted application",
action_object=app,
target=obj,
)
return Response(
data=serializers.GameApplicationSerializer(
app, context={"request": request}
).data,
status=status.HTTP_201_CREATED,
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def leave(self, request, *args, **kwargs):
obj = self.get_object()
if request.user == obj.gm.user:
return Response(
data={"errors": "The GM cannot leave the game."},
status=status.HTTP_400_BAD_REQUEST,
)
player = models.Player.objects.get(gamer=request.user.gamerprofile, game=obj)
player_left.send(models.Player, player=player)
player.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="Game: List Sessions",
operation_description="List the sessions for the given game.",
manual_parameters=[parent_lookup_game__slug],
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Game Session: Details",
operation_description="Get the details for the given session. **NOTE**: If the user is just a player, the GM notes and player details will not be included.",
manual_parameters=[parent_lookup_game__slug],
responses={
200: serializers.GameSessionGMSerializer,
403: "You are not a member of this game.",
},
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Game Session: Update",
operation_description="Update details of the game session.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.GameSessionGMSerializer,
responses={
200: serializers.GameSessionGMSerializer,
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Game Session: Update",
operation_description="Update details of the game session.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.GameSessionGMSerializer,
responses={
200: serializers.GameSessionGMSerializer,
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Game Session: Delete",
operation_description="Delete the game session.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.GameSessionGMSerializer,
responses={
204: "Session was deleted.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="cancel",
decorator=swagger_auto_schema(
operation_summary="Game Session: Cancel",
operation_description="Cancel the game session.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.GameSessionGMSerializer,
400: "This session is already canceled or complete.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="uncancel",
decorator=swagger_auto_schema(
operation_summary="Game Session: Uncancel",
operation_description="Uncancel the game session.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.GameSessionGMSerializer,
400: "This session is not canceled.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="complete",
decorator=swagger_auto_schema(
operation_summary="Game Session: Mark Complete",
operation_description="Mark the game session as complete.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.GameSessionGMSerializer,
400: "This session is already canceled or complete.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="uncomplete",
decorator=swagger_auto_schema(
operation_summary="Game Session: Uncomplete",
operation_description="Undo the completion status of the session.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.GameSessionGMSerializer,
400: "This session isn't marked as complete.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="reschedule",
decorator=swagger_auto_schema(
operation_summary="Game Session: Reschedule",
operation_description="Reschedule the game session to another date/time.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.ScheduleSerializer,
responses={
200: serializers.GameSessionGMSerializer,
400: "Your date and time were invalid or the session is already marked as complete or canceled.",
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="addlog",
decorator=swagger_auto_schema(
operation_summary="Game Session: Add Adventure Log",
operation_description="Add an adventure log to this session.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.AdventureLogSerializer,
responses={
201: serializers.AdventureLogSerializer,
400: "This session already has an adventure log. You should update that instead.",
403: "You don't have permission to add an adventure log.",
},
),
)
class GameSessionViewSet(
ParentObjectAutoPermissionViewSetMixin,
NestedViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
Views for seeing game session data.
"""
model = models.GameSession
serializer_class = serializers.GameSessionSerializer
lookup_field = "slug"
lookup_url_kwarg = "slug"
parent_dependent_actions = [
"create",
"retrieve",
"update",
"partial_update",
"list",
"destroy",
"reschedule",
"cancel",
"uncancel",
"addlog",
"complete",
"uncomplete",
]
parent_lookup_field = "game"
parent_object_model = models.GamePosting
parent_object_lookup_field = "slug"
parent_object_url_kwarg = "parent_lookup_game__slug"
permission_type_map = {
**ParentObjectAutoPermissionViewSetMixin.permission_type_map,
"addlog": "view",
"reschedule": "change",
"cancel": "change",
"uncancel": "change",
"complete": "change",
"uncomplete": "change",
}
permission_type_map["list"] = "view"
def get_parent_game(self):
return get_object_or_404(
models.GamePosting, slug=self.kwargs["parent_lookup_game__slug"]
)
def get_queryset(self):
return self.model.objects.filter(
game__slug=self.kwargs["parent_lookup_game__slug"]
).order_by("-scheduled_time")
def dispatch(self, request, *args, **kwargs):
if (
request.user.is_authenticated
and request.user.gamerprofile == self.get_parent_game().gm
):
self.serializer_class = serializers.GameSessionGMSerializer
return super().dispatch(request, *args, **kwargs)
@action(methods=["post"], detail=True)
def reschedule(self, request, *args, **kwargs):
date_serializer = serializers.ScheduleSerializer(data=request.data)
if not date_serializer.is_valid():
return Response(
data=date_serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
obj = self.get_object()
if obj.status in ["complete", "cancel"]:
return Response(
data={
"errors": "This session is already marked as {} and cannot be rescheduled.".format(
obj.get_status_display()
)
},
status=status.HTTP_400_BAD_REQUEST,
)
obj.move(date_serializer.validated_data["new_scheduled_time"])
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True)
def complete(self, request, *args, **kwargs):
obj = self.get_object()
if obj.status in ["complete", "cancel"]:
return Response(
data={
"errors": "This object is either already completed or canceled and cannot be toggled to complete."
},
status=status.HTTP_400_BAD_REQUEST,
)
obj.status = "complete"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True)
def uncomplete(self, request, *args, **kwargs):
obj = self.get_object()
if obj.status != "complete":
return Response(
data={
"errors": "This object is not completed and so completion cannot be undone."
},
status=status.HTTP_400_BAD_REQUEST,
)
obj.status = "pending"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True)
def cancel(self, request, *args, **kwargs):
obj = self.get_object()
if obj.status in ["complete", "cancel"]:
return Response(
data={"errors": "This session is already completed or canceled."},
status=status.HTTP_400_BAD_REQUEST,
)
obj.cancel()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True)
def uncancel(self, request, *args, **kwargs):
obj = self.get_object()
if obj.status != "cancel":
return Response(
data={
"errors": "This session is not canceled and can't be changed this way."
},
status=status.HTTP_400_BAD_REQUEST,
)
obj.uncancel()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True)
def addlog(self, request, *args, **kwargs):
"""
Create the adventure log for this session.
"""
session = self.get_object()
if hasattr(session, "adventurelog"):
return Response(
data={"errors": "This session already has an adventure log."},
status=status.HTTP_400_BAD_REQUEST,
)
log_serializer = serializers.AdventureLogSerializer(
session=session, data=request.data, context={"request": request}
)
if not log_serializer.is_valid():
return Response(
data=log_serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
new_log = log_serializer.save()
return Response(
data=serializers.AdventureLogSerializer(
new_log, context={"request": request}
).data,
status=status.HTTP_201_CREATED,
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Adventure Log: Details",
operation_description="Fetch the details for a given adventure log.",
manual_parameters=[
parent_lookup_session__game__slug,
parent_lookup_session__slug,
],
responses={
200: serializers.AdventureLogSerializer,
403: "You are not a member of this game.",
},
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Adventure Log: Update",
operation_description="Update the details for a given adventure log.",
manual_parameters=[
parent_lookup_session__game__slug,
parent_lookup_session__slug,
],
request_body=serializers.AdventureLogSerializer,
responses={
200: serializers.AdventureLogSerializer,
403: "You don't have permissions to edit this adventure log.",
},
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Adventure Log: Update",
operation_description="Update the details for a given adventure log.",
manual_parameters=[
parent_lookup_session__game__slug,
parent_lookup_session__slug,
],
request_body=serializers.AdventureLogSerializer,
responses={
200: serializers.AdventureLogSerializer,
403: "You don't have permissions to edit this adventure log.",
},
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Adventure Log: Delete",
operation_description="Delete a given adventure log.",
manual_parameters=[
parent_lookup_session__game__slug,
parent_lookup_session__slug,
],
request_body=no_body,
responses={
204: "The adventure log was successfully deleted.",
403: "You don't have permissions to edit this adventure log.",
},
),
)
class AdventureLogViewSet(
ParentObjectAutoPermissionViewSetMixin,
NestedViewSetMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
Allows the manipulation of view sets.
"""
model = models.AdventureLog
parent_lookup_field = "session__game"
parent_object_model = models.GamePosting
parent_object_lookup_field = "slug"
parent_object_url_kwarg = "parent_lookup_session__game__slug"
serializer_class = serializers.AdventureLogSerializer
lookup_field = "slug"
lookup_url_kwarg = "slug"
permission_required = "game.is_member"
permission_type_map = {**ParentObjectAutoPermissionViewSetMixin.permission_type_map}
permission_type_map["list"] = "add"
parent_dependent_actions = [
"create",
"retrieve",
"update",
"partial_update",
"destroy",
]
def get_queryset(self):
return models.AdventureLog.objects.filter(
session__slug=self.kwargs["parent_lookup_session__slug"]
)
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="List Your Game Applications",
operation_description="Fetch a list of all your game applications.",
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Your Game Application: Details",
operation_description="Fetch the details of your game application.",
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Your Game Application: Update",
operation_description="Update the details of your game application.",
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Your Game Application: Update",
operation_description="Update the details of your game application.",
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Your Game Application: Withdraw",
operation_description="Withdraw your game application by deleting the record.",
),
)
class GameApplicationViewSet(
AutoPermissionViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
View for an applicant to review, create, update, and delete their applications to games.
"""
permission_classes = (IsAuthenticated,)
serializer_class = serializers.GameApplicationSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ["status"]
lookup_field = "slug"
lookup_url_kwarg = "slug"
permission_type_map = {**AutoPermissionViewSetMixin.permission_type_map}
def get_queryset(self):
logger.debug("Fetching gamerprofile from request...")
gamer = self.request.user.gamerprofile
logger.debug("Fetching game applications for gamer {}".format(gamer))
qs = models.GamePostingApplication.objects.filter(
gamer=self.request.user.gamerprofile
).order_by("-modified", "-created", "status")
logger.debug(
"Retrieved queryset of length {} for gamer {}".format(
qs.count(), self.request.user.gamerprofile
)
)
return qs
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="List Applicants for Game",
operation_description="List the applicants for the current game. (GM Only)",
manual_parameters=[parent_lookup_game__slug],
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Game Applicant: Details",
operation_description="Fetch details for a given game application. (GM Only)",
manual_parameters=[parent_lookup_game__slug],
reponses={
200: serializers.GameApplicationGMSerializer,
403: "You are not the GM for this game.",
},
),
)
@method_decorator(
name="approve",
decorator=swagger_auto_schema(
operation_summary="Game Applicant: Approve",
operation_description="Approve the game applicant and add as a player to game.",
request_body=no_body,
responses={
201: serializers.PlayerSerializer,
403: "You are not the GM of this game.",
},
),
)
@method_decorator(
name="reject",
decorator=swagger_auto_schema(
operation_summary="Game Applicant: Reject",
operation_description="Reject the game applicant.",
request_body=no_body,
responses={
200: serializers.GameApplicationGMSerializer,
403: "You are not the GM of this game.",
},
),
)
class GMGameApplicationViewSet(
ParentObjectAutoPermissionViewSetMixin,
NestedViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet,
):
"""
View for a GM to review and approve applicants.
"""
permission_classes = (IsAuthenticated,)
serializer_class = serializers.GameApplicationGMSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ["status"]
lookup_field = "slug"
lookup_url_kwarg = "slug"
parent_lookup_field = "game"
parent_object_lookup_field = "slug"
parent_object_model = models.GamePosting
parent_object_url_kwarg = "parent_lookup_game__slug"
parent_dependent_actions = ["list", "retrieve", "approve", "reject"]
permission_type_map = {
**ParentObjectAutoPermissionViewSetMixin.permission_type_map,
"approve": "approve",
"reject": "approve",
}
permission_type_map["retrieve"] = "approve"
permission_type_map["list"] = "approve"
def get_queryset(self):
return models.GamePostingApplication.objects.filter(
game__slug=self.kwargs["parent_lookup_game__slug"]
).exclude(status="new")
def get_parent_game(self):
return get_object_or_404(
models.GamePosting, slug=self.kwargs["parent_lookup_game__slug"]
)
@action(methods=["post"], detail=True)
def approve(self, request, *args, **kwargs):
"""
Approves the game application.
"""
obj = self.get_object()
obj.status = "approve"
player = models.Player.objects.create(game=obj.game, gamer=obj.gamer)
obj.save()
return Response(
data=serializers.PlayerSerializer(
player, context={"request", request}
).data,
status=status.HTTP_201_CREATED,
)
@action(methods=["post"], detail=True)
def reject(self, request, *args, **kwargs):
"""
Rejects the game application.
"""
obj = self.get_object()
obj.status = "deny"
obj.save()
notify.send(
obj,
recipient=obj.gamer.user,
verb="Your player application was not accepted",
action_object=obj,
target=obj.game,
)
return Response(
data=serializers.GameApplicationSerializer(
obj, context={"request": request}
).data,
status=status.HTTP_200_OK,
)
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="Game: Player List",
operation_description="List players for a given game",
manual_parameters=[parent_lookup_game__slug],
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Player: Details",
operation_description="Details for a player record in a given game.",
manual_parameters=[parent_lookup_game__slug],
responses={
200: serializers.PlayerSerializer,
403: "You are not a member of this game.",
},
),
)
@method_decorator(
name="kick",
decorator=swagger_auto_schema(
operation_summary="Player: Kick from game",
operation_description="Kick the player out of the game.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
204: "Player was removed from the game.",
403: "You are not the GM of this game.",
},
),
)
class PlayerViewSet(
ParentObjectAutoPermissionViewSetMixin,
NestedViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet,
):
"""
Provides views for players in a given game.
"""
permission_classes = (IsAuthenticated,)
serializer_class = serializers.PlayerSerializer
permission_required = "game.is_member"
lookup_field = "slug"
lookup_url_kwarg = "slug"
parent_lookup_field = "game"
parent_object_model = models.GamePosting
parent_object_lookup_field = "slug"
parent_object_url_kwarg = "parent_lookup_game__slug"
parent_dependent_actions = ["list", "retrieve"]
permission_type_map = {**ParentObjectAutoPermissionViewSetMixin.permission_type_map}
permission_type_map["list"] = "view"
def get_parent_game(self):
return get_object_or_404(
models.GamePosting, slug=self.kwargs["parent_lookup_game__slug"]
)
def get_queryset(self):
return models.Player.objects.filter(game=self.get_parent_game())
@action(methods=["post"], detail=True)
def kick(self, request, *args, **kwargs):
obj = self.get_object()
player_kicked.send(request.user, player=obj)
obj.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
@method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="Game: List Characters",
operation_description="Fetch the list of characters for a given game.",
manual_parameters=[parent_lookup_game__slug],
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Game: Character Details",
operation_description="Fetch the details of a character for a given game.",
manual_parameters=[parent_lookup_game__slug],
responses={
200: serializers.CharacterSerializer,
403: "You are not a member of this game.",
},
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Game: Update Character Details",
operation_description="Update the character for the given game.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.CharacterSerializer,
responses={
200: serializers.CharacterSerializer,
403: "You are not the owner of this character or the GM of the game.",
},
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Game: Update Character Details",
operation_description="Update the character for the given game.",
manual_parameters=[parent_lookup_game__slug],
request_body=serializers.CharacterSerializer,
responses={
200: serializers.CharacterSerializer,
403: "You are not the owner of this character or the GM of the game.",
},
),
)
@method_decorator(
name="deactivate",
decorator=swagger_auto_schema(
operation_summary="Game: Deactivate Character",
operation_description="Mark the character as inactive.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.CharacterSerializer,
400: "This character is already inactive.",
403: "You are not the owner of this character or the GM of the game.",
},
),
)
@method_decorator(
name="reactivate",
decorator=swagger_auto_schema(
operation_summary="Game: Reactivate Character",
operation_description="Mark the character as active.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.CharacterSerializer,
400: "This character is already active.",
403: "You are not the owner of this character or the GM of the game.",
},
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Game: Delete Character",
operation_description="Delete the character.",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
204: "Character was deleted.",
403: "You are not the owner of this character.",
},
),
)
@method_decorator(
name="approve",
decorator=swagger_auto_schema(
operation_summary="Game: Approve Character",
operation_description="Mark the character as approved (GM Only).",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.CharacterSerializer,
400: "This character is already approved.",
403: "You are not the GM of the game.",
},
),
)
@method_decorator(
name="reject",
decorator=swagger_auto_schema(
operation_summary="Game: Reject Character",
operation_description="Mark the character as rejected (GM Only).",
manual_parameters=[parent_lookup_game__slug],
request_body=no_body,
responses={
200: serializers.CharacterSerializer,
400: "This character is already rejected.",
403: "You are not the GM of the game.",
},
),
)
class CharacterViewSet(
ParentObjectAutoPermissionViewSetMixin, NestedViewSetMixin, viewsets.ModelViewSet
):
"""
Provides views for the characters in a game.
"""
permission_classes = (IsAuthenticated,)
parser_classes = [FormParser, MultiPartParser]
parent_object_lookup_field = "slug"
parent_object_url_kwarg = "parent_lookup_game__slug"
parent_lookup_field = "game"
parent_object_model = models.GamePosting
parent_dependent_actions = ["create", "list", "retrieve"]
serializer_class = serializers.CharacterSerializer
lookup_field = "slug"
lookup_url_kwarg = "slug"
filter_backends = [DjangoFilterBackend]
filterset_fields = ["status"]
parent_game = None
permission_type_map = {
**ParentObjectAutoPermissionViewSetMixin.permission_type_map,
"approve": "approve",
"reject": "approve",
"deactivate": "delete",
"reactivate": "delete",
}
permission_type_map["list"] = "gamelist"
def get_parent_game(self):
if not self.parent_game:
self.parent_game = get_object_or_404(
models.GamePosting, slug=self.kwargs["parent_lookup_game__slug"]
)
return self.parent_game
def get_queryset(self):
return models.Character.objects.filter(game=self.get_parent_game())
def create(self, request, *args, **kwargs):
if request.user.gamerprofile == self.get_parent_game().gm:
return Response(
data={"errors": "Only a player can create a character."},
status=status.HTTP_403_FORBIDDEN,
)
char_ser = serializers.CharacterSerializer(
data=request.data,
context={"request": request, "game": self.get_parent_game()},
)
if not char_ser.is_valid():
return Response(data=char_ser.errors, status=status.HTTP_400_BAD_REQUEST)
char_ser.save()
return Response(data=char_ser.data, status=status.HTTP_201_CREATED)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def approve(self, request, *args, **kwargs):
"""
Approves the proposed character.
"""
obj = self.get_object()
obj.status = "approved"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def reject(self, request, *args, **kwargs):
"""
Rejects the proposed character.
"""
obj = self.get_object()
obj.status = "rejected"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def deactivate(self, request, *args, **kwargs):
"""
Make a character inactive.
"""
obj = self.get_object()
obj.status = "inactive"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def reactivate(self, request, *args, **kwargs):
"""
Reactivate an inactive character.
"""
obj = self.get_object()
obj.status = "pending"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
| @method_decorator(
name="list",
decorator=swagger_auto_schema(
operation_summary="List Your Characters",
operation_description="Fetch a list of all of your characters.",
),
)
@method_decorator(
name="retrieve",
decorator=swagger_auto_schema(
operation_summary="Your Character: Details",
operation_description="Fetch the details of your character.",
),
)
@method_decorator(
name="update",
decorator=swagger_auto_schema(
operation_summary="Your Character: Update",
operation_description="Update the details of your character.",
),
)
@method_decorator(
name="partial_update",
decorator=swagger_auto_schema(
operation_summary="Your Character: Update",
operation_description="Update the details of your character.",
),
)
@method_decorator(
name="destroy",
decorator=swagger_auto_schema(
operation_summary="Your Character: Delete",
operation_description="Delete your character.",
request_body=no_body,
responses={204: "Character was deleted."},
),
)
@method_decorator(
name="deactivate",
decorator=swagger_auto_schema(
operation_summary="Your Character: Deactivate",
operation_description="Mark your character as inactive.",
request_body=no_body,
responses={
200: "Character was marked as inactive.",
400: "Character was already inactive.",
},
),
)
@method_decorator(
name="reactivate",
decorator=swagger_auto_schema(
operation_summary="Your Character: Reactivate",
operation_description="Mark your character as active.",
request_body=no_body,
responses={
200: "Character was marked as active.",
400: "Character was already active.",
},
),
)
class MyCharacterViewSet(
AutoPermissionViewSetMixin,
NestedViewSetMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
Provides a vew so that players can view all their characters in one place.
"""
serializer_class = serializers.CharacterSerializer
permission_classes = (IsAuthenticated,)
lookup_field = "slug"
lookup_url_kwarg = "slug"
filter_backends = [DjangoFilterBackend]
filterset_fields = ["status"]
permission_type_map = {
**AutoPermissionViewSetMixin.permission_type_map,
"deactivate": "delete",
"reactivate": "delete",
}
permission_type_map["retrieve"] = "delete"
parser_classes = [FormParser, MultiPartParser]
def get_queryset(self):
return models.Character.objects.filter(
player__gamer=self.request.user.gamerprofile
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def deactivate(self, request, *args, **kwargs):
"""
Make a character inactive.
"""
obj = self.get_object()
obj.status = "inactive"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@action(methods=["post"], detail=True, parser_classes=[FormParser, JSONParser])
def reactivate(self, request, *args, **kwargs):
"""
Reactivate an inactive character.
"""
obj = self.get_object()
obj.status = "pending"
obj.save()
return Response(
data=self.serializer_class(obj, context={"request": request}).data,
status=status.HTTP_200_OK,
)
@dparser_classes([FormParser, JSONParser])
def destroy(self, request, *args, **kwargs):
self.parser_classes = [FormParser, JSONParser]
return super().destroy(request, *args, **kwargs) | |
user.js | const MachineOptions = require('./machine');
const inquirer = require('inquirer');
const options = require('../../data');
class User extends MachineOptions{
constructor({opt, name, selected}){
super({opt});
this._name = name;
this._selected = selected;
this._sort = this.sort()
}
set name(string){
this._name = string
}
get name(){ | this._selected = string
}
get selected(){
return this._selected
}
logic(){
if (this._selected === this._sort) {
return `${this._name}, O resultado é -> você empatou!!!`
} else if ((this._selected === 'Pedra' && this._sort === 'Tesoura') || (this._selected === 'Tesoura' && this._sort === 'Papel') || (this._selected === 'Papel' && this._sort === 'Pedra')) {
return `${this._name}, A máquina escolheu ${this._sort}. Você escolheu: ${this._selected} - O resultado é -> Você ganhou!!`
} else {
return `${this._name}, A máquina escolheu ${this._sort}. Você escolheu: ${this._selected} - O resultado é -> Você perdeu!!`
}
}
game(){
return inquirer
.prompt([
{
name: 'name',
message: 'Qual o seu nome? ',
default: 'Jogador'
},
{
type: 'list',
name: 'jokenpo',
message: 'Selecione uma destas opções ',
choices: options
}
]).then((answers) => {
this._name = answers.name
this._selected = answers.jokenpo
console.info(`${this.logic()}`)
})
}
}
module.exports = User | return this._name
}
set selected(string){ |
TagResourceCommand.ts | // smithy-typescript generated code
import { getSerdePlugin } from "@aws-sdk/middleware-serde";
import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http";
import { Command as $Command } from "@aws-sdk/smithy-client";
import {
FinalizeHandlerArguments,
Handler,
HandlerExecutionContext,
HttpHandlerOptions as __HttpHandlerOptions,
MetadataBearer as __MetadataBearer,
MiddlewareStack,
SerdeContext as __SerdeContext,
} from "@aws-sdk/types";
import { EFSClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../EFSClient";
import { TagResourceRequest } from "../models/models_0";
import {
deserializeAws_restJson1TagResourceCommand,
serializeAws_restJson1TagResourceCommand,
} from "../protocols/Aws_restJson1";
export interface TagResourceCommandInput extends TagResourceRequest {}
export interface TagResourceCommandOutput extends __MetadataBearer {}
/**
* <p>Creates a tag for an EFS resource. You can create tags for EFS file systems and access points using this API operation.</p>
* <p>This operation requires permissions for the <code>elasticfilesystem:TagResource</code> action.</p>
* @example
* Use a bare-bones client and the command you need to make an API call.
* ```javascript
* import { EFSClient, TagResourceCommand } from "@aws-sdk/client-efs"; // ES Modules import
* // const { EFSClient, TagResourceCommand } = require("@aws-sdk/client-efs"); // CommonJS import
* const client = new EFSClient(config);
* const command = new TagResourceCommand(input);
* const response = await client.send(command);
* ```
*
* @see {@link TagResourceCommandInput} for command's `input` shape.
* @see {@link TagResourceCommandOutput} for command's `response` shape.
* @see {@link EFSClientResolvedConfig | config} for EFSClient's `config` shape.
*
*/
export class TagResourceCommand extends $Command<
TagResourceCommandInput,
TagResourceCommandOutput,
EFSClientResolvedConfig
> {
// Start section: command_properties
// End section: command_properties
constructor(readonly input: TagResourceCommandInput) {
// Start section: command_constructor
super();
// End section: command_constructor
}
/**
* @internal
*/
resolveMiddleware(
clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>, | configuration: EFSClientResolvedConfig,
options?: __HttpHandlerOptions
): Handler<TagResourceCommandInput, TagResourceCommandOutput> {
this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));
const stack = clientStack.concat(this.middlewareStack);
const { logger } = configuration;
const clientName = "EFSClient";
const commandName = "TagResourceCommand";
const handlerExecutionContext: HandlerExecutionContext = {
logger,
clientName,
commandName,
inputFilterSensitiveLog: TagResourceRequest.filterSensitiveLog,
outputFilterSensitiveLog: (output: any) => output,
};
const { requestHandler } = configuration;
return stack.resolve(
(request: FinalizeHandlerArguments<any>) =>
requestHandler.handle(request.request as __HttpRequest, options || {}),
handlerExecutionContext
);
}
private serialize(input: TagResourceCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
return serializeAws_restJson1TagResourceCommand(input, context);
}
private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<TagResourceCommandOutput> {
return deserializeAws_restJson1TagResourceCommand(output, context);
}
// Start section: command_body_extra
// End section: command_body_extra
} | |
event.js | const { indexed, title } = require('./shared')
const { links } = require('../links')
function | (e, out) {
if (!e || e.length === 0) {
return
}
out('|Input name|Type|Indexed|')
out('|----|----|:----:|')
e.forEach(ev =>
out(`|${ev.name}|[${ev.type}](${links[ev.type]})| ${indexed(ev)} |`)
)
out('\n')
}
function renderEvent(e, out) {
title(e, out)
renderInputs(e.inputs, out)
}
module.exports = {
renderEvents: function events(events, out) {
out(`## Events`)
events.forEach(e => renderEvent(e, out))
},
renderEvent
}
| renderInputs |
test_templatetags.py | import datetime
from django.contrib.admin import ModelAdmin
from django.contrib.admin.templatetags.admin_list import date_hierarchy
from django.contrib.admin.templatetags.admin_modify import submit_row
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.test import RequestFactory, TestCase
from django.urls import reverse | from .tests import AdminViewBasicTestCase
class AdminTemplateTagsTest(AdminViewBasicTestCase):
request_factory = RequestFactory()
def test_submit_row(self):
"""
submit_row template tag should pass whole context.
"""
request = self.request_factory.get(reverse('admin:auth_user_change', args=[self.superuser.pk]))
request.user = self.superuser
admin = UserAdmin(User, site)
extra_context = {'extra': True}
response = admin.change_view(request, str(self.superuser.pk), extra_context=extra_context)
template_context = submit_row(response.context_data)
self.assertIs(template_context['extra'], True)
self.assertIs(template_context['show_save'], True)
def test_override_show_save_and_add_another(self):
request = self.request_factory.get(
reverse('admin:auth_user_change', args=[self.superuser.pk]),
)
request.user = self.superuser
admin = UserAdmin(User, site)
for extra_context, expected_flag in (
({}, True), # Default.
({'show_save_and_add_another': False}, False),
):
with self.subTest(show_save_and_add_another=expected_flag):
response = admin.change_view(
request,
str(self.superuser.pk),
extra_context=extra_context,
)
template_context = submit_row(response.context_data)
self.assertIs(template_context['show_save_and_add_another'], expected_flag)
def test_override_change_form_template_tags(self):
"""
admin_modify template tags follow the standard search pattern
admin/app_label/model/template.html.
"""
article = Article.objects.all()[0]
request = self.request_factory.get(reverse('admin:admin_views_article_change', args=[article.pk]))
request.user = self.superuser
admin = ArticleAdmin(Article, site)
extra_context = {'show_publish': True, 'extra': True}
response = admin.change_view(request, str(article.pk), extra_context=extra_context)
response.render()
self.assertIs(response.context_data['show_publish'], True)
self.assertIs(response.context_data['extra'], True)
self.assertContains(response, 'name="_save"')
self.assertContains(response, 'name="_publish"')
self.assertContains(response, 'override-change_form_object_tools')
self.assertContains(response, 'override-prepopulated_fields_js')
def test_override_change_list_template_tags(self):
"""
admin_list template tags follow the standard search pattern
admin/app_label/model/template.html.
"""
request = self.request_factory.get(reverse('admin:admin_views_article_changelist'))
request.user = self.superuser
admin = ArticleAdmin(Article, site)
admin.date_hierarchy = 'date'
admin.search_fields = ('title', 'content')
response = admin.changelist_view(request)
response.render()
self.assertContains(response, 'override-actions')
self.assertContains(response, 'override-change_list_object_tools')
self.assertContains(response, 'override-change_list_results')
self.assertContains(response, 'override-date_hierarchy')
self.assertContains(response, 'override-pagination')
self.assertContains(response, 'override-search_form')
class DateHierarchyTests(TestCase):
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(username='super', password='secret', email='[email protected]')
def test_choice_links(self):
modeladmin = ModelAdmin(Question, site)
modeladmin.date_hierarchy = 'posted'
posted_dates = (
datetime.date(2017, 10, 1),
datetime.date(2017, 10, 1),
datetime.date(2017, 12, 15),
datetime.date(2017, 12, 15),
datetime.date(2017, 12, 31),
datetime.date(2018, 2, 1),
)
Question.objects.bulk_create(Question(question='q', posted=posted) for posted in posted_dates)
tests = (
({}, [['year=2017'], ['year=2018']]),
({'year': 2016}, []),
({'year': 2017}, [['month=10', 'year=2017'], ['month=12', 'year=2017']]),
({'year': 2017, 'month': 9}, []),
({'year': 2017, 'month': 12}, [['day=15', 'month=12', 'year=2017'], ['day=31', 'month=12', 'year=2017']]),
)
for query, expected_choices in tests:
with self.subTest(query=query):
query = {'posted__%s' % q: val for q, val in query.items()}
request = self.factory.get('/', query)
request.user = self.superuser
changelist = modeladmin.get_changelist_instance(request)
spec = date_hierarchy(changelist)
choices = [choice['link'] for choice in spec['choices']]
expected_choices = [
'&'.join('posted__%s' % c for c in choice) for choice in expected_choices
]
expected_choices = [('?' + choice) if choice else '' for choice in expected_choices]
self.assertEqual(choices, expected_choices) |
from .admin import ArticleAdmin, site
from .models import Article, Question |
add-block.component.ts | import {
Component,
Input,
OnInit,
OnDestroy,
ViewChild,
Inject,
} from "@angular/core";
import { Observable, Subscription, Subject, of, from } from "rxjs";
import { take, map, tap, switchMap, filter, takeWhile } from "rxjs/operators";
import {
LiturgicalDocument,
sortPsalms,
Psalm,
BibleReading,
docsToLiturgy,
} from "@venite/ldf";
import { DocumentService } from "src/app/services/document.service";
import { AuthServiceInterface, AUTH_SERVICE } from "@venite/ng-service-api";
import { AuthService } from "src/app/auth/auth.service";
import { AlertController, LoadingController } from "@ionic/angular";
import { TranslateService } from "@ngx-translate/core";
import { isCompletelyCompiled } from "../../pray/is-completely-compiled";
class MenuOption {
label: string;
section: string[];
icon: () => any;
template?: LiturgicalDocument[];
hidden?: boolean;
needsMoreInfo?:
| "psalm"
| "canticle"
| "lectionary"
| "hymn"
| "liturgy"
| "liturgy-inline"
| "invitatory"
| "image"
| "category"
| "slug"
| "response"
| "reading";
}
@Component({
selector: "venite-add-block",
templateUrl: "./add-block.component.html",
styleUrls: ["./add-block.component.scss"],
})
export class AddBlockComponent implements OnInit, OnDestroy {
@Input() language: string = "en";
@Input() modal: any;
@Input() templateMode: boolean = false;
@ViewChild("additional") additionalElement;
addition: MenuOption;
additionalMode:
| "psalm"
| "lectionary"
| "canticle"
| "hymn"
| "liturgy"
| "invitatory"
| "image"
| undefined;
// used in ldf-editable-filter-documents
additionalVersions: Observable<{ [key: string]: string }>;
additionalOptions: Observable<LiturgicalDocument[]>;
// used for lectionary/canticle table select
additionalTable: Observable<{ [key: string]: string }>;
// used in lectionary select
additionalBibleTranslations: Observable<{ [key: string]: string }>;
// return value
public complete: Subject<LiturgicalDocument[]> = new Subject();
completeSubscription: Subscription;
constructor(
private documentService: DocumentService,
public auth: AuthService,
private translate: TranslateService,
private alert: AlertController,
private loading: LoadingController
) {}
ngOnInit() {}
ngOnDestroy() {
if (this.completeSubscription) {
this.completeSubscription.unsubscribe();
}
}
add(ev: CustomEvent) {
const completed = this.completeOption(ev.detail);
if (this.templateMode) {
this.completeSubscription = completed
.pipe(take(1))
.subscribe((addition) => this.modal.dismiss(addition));
} else {
this.completeSubscription = completed
.pipe(
takeWhile((doc) => !isCompletelyCompiled(docsToLiturgy(doc)), true)
)
.subscribe((addition) => this.modal.dismiss(addition));
}
}
dismissEmpty() {
this.modal.dismiss(null);
}
completeOption(addition: MenuOption): Observable<LiturgicalDocument[]> {
// store the `MenuOption` we're passed in case we need to access it in a callback from one of the forms below
this.addition = addition;
if (addition) {
if (window) {
window.scrollTo(0, 0);
}
// types like Psalm, Canticle, and Lectionary Readings need another component to be completed
switch (addition.needsMoreInfo) {
case "image":
this.additionalMode = "image";
return this.complete;
case "psalm":
this.additionalMode = "psalm";
this.additionalVersions = this.documentService.getVersions(
this.language,
"psalm"
);
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService
.findDocumentsByCategory(["Psalm"], this.language, versions)
.pipe(
map((objs) =>
objs.sort((a, b) => sortPsalms(a as Psalm, b as Psalm))
)
)
)
);
return this.complete;
case "reading":
return from(this.readingAlert()).pipe(
filter((response) => Boolean(response)),
map((response) => [response])
);
case "invitatory":
this.additionalMode = "invitatory";
this.additionalVersions = this.documentService.getVersions(
this.language,
"liturgy"
);
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService.findDocumentsByCategory(
["Invitatory"],
this.language,
versions
)
)
);
return this.complete;
case "lectionary":
this.additionalMode = "lectionary";
this.additionalVersions = this.documentService.getVersions(
this.language,
"lectionary"
);
this.additionalTable = this.documentService.getVersions(
this.language,
"readings"
);
this.additionalBibleTranslations = this.documentService.getVersions(
this.language,
"bible-translation"
);
this.additionalOptions = this.documentService.findDocumentsByCategory(
["Bible Reading Introduction"],
this.language
);
return this.complete;
case "canticle": | this.additionalMode = "canticle";
this.additionalVersions = this.documentService.getVersions(
this.language,
"liturgy"
);
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService
.findDocumentsByCategory(["Canticle"], this.language, versions)
.pipe(
map((objs) =>
objs.map(
(obj) =>
new LiturgicalDocument({
...obj,
value: undefined,
lookup: { type: "slug" },
})
)
)
)
)
);
this.additionalTable = this.documentService.getVersions(
this.language,
"canticle-table"
);
return this.complete;
case "hymn":
this.additionalMode = "hymn";
return this.complete;
case "liturgy":
case "liturgy-inline":
this.additionalMode = "liturgy";
this.additionalVersions = this.documentService.getVersions(
this.language,
"liturgy-versions"
);
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService.find({ type: "liturgy" }).pipe(
map((objs) =>
objs
.filter((obj) => !obj.day)
.map(
(obj) =>
new LiturgicalDocument({
...obj,
value:
addition.needsMoreInfo === "liturgy"
? undefined
: obj.value,
lookup: { type: "slug" },
})
)
.sort((a, b) => (a.label > b.label ? 1 : -1))
)
)
)
);
return this.complete;
case "category":
const tplCatDoc = new LiturgicalDocument(addition.template[0] || {});
this.additionalMode = "liturgy";
this.additionalVersions =
tplCatDoc.type === "liturgy"
? // versions like Rite-II, etc.
this.documentService.getVersions(
this.language,
"liturgy-versions"
)
: // versions like bcp1979, etc.
this.documentService.getVersions(this.language, "liturgy");
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService.findDocumentsByCategory(
tplCatDoc.category,
this.language,
versions
)
),
map((docs) => docs.sort((a, b) => (a.label > b.label ? 1 : -1)))
);
return this.complete;
case "slug":
const tplSlugDoc = new LiturgicalDocument(addition.template[0] || {});
this.additionalMode = "liturgy";
this.additionalVersions =
tplSlugDoc.type === "liturgy"
? // versions like Rite-II, etc.
this.documentService.getVersions(
this.language,
"liturgy-versions"
)
: // versions like bcp1979, etc.
this.documentService.getVersions(this.language, "liturgy");
this.additionalOptions = this.additionalVersions.pipe(
map((versions) => Object.keys(versions)),
switchMap((versions) =>
this.documentService.findDocumentsBySlug(
tplSlugDoc.slug,
this.language,
versions
)
),
map((docs) => docs.sort((a, b) => (a.label > b.label ? 1 : -1)))
);
return this.complete;
case "response":
return from(this.responseAlert()).pipe(
map((response) =>
response
? addition.template.map(
(d) =>
new LiturgicalDocument({
...d,
metadata: {
...d.metadata,
response,
},
})
)
: undefined
)
);
// otherwise, it's already complete and we can return the original
default:
return of(addition.template);
}
} else {
this.dismissEmpty();
}
}
readingSelected(selection: {
lectionary: string;
reading: string;
version: string | { preference: string };
intro: LiturgicalDocument | null;
}) {
const { lectionary, reading, version, intro } = selection;
this.complete.next(
(this.addition.template || []).map(
(doc) =>
new LiturgicalDocument({
...doc,
lookup: {
type: "lectionary",
table: lectionary,
item: reading,
},
version,
metadata: {
...doc.metadata,
intro,
},
})
)
);
}
async responseAlert(): Promise<string | undefined> {
const alert = await this.alert.create({
header: this.translate.instant("editor.response"),
inputs: [
{
name: "response",
placeholder: this.translate.instant("editor.response"),
},
],
buttons: [
{
text: this.translate.instant("editor.cancel"),
role: "cancel",
},
{
text: this.translate.instant("editor.add"),
},
],
});
await alert.present();
const data = await alert.onDidDismiss();
return data?.data?.values?.response;
}
async readingAlert(): Promise<BibleReading | null> {
const alert = await this.alert.create({
header: this.translate.instant("editor.reading_adder"),
inputs: [
{
name: "citation",
placeholder: this.translate.instant("editor.citation"),
},
{
name: "version",
placeholder: this.translate.instant("editor.bible_version"),
value: "NRSV",
},
],
buttons: [
{
text: this.translate.instant("editor.cancel"),
role: "cancel",
},
{
text: this.translate.instant("editor.add"),
},
],
});
await alert.present();
const data = await alert.onDidDismiss();
const { citation, version } = data?.data?.values;
// citation + version => load and insert
if (citation && version) {
const loading = await this.loading.create({ backdropDismiss: true });
const reading = await this.fetchReading(citation, version);
loading.dismiss();
return reading;
}
// citation but not version => insert a lookup by `bibleVersion` pref
else if (citation) {
return new BibleReading({
type: "bible-reading",
style: "long",
citation,
version: {
preference: "bibleVersion",
},
});
}
// neither => dismiss
else {
return null;
}
}
async fetchReading(
citation: string,
version: string,
api: string = "https://us-central1-venite-2.cloudfunctions.net"
): Promise<BibleReading> {
const findURL = new URL(`${api}/bible`);
findURL.searchParams.append("citation", citation);
findURL.searchParams.append("version", version);
const response = await fetch(findURL.toString()),
body = await response.text();
try {
return JSON.parse(body);
} catch {
throw new Error(body);
}
}
} | |
Settings.js | const path = require('path');
const imagesDir = path.join(__dirname, 'images');
const homedir = require('os').homedir();
| "clips": {
"display": {
"max-length": 50
},
},
"hide-on-copy": true,
"hide-dock-icon": true,
"tray-icon": path.join(imagesDir, 'tray16x16.png'),
"newline-representation": "\u23CE", // "↵", ⏎
"tab-representation": "[TAB]"
},
"max-clipboard-size": 25,
"quick-actions": ["copy-json", "open-url"],
"actions": {
"save-text-file": {
"file-save-dir": path.join(homedir, "Downloads")
}
},
"dev-mode": false
};
module.exports.SETTINGS = SETTINGS; |
let SETTINGS = {
"ui": { |
test_basicfunction.py | import unittest
from net.wyun.mer.basicfunction import BasicFunction
class TestBasicFunction(unittest.TestCase):
def setUp(self):
self.func = BasicFunction()
def test_1(self):
self.assertTrue(True)
def | (self):
self.assertTrue(True)
def test_3(self):
self.assertEqual(self.func.state, 0)
def test_4(self):
self.func.increment_state()
self.assertEqual(self.func.state, 1)
def test_5(self):
self.func.increment_state()
self.func.increment_state()
self.func.clear_state()
self.assertEqual(self.func.state, 0)
if __name__ == '__main__':
unittest.main() | test_2 |
tretinoinGlyph.ts | import { TretinoinGlyph, TretinoinGlyphSecondary } from './svgs';
import { IconProps, useIcon } from '../../shared-components/icon';
export default (props: IconProps) => | useIcon(TretinoinGlyph, TretinoinGlyphSecondary, props); |
|
annotation_set_ref_list.rs | // Shane Isbell licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
use map_list::MapData;
use prelude::DexReader;
use std::io::Cursor;
#[derive(Debug, PartialEq, PartialOrd, Clone)] | }
#[derive(Debug, PartialEq, PartialOrd, Clone)]
pub struct AnnotationSetRefItem {
annotations_off: u32,
}
pub fn diff_annotation_set_ref_list<'a, 'b>(
v1: &'a Vec<AnnotationSetRefList>,
v2: &'b Vec<AnnotationSetRefList>,
) -> Vec<(&'a AnnotationSetRefList, &'b AnnotationSetRefList)> {
v1.iter().zip(v2.iter()).filter(|&(a, b)| a != b).collect()
}
pub fn read_annotation_set_ref_list(data: &MapData) -> Vec<AnnotationSetRefList> {
let mut cursor = Cursor::new(&data.data);
let mut list = Vec::new();
for _i in 0..data.size {
list.push(AnnotationSetRefList::read(&mut cursor));
}
list
}
impl AnnotationSetRefList {
pub fn read(data: &mut Cursor<&Vec<u8>>) -> AnnotationSetRefList {
let size = data.u32();
AnnotationSetRefList {
size: size,
list: AnnotationSetRefItem::read_list(data, size),
}
}
}
impl AnnotationSetRefItem {
pub fn read_list(data: &mut Cursor<&Vec<u8>>, size: u32) -> Vec<AnnotationSetRefItem> {
let mut items = Vec::new();
for _i in 0..size {
items.push(AnnotationSetRefItem::read(data));
}
items
}
pub fn read(data: &mut Cursor<&Vec<u8>>) -> AnnotationSetRefItem {
AnnotationSetRefItem {
annotations_off: data.u32(),
}
}
} | pub struct AnnotationSetRefList {
size: u32,
list: Vec<AnnotationSetRefItem>, |
add.go | /*
Copyright © 2021 NAME HERE <EMAIL ADDRESS>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"github.com/gtck520/spiderMan/controller"
"github.com/spf13/cobra"
)
// addCmd represents the add command
var add_name string
var spider = controller.Spider{}
var addCmd = &cobra.Command{
Use: "add",
// 定义arguments数量最少为1个
Args: cobra.MinimumNArgs(1),
Short: "add ...urls",
Long: `添加一个或多个url地址,多个用空格分割,将地址加入到工作队列中,并同时生成这个地址爬虫规则文件。`,
Run: func(cmd *cobra.Command, args []string) {
spider.Add(cmd, args, add_name)
},
}
func init() {
rootCmd.AddCommand(addCmd)
//永久选项
// 下面定义了一个Flag foo, foo后面接的值会被赋值给Foo
//Foo = addCmd.PersistentFlags( | ).String("foo", "", "A help for foo")
// 下面定义了一个Flag print ,print后面的值会被赋值给Print变量
//addCmd.PersistentFlags().StringVar(&Print, "print", "", "print")
// 下面定义了一个Flag show,show默认为false, 有两种调用方式--show\-s,命令后面接了show则上面定义的show变量就会变成true
//addCmd.PersistentFlags().BoolVarP(&show, "show", "s", false, "show")
//本地选项
// 下面定义了一个Flag show,show默认为false, 有两种调用方式--show\-s,命令后面接了show则上面定义的show变量就会变成true
//showL = *addCmd.Flags().BoolP("showL", "S", false, "show")
// 下面定义了一个Flag print ,print后面的值会被赋值给Print变量
//addCmd.Flags().StringVar(&PrintL, "printL", "", "print")
// 下面定义了一个Flag fooL, foo后面接的值会被赋值给FooL
//FooL = addCmd.Flags().String("fooL", "", "A help for foo")
//show = *testCmd.Flags().BoolP("show", "s", false, "show")
// 设置使用test的时候后面必须接show
//_ = testCmd.MarkFlagRequired("show")
addCmd.Flags().StringVarP(&add_name, "name", "n", "", "必须为url标记个名称,多个需要一一对应用逗号隔开")
_ = addCmd.MarkFlagRequired("name")
}
|
|
discovery.py | """Device discovery functions for Zigbee Home Automation."""
from collections import Counter
import logging
from typing import Callable, List, Tuple
from homeassistant import const as ha_const
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import (
async_dispatcher_connect,
async_dispatcher_send,
)
from homeassistant.helpers.entity_registry import async_entries_for_device
from homeassistant.helpers.typing import HomeAssistantType
from . import const as zha_const, registries as zha_regs, typing as zha_typing
from .. import ( # noqa: F401 pylint: disable=unused-import,
binary_sensor,
cover,
device_tracker,
fan,
light,
lock,
sensor,
switch,
)
from .channels import base
_LOGGER = logging.getLogger(__name__)
@callback
async def async_add_entities(
_async_add_entities: Callable,
entities: List[
Tuple[
zha_typing.ZhaEntityType,
Tuple[str, zha_typing.ZhaDeviceType, List[zha_typing.ChannelType]],
]
],
) -> None:
|
class ProbeEndpoint:
"""All discovered channels and entities of an endpoint."""
def __init__(self):
"""Initialize instance."""
self._device_configs = {}
@callback
def discover_entities(self, channel_pool: zha_typing.ChannelPoolType) -> None:
"""Process an endpoint on a zigpy device."""
self.discover_by_device_type(channel_pool)
self.discover_by_cluster_id(channel_pool)
@callback
def discover_by_device_type(self, channel_pool: zha_typing.ChannelPoolType) -> None:
"""Process an endpoint on a zigpy device."""
unique_id = channel_pool.unique_id
component = self._device_configs.get(unique_id, {}).get(ha_const.CONF_TYPE)
if component is None:
ep_profile_id = channel_pool.endpoint.profile_id
ep_device_type = channel_pool.endpoint.device_type
component = zha_regs.DEVICE_CLASS[ep_profile_id].get(ep_device_type)
if component and component in zha_const.COMPONENTS:
channels = channel_pool.unclaimed_channels()
entity_class, claimed = zha_regs.ZHA_ENTITIES.get_entity(
component, channel_pool.manufacturer, channel_pool.model, channels
)
if entity_class is None:
return
channel_pool.claim_channels(claimed)
channel_pool.async_new_entity(component, entity_class, unique_id, claimed)
@callback
def discover_by_cluster_id(self, channel_pool: zha_typing.ChannelPoolType) -> None:
"""Process an endpoint on a zigpy device."""
items = zha_regs.SINGLE_INPUT_CLUSTER_DEVICE_CLASS.items()
single_input_clusters = {
cluster_class: match
for cluster_class, match in items
if not isinstance(cluster_class, int)
}
remaining_channels = channel_pool.unclaimed_channels()
for channel in remaining_channels:
if channel.cluster.cluster_id in zha_regs.CHANNEL_ONLY_CLUSTERS:
channel_pool.claim_channels([channel])
continue
component = zha_regs.SINGLE_INPUT_CLUSTER_DEVICE_CLASS.get(
channel.cluster.cluster_id
)
if component is None:
for cluster_class, match in single_input_clusters.items():
if isinstance(channel.cluster, cluster_class):
component = match
break
self.probe_single_cluster(component, channel, channel_pool)
# until we can get rid off registries
self.handle_on_off_output_cluster_exception(channel_pool)
@staticmethod
def probe_single_cluster(
component: str,
channel: zha_typing.ChannelType,
ep_channels: zha_typing.ChannelPoolType,
) -> None:
"""Probe specified cluster for specific component."""
if component is None or component not in zha_const.COMPONENTS:
return
channel_list = [channel]
unique_id = f"{ep_channels.unique_id}-{channel.cluster.cluster_id}"
entity_class, claimed = zha_regs.ZHA_ENTITIES.get_entity(
component, ep_channels.manufacturer, ep_channels.model, channel_list
)
if entity_class is None:
return
ep_channels.claim_channels(claimed)
ep_channels.async_new_entity(component, entity_class, unique_id, claimed)
def handle_on_off_output_cluster_exception(
self, ep_channels: zha_typing.ChannelPoolType
) -> None:
"""Process output clusters of the endpoint."""
profile_id = ep_channels.endpoint.profile_id
device_type = ep_channels.endpoint.device_type
if device_type in zha_regs.REMOTE_DEVICE_TYPES.get(profile_id, []):
return
for cluster_id, cluster in ep_channels.endpoint.out_clusters.items():
component = zha_regs.SINGLE_OUTPUT_CLUSTER_DEVICE_CLASS.get(
cluster.cluster_id
)
if component is None:
continue
channel_class = zha_regs.ZIGBEE_CHANNEL_REGISTRY.get(
cluster_id, base.ZigbeeChannel
)
channel = channel_class(cluster, ep_channels)
self.probe_single_cluster(component, channel, ep_channels)
def initialize(self, hass: HomeAssistantType) -> None:
"""Update device overrides config."""
zha_config = hass.data[zha_const.DATA_ZHA].get(zha_const.DATA_ZHA_CONFIG, {})
overrides = zha_config.get(zha_const.CONF_DEVICE_CONFIG)
if overrides:
self._device_configs.update(overrides)
class GroupProbe:
"""Determine the appropriate component for a group."""
def __init__(self):
"""Initialize instance."""
self._hass = None
self._unsubs = []
def initialize(self, hass: HomeAssistantType) -> None:
"""Initialize the group probe."""
self._hass = hass
self._unsubs.append(
async_dispatcher_connect(
hass, zha_const.SIGNAL_GROUP_ENTITY_REMOVED, self._reprobe_group
)
)
def cleanup(self):
"""Clean up on when zha shuts down."""
for unsub in self._unsubs[:]:
unsub()
self._unsubs.remove(unsub)
def _reprobe_group(self, group_id: int) -> None:
"""Reprobe a group for entities after its members change."""
zha_gateway = self._hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
zha_group = zha_gateway.groups.get(group_id)
if zha_group is None:
return
self.discover_group_entities(zha_group)
@callback
def discover_group_entities(self, group: zha_typing.ZhaGroupType) -> None:
"""Process a group and create any entities that are needed."""
# only create a group entity if there are 2 or more members in a group
if len(group.members) < 2:
_LOGGER.debug(
"Group: %s:0x%04x has less than 2 members - skipping entity discovery",
group.name,
group.group_id,
)
return
entity_domains = GroupProbe.determine_entity_domains(self._hass, group)
if not entity_domains:
return
zha_gateway = self._hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
for domain in entity_domains:
entity_class = zha_regs.ZHA_ENTITIES.get_group_entity(domain)
if entity_class is None:
continue
self._hass.data[zha_const.DATA_ZHA][domain].append(
(
entity_class,
(
group.get_domain_entity_ids(domain),
f"{domain}_zha_group_0x{group.group_id:04x}",
group.group_id,
zha_gateway.coordinator_zha_device,
),
)
)
async_dispatcher_send(self._hass, zha_const.SIGNAL_ADD_ENTITIES)
@staticmethod
def determine_entity_domains(
hass: HomeAssistantType, group: zha_typing.ZhaGroupType
) -> List[str]:
"""Determine the entity domains for this group."""
entity_domains: List[str] = []
zha_gateway = hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY]
all_domain_occurrences = []
for member in group.members:
if member.device.is_coordinator:
continue
entities = async_entries_for_device(
zha_gateway.ha_entity_registry, member.device.device_id
)
all_domain_occurrences.extend(
[
entity.domain
for entity in entities
if entity.domain in zha_regs.GROUP_ENTITY_DOMAINS
]
)
if not all_domain_occurrences:
return entity_domains
# get all domains we care about if there are more than 2 entities of this domain
counts = Counter(all_domain_occurrences)
entity_domains = [domain[0] for domain in counts.items() if domain[1] >= 2]
_LOGGER.debug(
"The entity domains are: %s for group: %s:0x%04x",
entity_domains,
group.name,
group.group_id,
)
return entity_domains
PROBE = ProbeEndpoint()
GROUP_PROBE = GroupProbe()
| """Add entities helper."""
if not entities:
return
to_add = [ent_cls(*args) for ent_cls, args in entities]
_async_add_entities(to_add, update_before_add=True)
entities.clear() |
exception.rs | pub use jni::errors::Error;
use jni::{errors::ErrorKind, JNIEnv};
use std::thread;
pub fn runtime_error(message: String) -> Error {
Error::from_kind(ErrorKind::Msg(message))
}
#[derive(Debug)]
pub enum | <T> {
Some(T),
None,
}
impl<T> JOption<T> {
pub fn unwrap_or(self, default: T) -> T {
match self {
JOption::Some(result) => result,
JOption::None => default,
}
}
}
pub fn joption_or_throw<T>(env: &JNIEnv, result: thread::Result<Result<T, Error>>) -> JOption<T> {
match result {
Ok(result) => match result {
Ok(result) => JOption::Some(result),
Err(error) => {
if !env.exception_check().unwrap() {
env.throw_new("java/lang/RuntimeException", &error.to_string())
.expect("Cannot throw an `java/lang/RuntimeException` exception.");
}
JOption::None
}
},
Err(ref error) => {
env.throw_new("java/lang/RuntimeException", format!("{:?}", error))
.expect("Cannot throw an `java/lang/RuntimeException` exception.");
JOption::None
}
}
}
| JOption |
threading.py | """Thread module emulating a subset of Java's threading model."""
import sys as _sys
import _thread
from time import monotonic as _time
from traceback import format_exc as _format_exc
from _weakrefset import WeakSet
from itertools import islice as _islice
try:
from _collections import deque as _deque
except ImportError:
from collections import deque as _deque
# Note regarding PEP 8 compliant names
# This threading model was originally inspired by Java, and inherited
# the convention of camelCase function and method names from that
# language. Those original names are not in any imminent danger of
# being deprecated (even for Py3k),so this module provides them as an
# alias for the PEP 8 compliant names
# Note that using the new PEP 8 compliant names facilitates substitution
# with the multiprocessing module, which doesn't provide the old
# Java inspired names.
__all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier',
'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size']
# Rename some stuff so "from threading import *" is safe
_start_new_thread = _thread.start_new_thread
_allocate_lock = _thread.allocate_lock
_set_sentinel = _thread._set_sentinel
get_ident = _thread.get_ident
ThreadError = _thread.error
try:
_CRLock = _thread.RLock
except AttributeError:
_CRLock = None
TIMEOUT_MAX = _thread.TIMEOUT_MAX
del _thread
# Support for profile and trace hooks
_profile_hook = None
_trace_hook = None
def setprofile(func):
"""Set a profile function for all threads started from the threading module.
The func will be passed to sys.setprofile() for each thread, before its
run() method is called.
"""
global _profile_hook
_profile_hook = func
def settrace(func):
"""Set a trace function for all threads started from the threading module.
The func will be passed to sys.settrace() for each thread, before its run()
method is called.
"""
global _trace_hook
_trace_hook = func
# Synchronization classes
Lock = _allocate_lock
def RLock(*args, **kwargs):
"""Factory function that returns a new reentrant lock.
A reentrant lock must be released by the thread that acquired it. Once a
thread has acquired a reentrant lock, the same thread may acquire it again
without blocking; the thread must release it once for each time it has
acquired it.
"""
if _CRLock is None:
return _PyRLock(*args, **kwargs)
return _CRLock(*args, **kwargs)
class _RLock:
"""This class implements reentrant lock objects.
A reentrant lock must be released by the thread that acquired it. Once a
thread has acquired a reentrant lock, the same thread may acquire it
again without blocking; the thread must release it once for each time it
has acquired it.
"""
def __init__(self):
self._block = _allocate_lock()
self._owner = None
self._count = 0
def __repr__(self):
owner = self._owner
try:
owner = _active[owner].name
except KeyError:
pass
return "<%s %s.%s object owner=%r count=%d at %s>" % (
"locked" if self._block.locked() else "unlocked",
self.__class__.__module__,
self.__class__.__qualname__,
owner,
self._count,
hex(id(self))
)
def acquire(self, blocking=True, timeout=-1):
"""Acquire a lock, blocking or non-blocking.
When invoked without arguments: if this thread already owns the lock,
increment the recursion level by one, and return immediately. Otherwise,
if another thread owns the lock, block until the lock is unlocked. Once
the lock is unlocked (not owned by any thread), then grab ownership, set
the recursion level to one, and return. If more than one thread is
blocked waiting until the lock is unlocked, only one at a time will be
able to grab ownership of the lock. There is no return value in this
case.
When invoked with the blocking argument set to true, do the same thing
as when called without arguments, and return true.
When invoked with the blocking argument set to false, do not block. If a
call without an argument would block, return false immediately;
otherwise, do the same thing as when called without arguments, and
return true.
When invoked with the floating-point timeout argument set to a positive
value, block for at most the number of seconds specified by timeout
and as long as the lock cannot be acquired. Return true if the lock has
been acquired, false if the timeout has elapsed.
"""
me = get_ident()
if self._owner == me:
self._count += 1
return 1
rc = self._block.acquire(blocking, timeout)
if rc:
self._owner = me
self._count = 1
return rc
__enter__ = acquire
def release(self):
"""Release a lock, decrementing the recursion level.
If after the decrement it is zero, reset the lock to unlocked (not owned
by any thread), and if any other threads are blocked waiting for the
lock to become unlocked, allow exactly one of them to proceed. If after
the decrement the recursion level is still nonzero, the lock remains
locked and owned by the calling thread.
Only call this method when the calling thread owns the lock. A
RuntimeError is raised if this method is called when the lock is
unlocked.
There is no return value.
"""
if self._owner != get_ident():
raise RuntimeError("cannot release un-acquired lock")
self._count = count = self._count - 1
if not count:
self._owner = None
self._block.release()
def __exit__(self, t, v, tb):
self.release()
# Internal methods used by condition variables
def _acquire_restore(self, state):
self._block.acquire()
self._count, self._owner = state
def _release_save(self):
if self._count == 0:
raise RuntimeError("cannot release un-acquired lock")
count = self._count
self._count = 0
owner = self._owner
self._owner = None
self._block.release()
return (count, owner)
def _is_owned(self):
return self._owner == get_ident()
_PyRLock = _RLock
class Condition:
"""Class that implements a condition variable.
A condition variable allows one or more threads to wait until they are
notified by another thread.
If the lock argument is given and not None, it must be a Lock or RLock
object, and it is used as the underlying lock. Otherwise, a new RLock object
is created and used as the underlying lock.
"""
def __init__(self, lock=None):
if lock is None:
lock = RLock()
self._lock = lock
# Export the lock's acquire() and release() methods
self.acquire = lock.acquire
self.release = lock.release
# If the lock defines _release_save() and/or _acquire_restore(),
# these override the default implementations (which just call
# release() and acquire() on the lock). Ditto for _is_owned().
try:
self._release_save = lock._release_save
except AttributeError:
pass
try:
self._acquire_restore = lock._acquire_restore
except AttributeError:
pass
try:
self._is_owned = lock._is_owned
except AttributeError:
pass
self._waiters = _deque()
def __enter__(self):
return self._lock.__enter__()
def __exit__(self, *args):
return self._lock.__exit__(*args)
def | (self):
return "<Condition(%s, %d)>" % (self._lock, len(self._waiters))
def _release_save(self):
self._lock.release() # No state to save
def _acquire_restore(self, x):
self._lock.acquire() # Ignore saved state
def _is_owned(self):
# Return True if lock is owned by current_thread.
# This method is called only if _lock doesn't have _is_owned().
if self._lock.acquire(0):
self._lock.release()
return False
else:
return True
def wait(self, timeout=None):
"""Wait until notified or until a timeout occurs.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is
awakened by a notify() or notify_all() call for the same condition
variable in another thread, or until the optional timeout occurs. Once
awakened or timed out, it re-acquires the lock and returns.
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
When the underlying lock is an RLock, it is not released using its
release() method, since this may not actually unlock the lock when it
was acquired multiple times recursively. Instead, an internal interface
of the RLock class is used, which really unlocks it even when it has
been recursively acquired several times. Another internal interface is
then used to restore the recursion level when the lock is reacquired.
"""
if not self._is_owned():
raise RuntimeError("cannot wait on un-acquired lock")
waiter = _allocate_lock()
waiter.acquire()
self._waiters.append(waiter)
saved_state = self._release_save()
gotit = False
try: # restore state no matter what (e.g., KeyboardInterrupt)
if timeout is None:
waiter.acquire()
gotit = True
else:
if timeout > 0:
gotit = waiter.acquire(True, timeout)
else:
gotit = waiter.acquire(False)
return gotit
finally:
self._acquire_restore(saved_state)
if not gotit:
try:
self._waiters.remove(waiter)
except ValueError:
pass
def wait_for(self, predicate, timeout=None):
"""Wait until a condition evaluates to True.
predicate should be a callable which result will be interpreted as a
boolean value. A timeout may be provided giving the maximum time to
wait.
"""
endtime = None
waittime = timeout
result = predicate()
while not result:
if waittime is not None:
if endtime is None:
endtime = _time() + waittime
else:
waittime = endtime - _time()
if waittime <= 0:
break
self.wait(waittime)
result = predicate()
return result
def notify(self, n=1):
"""Wake up one or more threads waiting on this condition, if any.
If the calling thread has not acquired the lock when this method is
called, a RuntimeError is raised.
This method wakes up at most n of the threads waiting for the condition
variable; it is a no-op if no threads are waiting.
"""
if not self._is_owned():
raise RuntimeError("cannot notify on un-acquired lock")
all_waiters = self._waiters
waiters_to_notify = _deque(_islice(all_waiters, n))
if not waiters_to_notify:
return
for waiter in waiters_to_notify:
waiter.release()
try:
all_waiters.remove(waiter)
except ValueError:
pass
def notify_all(self):
"""Wake up all threads waiting on this condition.
If the calling thread has not acquired the lock when this method
is called, a RuntimeError is raised.
"""
self.notify(len(self._waiters))
notifyAll = notify_all
class Semaphore:
"""This class implements semaphore objects.
Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If not given, value defaults to 1.
"""
# After Tim Peters' semaphore class, but not quite the same (no maximum)
def __init__(self, value=1):
if value < 0:
raise ValueError("semaphore initial value must be >= 0")
self._cond = Condition(Lock())
self._value = value
def acquire(self, blocking=True, timeout=None):
"""Acquire a semaphore, decrementing the internal counter by one.
When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately. If it is zero
on entry, block, waiting until some other thread has called release() to
make it larger than zero. This is done with proper interlocking so that
if multiple acquire() calls are blocked, release() will wake exactly one
of them up. The implementation may pick one at random, so the order in
which blocked threads are awakened should not be relied on. There is no
return value in this case.
When invoked with blocking set to true, do the same thing as when called
without arguments, and return true.
When invoked with blocking set to false, do not block. If a call without
an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.
When invoked with a timeout other than None, it will block for at
most timeout seconds. If acquire does not complete successfully in
that interval, return false. Return true otherwise.
"""
if not blocking and timeout is not None:
raise ValueError("can't specify timeout for non-blocking acquire")
rc = False
endtime = None
with self._cond:
while self._value == 0:
if not blocking:
break
if timeout is not None:
if endtime is None:
endtime = _time() + timeout
else:
timeout = endtime - _time()
if timeout <= 0:
break
self._cond.wait(timeout)
else:
self._value -= 1
rc = True
return rc
__enter__ = acquire
def release(self):
"""Release a semaphore, incrementing the internal counter by one.
When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.
"""
with self._cond:
self._value += 1
self._cond.notify()
def __exit__(self, t, v, tb):
self.release()
class BoundedSemaphore(Semaphore):
"""Implements a bounded semaphore.
A bounded semaphore checks to make sure its current value doesn't exceed its
initial value. If it does, ValueError is raised. In most situations
semaphores are used to guard resources with limited capacity.
If the semaphore is released too many times it's a sign of a bug. If not
given, value defaults to 1.
Like regular semaphores, bounded semaphores manage a counter representing
the number of release() calls minus the number of acquire() calls, plus an
initial value. The acquire() method blocks if necessary until it can return
without making the counter negative. If not given, value defaults to 1.
"""
def __init__(self, value=1):
Semaphore.__init__(self, value)
self._initial_value = value
def release(self):
"""Release a semaphore, incrementing the internal counter by one.
When the counter is zero on entry and another thread is waiting for it
to become larger than zero again, wake up that thread.
If the number of releases exceeds the number of acquires,
raise a ValueError.
"""
with self._cond:
if self._value >= self._initial_value:
raise ValueError("Semaphore released too many times")
self._value += 1
self._cond.notify()
class Event:
"""Class implementing event objects.
Events manage a flag that can be set to true with the set() method and reset
to false with the clear() method. The wait() method blocks until the flag is
true. The flag is initially false.
"""
# After Tim Peters' event class (without is_posted())
def __init__(self):
self._cond = Condition(Lock())
self._flag = False
def _reset_internal_locks(self):
# private! called by Thread._reset_internal_locks by _after_fork()
self._cond.__init__()
def is_set(self):
"""Return true if and only if the internal flag is true."""
return self._flag
isSet = is_set
def set(self):
"""Set the internal flag to true.
All threads waiting for it to become true are awakened. Threads
that call wait() once the flag is true will not block at all.
"""
self._cond.acquire()
try:
self._flag = True
self._cond.notify_all()
finally:
self._cond.release()
def clear(self):
"""Reset the internal flag to false.
Subsequently, threads calling wait() will block until set() is called to
set the internal flag to true again.
"""
self._cond.acquire()
try:
self._flag = False
finally:
self._cond.release()
def wait(self, timeout=None):
"""Block until the internal flag is true.
If the internal flag is true on entry, return immediately. Otherwise,
block until another thread calls set() to set the flag to true, or until
the optional timeout occurs.
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).
This method returns the internal flag on exit, so it will always return
True except if a timeout is given and the operation times out.
"""
self._cond.acquire()
try:
signaled = self._flag
if not signaled:
signaled = self._cond.wait(timeout)
return signaled
finally:
self._cond.release()
# A barrier class. Inspired in part by the pthread_barrier_* api and
# the CyclicBarrier class from Java. See
# http://sourceware.org/pthreads-win32/manual/pthread_barrier_init.html and
# http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/
# CyclicBarrier.html
# for information.
# We maintain two main states, 'filling' and 'draining' enabling the barrier
# to be cyclic. Threads are not allowed into it until it has fully drained
# since the previous cycle. In addition, a 'resetting' state exists which is
# similar to 'draining' except that threads leave with a BrokenBarrierError,
# and a 'broken' state in which all threads get the exception.
class Barrier:
"""Implements a Barrier.
Useful for synchronizing a fixed number of threads at known synchronization
points. Threads block on 'wait()' and are simultaneously once they have all
made that call.
"""
def __init__(self, parties, action=None, timeout=None):
"""Create a barrier, initialised to 'parties' threads.
'action' is a callable which, when supplied, will be called by one of
the threads after they have all entered the barrier and just prior to
releasing them all. If a 'timeout' is provided, it is uses as the
default for all subsequent 'wait()' calls.
"""
self._cond = Condition(Lock())
self._action = action
self._timeout = timeout
self._parties = parties
self._state = 0 #0 filling, 1, draining, -1 resetting, -2 broken
self._count = 0
def wait(self, timeout=None):
"""Wait for the barrier.
When the specified number of threads have started waiting, they are all
simultaneously awoken. If an 'action' was provided for the barrier, one
of the threads will have executed that callback prior to returning.
Returns an individual index number from 0 to 'parties-1'.
"""
if timeout is None:
timeout = self._timeout
with self._cond:
self._enter() # Block while the barrier drains.
index = self._count
self._count += 1
try:
if index + 1 == self._parties:
# We release the barrier
self._release()
else:
# We wait until someone releases us
self._wait(timeout)
return index
finally:
self._count -= 1
# Wake up any threads waiting for barrier to drain.
self._exit()
# Block until the barrier is ready for us, or raise an exception
# if it is broken.
def _enter(self):
while self._state in (-1, 1):
# It is draining or resetting, wait until done
self._cond.wait()
#see if the barrier is in a broken state
if self._state < 0:
raise BrokenBarrierError
assert self._state == 0
# Optionally run the 'action' and release the threads waiting
# in the barrier.
def _release(self):
try:
if self._action:
self._action()
# enter draining state
self._state = 1
self._cond.notify_all()
except:
#an exception during the _action handler. Break and reraise
self._break()
raise
# Wait in the barrier until we are relased. Raise an exception
# if the barrier is reset or broken.
def _wait(self, timeout):
if not self._cond.wait_for(lambda : self._state != 0, timeout):
#timed out. Break the barrier
self._break()
raise BrokenBarrierError
if self._state < 0:
raise BrokenBarrierError
assert self._state == 1
# If we are the last thread to exit the barrier, signal any threads
# waiting for the barrier to drain.
def _exit(self):
if self._count == 0:
if self._state in (-1, 1):
#resetting or draining
self._state = 0
self._cond.notify_all()
def reset(self):
"""Reset the barrier to the initial state.
Any threads currently waiting will get the BrokenBarrier exception
raised.
"""
with self._cond:
if self._count > 0:
if self._state == 0:
#reset the barrier, waking up threads
self._state = -1
elif self._state == -2:
#was broken, set it to reset state
#which clears when the last thread exits
self._state = -1
else:
self._state = 0
self._cond.notify_all()
def abort(self):
"""Place the barrier into a 'broken' state.
Useful in case of error. Any currently waiting threads and threads
attempting to 'wait()' will have BrokenBarrierError raised.
"""
with self._cond:
self._break()
def _break(self):
# An internal error was detected. The barrier is set to
# a broken state all parties awakened.
self._state = -2
self._cond.notify_all()
@property
def parties(self):
"""Return the number of threads required to trip the barrier."""
return self._parties
@property
def n_waiting(self):
"""Return the number of threads currently waiting at the barrier."""
# We don't need synchronization here since this is an ephemeral result
# anyway. It returns the correct value in the steady state.
if self._state == 0:
return self._count
return 0
@property
def broken(self):
"""Return True if the barrier is in a broken state."""
return self._state == -2
# exception raised by the Barrier class
class BrokenBarrierError(RuntimeError):
pass
# Helper to generate new thread names
_counter = 0
def _newname(template="Thread-%d"):
global _counter
_counter += 1
return template % _counter
# Active thread administration
_active_limbo_lock = _allocate_lock()
_active = {} # maps thread id to Thread object
_limbo = {}
_dangling = WeakSet()
# Main class for threads
class Thread:
"""A class that represents a thread of control.
This class can be safely subclassed in a limited fashion. There are two ways
to specify the activity: by passing a callable object to the constructor, or
by overriding the run() method in a subclass.
"""
_initialized = False
# Need to store a reference to sys.exc_info for printing
# out exceptions when a thread tries to use a global var. during interp.
# shutdown and thus raises an exception about trying to perform some
# operation on/with a NoneType
_exc_info = _sys.exc_info
# Keep sys.exc_clear too to clear the exception just before
# allowing .join() to return.
#XXX __exc_clear = _sys.exc_clear
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None):
"""This constructor should always be called with keyword arguments. Arguments are:
*group* should be None; reserved for future extension when a ThreadGroup
class is implemented.
*target* is the callable object to be invoked by the run()
method. Defaults to None, meaning nothing is called.
*name* is the thread name. By default, a unique name is constructed of
the form "Thread-N" where N is a small decimal number.
*args* is the argument tuple for the target invocation. Defaults to ().
*kwargs* is a dictionary of keyword arguments for the target
invocation. Defaults to {}.
If a subclass overrides the constructor, it must make sure to invoke
the base class constructor (Thread.__init__()) before doing anything
else to the thread.
"""
assert group is None, "group argument must be None for now"
if kwargs is None:
kwargs = {}
self._target = target
self._name = str(name or _newname())
self._args = args
self._kwargs = kwargs
if daemon is not None:
self._daemonic = daemon
else:
self._daemonic = current_thread().daemon
self._ident = None
self._tstate_lock = None
self._started = Event()
self._is_stopped = False
self._initialized = True
# sys.stderr is not stored in the class like
# sys.exc_info since it can be changed between instances
self._stderr = _sys.stderr
# For debugging and _after_fork()
_dangling.add(self)
def _reset_internal_locks(self, is_alive):
# private! Called by _after_fork() to reset our internal locks as
# they may be in an invalid state leading to a deadlock or crash.
self._started._reset_internal_locks()
if is_alive:
self._set_tstate_lock()
else:
# The thread isn't alive after fork: it doesn't have a tstate
# anymore.
self._is_stopped = True
self._tstate_lock = None
def __repr__(self):
assert self._initialized, "Thread.__init__() was not called"
status = "initial"
if self._started.is_set():
status = "started"
self.is_alive() # easy way to get ._is_stopped set when appropriate
if self._is_stopped:
status = "stopped"
if self._daemonic:
status += " daemon"
if self._ident is not None:
status += " %s" % self._ident
return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)
def start(self):
"""Start the thread's activity.
It must be called at most once per thread object. It arranges for the
object's run() method to be invoked in a separate thread of control.
This method will raise a RuntimeError if called more than once on the
same thread object.
"""
if not self._initialized:
raise RuntimeError("thread.__init__() not called")
if self._started.is_set():
raise RuntimeError("threads can only be started once")
with _active_limbo_lock:
_limbo[self] = self
try:
_start_new_thread(self._bootstrap, ())
except Exception:
with _active_limbo_lock:
del _limbo[self]
raise
self._started.wait()
def run(self):
"""Method representing the thread's activity.
You may override this method in a subclass. The standard run() method
invokes the callable object passed to the object's constructor as the
target argument, if any, with sequential and keyword arguments taken
from the args and kwargs arguments, respectively.
"""
try:
if self._target:
self._target(*self._args, **self._kwargs)
finally:
# Avoid a refcycle if the thread is running a function with
# an argument that has a member that points to the thread.
del self._target, self._args, self._kwargs
def _bootstrap(self):
# Wrapper around the real bootstrap code that ignores
# exceptions during interpreter cleanup. Those typically
# happen when a daemon thread wakes up at an unfortunate
# moment, finds the world around it destroyed, and raises some
# random exception *** while trying to report the exception in
# _bootstrap_inner() below ***. Those random exceptions
# don't help anybody, and they confuse users, so we suppress
# them. We suppress them only when it appears that the world
# indeed has already been destroyed, so that exceptions in
# _bootstrap_inner() during normal business hours are properly
# reported. Also, we only suppress them for daemonic threads;
# if a non-daemonic encounters this, something else is wrong.
try:
self._bootstrap_inner()
except:
if self._daemonic and _sys is None:
return
raise
def _set_ident(self):
self._ident = get_ident()
def _set_tstate_lock(self):
"""
Set a lock object which will be released by the interpreter when
the underlying thread state (see pystate.h) gets deleted.
"""
self._tstate_lock = _set_sentinel()
self._tstate_lock.acquire()
def _bootstrap_inner(self):
try:
self._set_ident()
self._set_tstate_lock()
self._started.set()
with _active_limbo_lock:
_active[self._ident] = self
del _limbo[self]
if _trace_hook:
_sys.settrace(_trace_hook)
if _profile_hook:
_sys.setprofile(_profile_hook)
try:
self.run()
except SystemExit:
pass
except:
# If sys.stderr is no more (most likely from interpreter
# shutdown) use self._stderr. Otherwise still use sys (as in
# _sys) in case sys.stderr was redefined since the creation of
# self.
if _sys and _sys.stderr is not None:
print("Exception in thread %s:\n%s" %
(self.name, _format_exc()), file=self._stderr)
elif self._stderr is not None:
# Do the best job possible w/o a huge amt. of code to
# approximate a traceback (code ideas from
# Lib/traceback.py)
exc_type, exc_value, exc_tb = self._exc_info()
try:
print((
"Exception in thread " + self.name +
" (most likely raised during interpreter shutdown):"), file=self._stderr)
print((
"Traceback (most recent call last):"), file=self._stderr)
while exc_tb:
print((
' File "%s", line %s, in %s' %
(exc_tb.tb_frame.f_code.co_filename,
exc_tb.tb_lineno,
exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
exc_tb = exc_tb.tb_next
print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
# Make sure that exc_tb gets deleted since it is a memory
# hog; deleting everything else is just for thoroughness
finally:
del exc_type, exc_value, exc_tb
finally:
# Prevent a race in
# test_threading.test_no_refcycle_through_target when
# the exception keeps the target alive past when we
# assert that it's dead.
#XXX self._exc_clear()
pass
finally:
with _active_limbo_lock:
try:
# We don't call self._delete() because it also
# grabs _active_limbo_lock.
del _active[get_ident()]
except:
pass
def _stop(self):
# After calling ._stop(), .is_alive() returns False and .join() returns
# immediately. ._tstate_lock must be released before calling ._stop().
#
# Normal case: C code at the end of the thread's life
# (release_sentinel in _threadmodule.c) releases ._tstate_lock, and
# that's detected by our ._wait_for_tstate_lock(), called by .join()
# and .is_alive(). Any number of threads _may_ call ._stop()
# simultaneously (for example, if multiple threads are blocked in
# .join() calls), and they're not serialized. That's harmless -
# they'll just make redundant rebindings of ._is_stopped and
# ._tstate_lock. Obscure: we rebind ._tstate_lock last so that the
# "assert self._is_stopped" in ._wait_for_tstate_lock() always works
# (the assert is executed only if ._tstate_lock is None).
#
# Special case: _main_thread releases ._tstate_lock via this
# module's _shutdown() function.
lock = self._tstate_lock
if lock is not None:
assert not lock.locked()
self._is_stopped = True
self._tstate_lock = None
def _delete(self):
"Remove current thread from the dict of currently running threads."
# Notes about running with _dummy_thread:
#
# Must take care to not raise an exception if _dummy_thread is being
# used (and thus this module is being used as an instance of
# dummy_threading). _dummy_thread.get_ident() always returns -1 since
# there is only one thread if _dummy_thread is being used. Thus
# len(_active) is always <= 1 here, and any Thread instance created
# overwrites the (if any) thread currently registered in _active.
#
# An instance of _MainThread is always created by 'threading'. This
# gets overwritten the instant an instance of Thread is created; both
# threads return -1 from _dummy_thread.get_ident() and thus have the
# same key in the dict. So when the _MainThread instance created by
# 'threading' tries to clean itself up when atexit calls this method
# it gets a KeyError if another Thread instance was created.
#
# This all means that KeyError from trying to delete something from
# _active if dummy_threading is being used is a red herring. But
# since it isn't if dummy_threading is *not* being used then don't
# hide the exception.
try:
with _active_limbo_lock:
del _active[get_ident()]
# There must not be any python code between the previous line
# and after the lock is released. Otherwise a tracing function
# could try to acquire the lock again in the same thread, (in
# current_thread()), and would block.
except KeyError:
if 'dummy_threading' not in _sys.modules:
raise
def join(self, timeout=None):
"""Wait until the thread terminates.
This blocks the calling thread until the thread whose join() method is
called terminates -- either normally or through an unhandled exception
or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As join() always returns None, you must call
isAlive() after join() to decide whether a timeout happened -- if the
thread is still alive, the join() call timed out.
When the timeout argument is not present or None, the operation will
block until the thread terminates.
A thread can be join()ed many times.
join() raises a RuntimeError if an attempt is made to join the current
thread as that would cause a deadlock. It is also an error to join() a
thread before it has been started and attempts to do so raises the same
exception.
"""
if not self._initialized:
raise RuntimeError("Thread.__init__() not called")
if not self._started.is_set():
raise RuntimeError("cannot join thread before it is started")
if self is current_thread():
raise RuntimeError("cannot join current thread")
if timeout is None:
self._wait_for_tstate_lock()
else:
# the behavior of a negative timeout isn't documented, but
# historically .join(timeout=x) for x<0 has acted as if timeout=0
self._wait_for_tstate_lock(timeout=max(timeout, 0))
def _wait_for_tstate_lock(self, block=True, timeout=-1):
# Issue #18808: wait for the thread state to be gone.
# At the end of the thread's life, after all knowledge of the thread
# is removed from C data structures, C code releases our _tstate_lock.
# This method passes its arguments to _tstate_lock.aquire().
# If the lock is acquired, the C code is done, and self._stop() is
# called. That sets ._is_stopped to True, and ._tstate_lock to None.
lock = self._tstate_lock
if lock is None: # already determined that the C code is done
assert self._is_stopped
elif lock.acquire(block, timeout):
lock.release()
self._stop()
@property
def name(self):
"""A string used for identification purposes only.
It has no semantics. Multiple threads may be given the same name. The
initial name is set by the constructor.
"""
assert self._initialized, "Thread.__init__() not called"
return self._name
@name.setter
def name(self, name):
assert self._initialized, "Thread.__init__() not called"
self._name = str(name)
@property
def ident(self):
"""Thread identifier of this thread or None if it has not been started.
This is a nonzero integer. See the thread.get_ident() function. Thread
identifiers may be recycled when a thread exits and another thread is
created. The identifier is available even after the thread has exited.
"""
assert self._initialized, "Thread.__init__() not called"
return self._ident
def is_alive(self):
"""Return whether the thread is alive.
This method returns True just before the run() method starts until just
after the run() method terminates. The module function enumerate()
returns a list of all alive threads.
"""
assert self._initialized, "Thread.__init__() not called"
if self._is_stopped or not self._started.is_set():
return False
self._wait_for_tstate_lock(False)
return not self._is_stopped
isAlive = is_alive
@property
def daemon(self):
"""A boolean value indicating whether this thread is a daemon thread.
This must be set before start() is called, otherwise RuntimeError is
raised. Its initial value is inherited from the creating thread; the
main thread is not a daemon thread and therefore all threads created in
the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are
left.
"""
assert self._initialized, "Thread.__init__() not called"
return self._daemonic
@daemon.setter
def daemon(self, daemonic):
if not self._initialized:
raise RuntimeError("Thread.__init__() not called")
if self._started.is_set():
raise RuntimeError("cannot set daemon status of active thread")
self._daemonic = daemonic
def isDaemon(self):
return self.daemon
def setDaemon(self, daemonic):
self.daemon = daemonic
def getName(self):
return self.name
def setName(self, name):
self.name = name
# The timer class was contributed by Itamar Shtull-Trauring
class Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=None, kwargs=None)
t.start()
t.cancel() # stop the timer's action if it's still waiting
"""
def __init__(self, interval, function, args=None, kwargs=None):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args if args is not None else []
self.kwargs = kwargs if kwargs is not None else {}
self.finished = Event()
def cancel(self):
"""Stop the timer if it hasn't finished yet."""
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
# Special thread class to represent the main thread
# This is garbage collected through an exit handler
class _MainThread(Thread):
def __init__(self):
Thread.__init__(self, name="MainThread", daemon=False)
self._set_tstate_lock()
self._started.set()
self._set_ident()
with _active_limbo_lock:
_active[self._ident] = self
# Dummy thread class to represent threads not started here.
# These aren't garbage collected when they die, nor can they be waited for.
# If they invoke anything in threading.py that calls current_thread(), they
# leave an entry in the _active dict forever after.
# Their purpose is to return *something* from current_thread().
# They are marked as daemon threads so we won't wait for them
# when we exit (conform previous semantics).
class _DummyThread(Thread):
def __init__(self):
Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
self._started.set()
self._set_ident()
with _active_limbo_lock:
_active[self._ident] = self
def _stop(self):
pass
def join(self, timeout=None):
assert False, "cannot join a dummy thread"
# Global API functions
def current_thread():
"""Return the current Thread object, corresponding to the caller's thread of control.
If the caller's thread of control was not created through the threading
module, a dummy thread object with limited functionality is returned.
"""
try:
return _active[get_ident()]
except KeyError:
return _DummyThread()
currentThread = current_thread
def active_count():
"""Return the number of Thread objects currently alive.
The returned count is equal to the length of the list returned by
enumerate().
"""
with _active_limbo_lock:
return len(_active) + len(_limbo)
activeCount = active_count
def _enumerate():
# Same as enumerate(), but without the lock. Internal use only.
return list(_active.values()) + list(_limbo.values())
def enumerate():
"""Return a list of all Thread objects currently alive.
The list includes daemonic threads, dummy thread objects created by
current_thread(), and the main thread. It excludes terminated threads and
threads that have not yet been started.
"""
with _active_limbo_lock:
return list(_active.values()) + list(_limbo.values())
from _thread import stack_size
# Create the main thread object,
# and make it available for the interpreter
# (Py_Main) as threading._shutdown.
_main_thread = _MainThread()
def _shutdown():
# Obscure: other threads may be waiting to join _main_thread. That's
# dubious, but some code does it. We can't wait for C code to release
# the main thread's tstate_lock - that won't happen until the interpreter
# is nearly dead. So we release it here. Note that just calling _stop()
# isn't enough: other threads may already be waiting on _tstate_lock.
tlock = _main_thread._tstate_lock
# The main thread isn't finished yet, so its thread state lock can't have
# been released.
assert tlock is not None
assert tlock.locked()
tlock.release()
_main_thread._stop()
t = _pickSomeNonDaemonThread()
while t:
t.join()
t = _pickSomeNonDaemonThread()
_main_thread._delete()
def _pickSomeNonDaemonThread():
for t in enumerate():
if not t.daemon and t.is_alive():
return t
return None
def main_thread():
"""Return the main thread object.
In normal conditions, the main thread is the thread from which the
Python interpreter was started.
"""
return _main_thread
# get thread-local implementation, either from the thread
# module, or from the python fallback
try:
from _thread import _local as local
except ImportError:
from _threading_local import local
def _after_fork():
# This function is called by Python/ceval.c:PyEval_ReInitThreads which
# is called from PyOS_AfterFork. Here we cleanup threading module state
# that should not exist after a fork.
# Reset _active_limbo_lock, in case we forked while the lock was held
# by another (non-forked) thread. http://bugs.python.org/issue874900
global _active_limbo_lock, _main_thread
_active_limbo_lock = _allocate_lock()
# fork() only copied the current thread; clear references to others.
new_active = {}
current = current_thread()
_main_thread = current
with _active_limbo_lock:
# Dangling thread instances must still have their locks reset,
# because someone may join() them.
threads = set(_enumerate())
threads.update(_dangling)
for thread in threads:
# Any lock/condition variable may be currently locked or in an
# invalid state, so we reinitialize them.
if thread is current:
# There is only one active thread. We reset the ident to
# its new value since it can have changed.
thread._reset_internal_locks(True)
ident = get_ident()
thread._ident = ident
new_active[ident] = thread
else:
# All the others are already stopped.
thread._reset_internal_locks(False)
thread._stop()
_limbo.clear()
_active.clear()
_active.update(new_active)
assert len(_active) == 1
| __repr__ |
gdb.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
use trans::common::{C_bytes, CrateContext};
use trans::declare;
use trans::type_::Type;
use session::config::NoDebugInfo;
use std::ffi::CString;
use std::ptr;
use syntax::attr;
/// Inserts a side-effect free instruction sequence that makes sure that the
/// .debug_gdb_scripts global is referenced, so it isn't removed by the linker.
pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext) {
if needs_gdb_debug_scripts_section(ccx) {
let empty = CString::new("").unwrap();
let gdb_debug_scripts_section_global =
get_or_insert_gdb_debug_scripts_section_global(ccx);
unsafe {
let volative_load_instruction =
llvm::LLVMBuildLoad(ccx.raw_builder(),
gdb_debug_scripts_section_global,
empty.as_ptr());
llvm::LLVMSetVolatile(volative_load_instruction, llvm::True);
}
}
}
/// Allocates the global variable responsible for the .debug_gdb_scripts binary
/// section.
pub fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext)
-> llvm::ValueRef {
let section_var_name = "__rustc_debug_gdb_scripts_section__";
let section_var = unsafe {
llvm::LLVMGetNamedGlobal(ccx.llmod(),
section_var_name.as_ptr() as *const _)
};
if section_var == ptr::null_mut() {
let section_name = b".debug_gdb_scripts\0";
let section_contents = b"\x01gdb_load_rust_pretty_printers.py\0";
unsafe {
let llvm_type = Type::array(&Type::i8(ccx),
section_contents.len() as u64);
let section_var = declare::define_global(ccx, section_var_name,
llvm_type).unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` is already defined", section_var_name))
});
llvm::LLVMSetSection(section_var, section_name.as_ptr() as *const _);
llvm::LLVMSetInitializer(section_var, C_bytes(ccx, section_contents));
llvm::LLVMSetGlobalConstant(section_var, llvm::True);
llvm::LLVMSetUnnamedAddr(section_var, llvm::True);
llvm::SetLinkage(section_var, llvm::Linkage::LinkOnceODRLinkage);
// This should make sure that the whole section is not larger than
// the string it contains. Otherwise we get a warning from GDB.
llvm::LLVMSetAlignment(section_var, 1);
section_var
}
} else {
section_var
}
}
pub fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
let omit_gdb_pretty_printer_section =
attr::contains_name(&ccx.tcx()
.map
.krate()
.attrs,
"omit_gdb_pretty_printer_section");
!omit_gdb_pretty_printer_section &&
!ccx.sess().target.target.options.is_like_osx &&
!ccx.sess().target.target.options.is_like_windows &&
ccx.sess().opts.debuginfo != NoDebugInfo
} | // .debug_gdb_scripts binary section.
use llvm;
use llvm::ValueRef; |
test_ntpx.py | import pytest
import os
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from pathlib import Path
from dselib.context import DSEContext
from dselib.ntpx import NTPX
def context(varfile=None):
"""returns the DSE context object for this script."""
try:
myself = __file__
except NameError:
myself = sys.argv[0]
return DSEContext(myself, varfile)
me = context('test_ntpx')
def test_1():
a = NTPX('.')
b = NTPX('./fu')
c = NTPX('./fu.bar')
d = NTPX('fu.bar')
e = NTPX('/fu.bar')
def | (input, ntobj, cwd):
# logger.info(f"{cwd=}::{str(cwd)=}::{os.sep=}::{str(cwd.parent)[2 if os.name == 'nt' else 0:]}")
suffix = lambda x: '' if str(x.parent)[2 if os.name == 'nt' else 0:] == os.sep else os.sep
path = lambda x: str(x.parent)[2 if os.name == 'nt' else 0:] + suffix(x)
# logger.info(f"{cwd=}::{suffix(cwd)=}::justpath={path(cwd)=}")
# the path_suffix is os.sep unless we are already at the root directory
# logger.info(f"{os.path.split(cwd)=}::{str(cwd.parent)=}")
path_suffix = '' if str(cwd.parent)[2 if os.name == 'nt' else 0:] == os.sep else os.sep
assert ntobj.format('dpnx') == str(cwd)
assert ntobj.format('d') == cwd.drive
assert ntobj.format('p') == path(cwd) #str(cwd.parent)[2 if os.name == 'nt' else 0:] + path_suffix
assert ntobj.format('n') == cwd.stem
assert ntobj.format('x') == cwd.suffix
assert ntobj.drive == cwd.drive
assert ntobj.path == path(cwd) #str(cwd.parent)[2 if os.name == 'nt' else 0:] + path_suffix
assert ntobj.name == cwd.stem
assert ntobj.ext == cwd.suffix
# logger.info(f"ntobj.all::{ntobj.all()[:5]}")
# logger.info(f"otherexpr::{(str(cwd), cwd.drive, path(cwd), cwd.stem, cwd.suffix)}")
# assert ntobj.all()[:5] == (str(cwd), cwd.drive, path(cwd), cwd.stem, cwd.suffix)
assert ntobj.all()[:5] == (str(cwd), cwd.drive, path(cwd), cwd.stem, cwd.suffix)
assert ntobj.full == cwd
# assert ntobj == str(cwd) # C:\Users\user\dse\test == C:\\Users\\user\\dse\\test
logger.info(f"NTPX('{input}') has passed. fully qualified is {ntobj.full}. formatted is {ntobj.format('dpnx')}")
check_it('.', a, Path('.').resolve())
check_it('./fu', b, Path('./fu').resolve())
check_it('./fu.bar', c, Path('fu.bar').resolve())
check_it('fu.bar', d, Path('fu.bar').resolve())
check_it('/fu.bar', e, Path('/fu.bar').resolve())
| check_it |
trainer.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import itertools
import time
from contextlib import ExitStack as contextlib_ExitStack
from typing import Any, Iterable, List, Optional, Tuple
import torch
from pytext.common.constants import BatchContext, Stage
from pytext.config import PyTextConfig
from pytext.config.component import (
Component,
ComponentType,
create_optimizer,
create_scheduler,
create_sparsifier,
)
from pytext.config.pytext_config import ConfigBase
from pytext.data.data_handler import BatchIterator
from pytext.metric_reporters import MetricReporter
from pytext.models.distributed_model import DistributedModel
from pytext.models.model import Model
from pytext.optimizer import Adam, Optimizer, learning_rates
from pytext.optimizer.scheduler import Scheduler
from pytext.optimizer.sparsifier import Sparsifier
from pytext.task.serialize import save
from pytext.trainers.training_state import TrainingState
from pytext.utils import cuda, precision, timing
class TrainerBase(Component):
__COMPONENT_TYPE__ = ComponentType.TRAINER
def cycle(iterator: Iterable[Any]) -> Iterable[Any]:
"""Like itertools.cycle, but will call iter on the original iterable instead.
This limits it to not be able to run on say raw generators, but also doesn't
store a copy of the iterable in memory for repetition."""
while True:
yield from iterator
def maybe_accumulate_gradients(exit_stack, model, index, sample_size):
# index == sample_size - 1 represents the last backward pass
if (
cuda.DISTRIBUTED_WORLD_SIZE > 1
and hasattr(model, "no_sync")
and index < sample_size - 1
):
"""
Whenever *samples* contains more than one mini-batch (e.g sample_size > 1),
we want to accumulate gradients locally and only call all-reduce in the
last backwards pass.
"""
exit_stack.enter_context(model.no_sync())
if precision._FP16_ENABLED and index < sample_size - 1:
"""
Whenever *samples* contains more than one mini-batch (e.g sample_size > 1),
we want to accumulate gradients in FP16 parameters (e.g delay unscale)
and only unscale to FP32 parameters after the last backward pass.
"""
exit_stack.enter_context(precision.delay_unscale())
class Trainer(TrainerBase):
"""
Base Trainer class that provide ways to
1 Train model, compute metrics against eval set and use the metrics for
model selection.
2 Test trained model, compute and publish metrics against a blind test set.
Attributes:
epochs (int): Training epochs
early_stop_after (int): Stop after how many epochs when the eval metric
is not improving
max_clip_norm (Optional[float]): Clip gradient norm if set
report_train_metrics (bool): Whether metrics on training data should be
computed and reported.
target_time_limit_seconds (float): Target time limit for training in seconds. If
the expected time to train another epoch exceeds this limit, stop training.
"""
class Config(ConfigBase):
#: Training epochs
epochs: int = 10
#: Stop after how many epochs when the eval metric is not improving
early_stop_after: int = 0
#: Clip gradient norm if set
max_clip_norm: Optional[float] = None
#: Whether metrics on training data should be computed and reported.
report_train_metrics: bool = True
#: Target time limit for training, default (None) to no time limit.
target_time_limit_seconds: Optional[int] = None
#: Whether to do evaluation and model selection based on it.
do_eval: bool = True
#: Number of samples for logging training progress.
num_samples_to_log_progress: int = 1000
#: Number of forward & backward per batch before update gradients, the
#: actual_batch_size = batch_size x num_accumulated_batches
num_accumulated_batches: int = 1
#: Define epoch as a fixed number of batches. Subsequent epochs will continue
#: to iterate through the data, cycling through it when they reach the end.
#: If not set, use exactly one pass through the dataset as one epoch.
#: This configuration only affects the train epochs, test and eval
#: will always test their entire datasets.
num_batches_per_epoch: Optional[int] = None
#: config for optimizer, used in parameter update
optimizer: Optimizer.Config = Adam.Config()
scheduler: Optional[Scheduler.Config] = None
sparsifier: Optional[Sparsifier.Config] = None
def __init__(self, config: Config, model: torch.nn.Module):
if config.early_stop_after > 0:
assert config.do_eval, "can't do early stopping when not running evalution"
optimizer: torch.optim.Optimizer = create_optimizer(config.optimizer, model)
self.scheduler: torch.optim.lr_scheduler = (
create_scheduler(config.scheduler, optimizer)
if config.scheduler
else Scheduler()
)
self.sparsifier: Sparsifier = (
create_sparsifier(config.sparsifier) if config.sparsifier else Sparsifier()
)
model, self.optimizer = precision.initialize(model, optimizer)
self.config = config
@classmethod
def from_config(cls, config: Config, model: torch.nn.Module, *args, **kwargs):
return cls(config, model)
@timing.time("Trainer.test")
def test(self, test_iter, model, metric_reporter: MetricReporter):
state = TrainingState(stage=Stage.TEST, model=model, epoch=1)
if cuda.CUDA_ENABLED:
state.model.cuda()
state.model.eval()
with torch.no_grad():
return self.run_epoch(state, test_iter, metric_reporter)
@timing.time("pre-training")
def set_up_training(self, state: TrainingState, training_data: BatchIterator):
if cuda.CUDA_ENABLED:
state.model.cuda()
state.scheduler.prepare(training_data, self.config.epochs)
if cuda.DISTRIBUTED_WORLD_SIZE > 1:
device_id = torch.cuda.current_device()
state.model = DistributedModel(
module=state.model,
device_ids=[device_id],
output_device=device_id,
broadcast_buffers=False,
find_unused_parameters=state.model.find_unused_parameters,
)
state.start_time = time.time()
if self.config.num_batches_per_epoch:
# Set the training_data iterator to cycle, so it will never run out,
# but rather after reaching the end will loop back to the beginning.
training_data = cycle(training_data)
return training_data
@timing.time("zero gradients")
def zero_grads(self, state):
if state.stage != Stage.TRAIN:
return
state.optimizer.zero_grad()
@timing.time("backprop")
def backprop(self, state, loss):
if state.stage != Stage.TRAIN:
return
with timing.time("loss.backward"):
precision.backward(state.optimizer, loss)
@timing.time("optimizer")
def optimizer_step(self, state):
if state.stage != Stage.TRAIN:
return
state.scheduler.step_batch()
if self.config.max_clip_norm is not None:
grad_norm = precision.clip_grad_norm(
state.model, state.optimizer, self.config.max_clip_norm
)
else:
grad_norm = None
with timing.time("optimizer.step"):
state.optimizer.step()
state.step_counter += 1
# grad_norm could be used to check grads sync in distributed training
return grad_norm
@timing.time("sparsifier")
def sparsification_step(self, state):
# sparsification only if sparifier is used
if not self.config.sparsifier:
return
if state.stage != Stage.TRAIN:
return
if state.sparsifier.sparsification_condition(state):
state.sparsifier.sparsify(state)
if state.rank == 0:
current_sparsity = state.sparsifier.get_current_sparsity(state.model)
print(f"sparsity in the model: {current_sparsity}")
def continue_training(self, state: TrainingState) -> bool:
# Are we done?
|
def update_best_model(
self, state: TrainingState, train_config: PyTextConfig, eval_metric
):
# This should be updated by all workers so they agree on when to stop training
# when `early_stop_after` is specified.
state.epochs_since_last_improvement = 0
state.best_model_metric = eval_metric
print(f"Found a better model!")
# Only one worker should save checkpoints
if state.rank != 0:
return
model_state = state.model.state_dict()
# save to cpu to avoid multiple model copies in gpu memory
if cuda.CUDA_ENABLED:
for key, parameter in model_state.items():
model_state[key] = parameter.cpu()
state.best_model_state = model_state
@timing.time("save checkpoint")
def save_checkpoint(self, state: TrainingState, train_config: PyTextConfig) -> str:
# Only one worker should save checkpoints
if state.rank != 0:
return
if train_config.save_module_checkpoints or train_config.save_all_checkpoints:
# saves per-epoch sub-modules when save_all_checkpoints or
# save_module_checkpoints is enabled
state.model.save_modules(
base_path=train_config.modules_save_dir, suffix=f"-ep{state.epoch}"
)
if state.epochs_since_last_improvement == 0:
# state.epochs_since_last_improvement == 0 means found a better
# model in current epoch, thus update best model's sub-modules
state.model.save_modules(base_path=train_config.modules_save_dir)
# next to add new config and implementation of frequency on checkpointing
if train_config.save_all_checkpoints:
return save(
config=train_config,
model=state.model,
meta=None,
tensorizers=None,
training_state=state,
identifier=str(state.epoch),
)
def load_best_model(self, state: TrainingState):
if cuda.CUDA_ENABLED:
# Move current model to CPU to avoid multiple models in GPU memory
state.model.cpu()
state.model.load_state_dict(
{k: v.cuda() for k, v in state.best_model_state.items()}
)
# Move model back to GPU
state.model.cuda()
else:
state.model.load_state_dict(state.best_model_state)
def train(
self,
training_data: BatchIterator,
eval_data: BatchIterator,
model: Model,
metric_reporter: MetricReporter,
train_config: PyTextConfig,
rank: int = 0,
) -> Tuple[torch.nn.Module, Any]:
"""
Train and eval a model, the model states will be modified.
Args:
train_iter (BatchIterator): batch iterator of training data
eval_iter (BatchIterator): batch iterator of evaluation data
model (Model): model to be trained
metric_reporter (MetricReporter): compute metric based on training
output and report results to console, file.. etc
train_config (PyTextConfig): training config
training_result (Optional): only meaningful for Hogwild training. default
is None
rank (int): only used in distributed training, the rank of the current
training thread, evaluation will only be done in rank 0
Returns:
model, best_metric: the trained model together with the best metric
"""
state = TrainingState(
model=model,
optimizer=self.optimizer,
scheduler=self.scheduler,
sparsifier=self.sparsifier,
rank=rank,
)
return self.train_from_state(
state, training_data, eval_data, metric_reporter, train_config
)
@timing.time("Trainer.train_from_state")
def train_from_state(
self,
state: TrainingState,
training_data: BatchIterator,
eval_data: BatchIterator,
metric_reporter: MetricReporter,
train_config: PyTextConfig,
) -> Tuple[torch.nn.Module, Any]:
"""
Train and eval a model from a given training state will be modified.
This function iterates epochs specified in config, and for each epoch do:
1. Train model using training data, aggregate and report training results
2. Adjust learning rate if scheduler is specified
3. Evaluate model using evaluation data
4. Calculate metrics based on evaluation results and select best model
Args:
training_state (TrainingState): contrains stateful information to be
able to restore a training job
train_iter (BatchIterator): batch iterator of training data
eval_iter (BatchIterator): batch iterator of evaluation data
model (Model): model to be trained
metric_reporter (MetricReporter): compute metric based on training
output and report results to console, file.. etc
train_config (PyTextConfig): training config
Returns:
model, best_metric: the trained model together with the best metric
"""
training_data = self.set_up_training(state, training_data)
model = state.model
rank = state.rank
trainable_params = sum(
p.numel() for p in state.model.parameters() if p.requires_grad
)
print(f"Num trainable parameters: {trainable_params}")
while self.continue_training(state):
state.epoch += 1
state.epochs_since_last_improvement += 1
lrs = learning_rates(state.optimizer)
print(f"\nWorker {state.rank} starting epoch {state.epoch}")
print(f"Learning rate(s): {', '.join(map(str, lrs))}")
with timing.time("train epoch"):
state.stage = Stage.TRAIN
state.model.train()
print(f"start training epoch {state.epoch}")
epoch_data = training_data
if self.config.num_batches_per_epoch:
# We want to limit the number of batches in the epoch;
# equivalent to epoch_data[:num_batches_per_epoch] for iterators.
# In this case we set the training data iterator to cycle earlier
# in the training process, so when it reaches the end it will
# loop back to the beginning.
epoch_data = itertools.islice(
epoch_data, self.config.num_batches_per_epoch
)
self.run_epoch(state, epoch_data, metric_reporter)
if not self.config.do_eval:
continue
with timing.time("eval epoch"):
state.stage = Stage.EVAL
model.eval(Stage.EVAL)
print(f"start evaluating epoch {state.epoch}")
with torch.no_grad():
eval_metric = self.run_epoch(state, eval_data, metric_reporter)
# Step the learning rate scheduler(s)
assert eval_metric is not None
state.scheduler.step_epoch(
metrics=metric_reporter.get_model_select_metric(eval_metric),
epoch=state.epoch,
)
# Did we train a better model?
better_model = metric_reporter.compare_metric(
eval_metric, state.best_model_metric
)
if better_model:
self.update_best_model(state, train_config, eval_metric)
if better_model or train_config.save_all_checkpoints:
self.save_checkpoint(state, train_config)
if self.optimizer.finalize():
state.stage = Stage.EVAL
model.eval(Stage.EVAL)
print(f"start evaluating finalized state")
with torch.no_grad():
eval_metric = self.run_epoch(state, eval_data, metric_reporter)
better_model = metric_reporter.compare_metric(
eval_metric, state.best_model_metric
)
if better_model:
self.update_best_model(state, train_config, eval_metric)
if better_model or train_config.save_all_checkpoints:
self.save_checkpoint(state, train_config)
# Only bother loading the best model for master worker
if rank == 0 and state.best_model_state is not None:
self.load_best_model(state)
return state.model, state.best_model_metric
@timing.report_snapshot
def run_epoch(
self, state: TrainingState, data: BatchIterator, metric_reporter: MetricReporter
):
# This method is due for some refactoring, pushing it off because it interacts
# with the metric reporter too much. Much of the logic here either changes in
# the NewTaskTrainer or should change with a better metric reporter design.
report_metric = state.stage != Stage.TRAIN or self.config.report_train_metrics
model = state.model
samples = []
"""
Sometimes, a batch of inputs is too large to fit into GPU, which has to
be split into several micro-batches. However, to improve efficiency,
it would be helpful to only apply params/gradients sync at original batch
boundaries instead of micro-batch boundaries.
num_accumulated_batches specified the number of accumulating gradients
locally before sync gradients, total training_batch_size =
train_batch_size x num_accumulated_batches and it will improve the system
performance by reduce the total network transfer bytes.
"""
for sample in enumerate(data):
samples.append(sample)
if (
state.stage != Stage.TRAIN
or len(samples) == self.config.num_accumulated_batches
):
self.run_step(samples, state, metric_reporter, report_metric)
samples = []
if samples:
self.run_step(samples, state, metric_reporter, report_metric)
samples = []
metrics = None
if report_metric:
with timing.time("report metrics"):
metrics = metric_reporter.report_metric(
model, state.stage, state.epoch, print_to_channels=(state.rank == 0)
)
else:
metric_reporter._reset()
return metrics
@timing.time("run_step")
def run_step(
self,
samples: List[Any],
state: TrainingState,
metric_reporter: MetricReporter,
report_metric: bool,
):
sample_size = len(samples)
assert sample_size <= self.config.num_accumulated_batches
model = state.model
self.zero_grads(state)
for idx, (batch_id, (inputs, targets, context)) in enumerate(samples):
with contextlib_ExitStack() as exit_stack:
maybe_accumulate_gradients(exit_stack, model, idx, sample_size)
# pass context to model to use in forward call if needed
model.contextualize(context)
with timing.time("model.forward"):
logits = model(*inputs)
with timing.time("compute loss"):
loss = precision.maybe_float(
model.get_loss(logits, targets, context)
)
if BatchContext.IGNORE_LOSS in context:
loss *= 0
elif sample_size > 1:
# gradients averaged per batch and accumulated across samples.
# divide sample_size to let gradients averaged per example
loss = loss / sample_size
self.backprop(state, loss)
if report_metric:
with timing.time("get pred"):
preds, scores = model.get_pred(
logits, targets, context, state.stage, *inputs
)
with timing.time("add metrics"):
metric_reporter.add_batch_stats(
batch_id, preds, targets, scores, loss.item(), inputs, **context
)
if batch_id % self.config.num_samples_to_log_progress == 0:
print(
f"Running batch {batch_id} for epoch {state.epoch} in {state.stage} stage",
flush=True,
)
# update gradients after len(samples) forward & backward
self.optimizer_step(state)
self.sparsification_step(state)
class TaskTrainer(Trainer):
__EXPANSIBLE__ = True
class Config(Trainer.Config):
"""Make mypy happy"""
@timing.time("run_step")
def run_step(
self,
samples: List[Any],
state: TrainingState,
metric_reporter: MetricReporter,
report_metric: bool,
):
"""Our run_step is a bit different, because we're wrapping the model forward
call with model.train_batch, which arranges tensors and gets loss, etc.
Whenever "samples" contains more than one mini-batch (sample_size > 1),
we want to accumulate gradients locally and only call all-reduce in the
last backwards pass.
"""
sample_size = len(samples)
assert sample_size <= self.config.num_accumulated_batches
model = state.model
self.zero_grads(state)
for idx, (batch_id, (raw_batch, batch)) in enumerate(samples):
with contextlib_ExitStack() as exit_stack:
# enter ddp no_sync context and fp16 delay_scale context if needed
maybe_accumulate_gradients(exit_stack, model, idx, sample_size)
with timing.time("model.train_batch"):
loss, metric_data = model.train_batch(model, batch, state)
if sample_size > 1:
# gradients averaged per batch and accumulated across samples.
# divide sample_size to let gradients averaged per example
loss = loss / sample_size
self.backprop(state, loss)
if report_metric:
with timing.time("add metrics"):
metric_reporter.add_batch_stats(
batch_id,
*metric_data,
# TODO merge this step into add_batch_stats once all data
# migration is done
**metric_reporter.batch_context(raw_batch, batch),
)
if batch_id % self.config.num_samples_to_log_progress == 0:
metric_reporter.report_realtime_metric(state.stage)
# update gradients after #len(samples) forward & backward
self.optimizer_step(state)
self.sparsification_step(state)
def _prepare_scheduler(self, training_batches, scheduler=None):
"""Batch based schedulers require knowing the number of batches in
the data. We're not supporting that yet with the Data api, need to figure out
how to expose this info or restructure batch-based schedulers to not need it."""
if scheduler.batch_based_schedulers:
raise Exception("New tasks don't yet support batch-based scheduling")
return scheduler
| if state.epoch >= self.config.epochs:
return False
# Check whether the model has improved recently enough
# Only do this if we're bothering to evaluate the model
if self.config.do_eval and state.epochs_since_last_improvement >= (
self.config.early_stop_after or float("inf")
):
print(
f"Worker {state.rank}: Eval metric hasn't changed for "
+ f"{state.epochs_since_last_improvement} epochs. Stopping now."
)
return False
# Check whether we think the next epoch will put us over the configured
# time limit.
epochs_run = state.epoch + 1
time_elapsed = time.time() - state.start_time
mean_epoch_time = time_elapsed / epochs_run
expected_next_epoch_time = time_elapsed + mean_epoch_time
target_time_limit = (
float("inf")
if self.config.target_time_limit_seconds is None
else self.config.target_time_limit_seconds
)
if expected_next_epoch_time > target_time_limit:
print(
f"Worker {state.rank}: Stopping training after {epochs_run} epochs "
f"and {int(time_elapsed)} seconds, due to the target max training "
f"time of {self.config.target_time_limit_seconds} seconds."
)
return False
return True |
get-data-layout.component.state.ts | /**
* Human Cell Atlas
* https://www.humancellatlas.org/
*
* State backing get data layout component. |
// App dependencies
import { Facet } from "../../facet/facet.model";
import { FileSummary } from "../../file-summary/file-summary.model";
import { SearchTerm } from "../../search/search-term.model";
export interface GetDataLayoutComponentState {
filesFacets?: Facet[];
fileSummary?: FileSummary;
loaded: boolean;
selectedSearchTerms?: SearchTerm[];
} | */ |
logos.py | #!/usr/bin/env python
'''
The logos module provides a kind of decision making process center.
It has hints of imagination and logic.
Copyright (c) 2011 Joseph Lewis <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
import threading
import time
import pavlov
import maslow
import copy
__version__ = 1.0
__author__ = "Joseph Lewis <[email protected]>"
DEBUGGING = False
class Mode:
'''An interface for building modes for the mind to operate in.
Each mode has a specific Need that triggers it i.e. Hunger mode
would be triggered by the Need "Hunger". Modes are added to a
Mind class. When the Mind updates it checks for the most pressing
Need, then triggers the mode with the same name as the need. The
mode then is called periodically by the brain until it sets its
done value to True, the mind then moves to the next most pressing
need. If the done flag is not set to True this need will continue
to execute until another one becomes more pressing.
If however a more pressing need comes up, like a Basic Need, while
a higher one is being fufilled the higher need will be destroyed
in favor of the lesser one.
The variables available to you are:
done -- Is this Mode done executing? Set to True to end.
my_need -- An instance of the need that is associated with this
mode.
my_map -- An instance of the mapper.Grid that the Actor belonging
to the Mind of this Need has.
name -- The name of this mode, should be the same as a need, when
the need with the same name arises this mode goes in to
effect.
'''
done = False
my_need = None
my_map = None
my_actor = None
name = "Override with the same name as a need so the two are\
associated"
def __init__(self, need, my_map, my_actor):
self.my_need = need
self.my_map = my_map
self.my_actor = my_actor
def make_move(self):
'''Override this function with one that will make a move for
the Actor.'''
raise NotImplementedError("make_move was not overriden for the mode: %s" % (self.name))
def get_closest(self, itemlist, quick=False):
'''Gets the path to the closest item in itemlist. Returns
none if none of the given items were in the known world.'''
here = self.my_actor.view_terrain()
closest = []
for i in itemlist:
j = self.my_map.find_closest(i, here, quick)
if j != (None, None):
closestdict.append(j)
try:
return closest.sort()[0]
except IndexError:
return None
def | ( mode_name ):
'''Returns a simple mode class with the given mode_name that
searches for an item and goes to it.'''
class sag_mode( Mode ):
path_to_resource = None
done = False
name = mode_name
item = ""
def make_move(self):
#Get the path to item the first time.
if self.path_to_resource == None:
pr = self.my_actor.response_network.lookup_association(self.name)
self.potential_resource = self.my_actor.world.item_event_interface.exists( pr )
dist, closest, item = self.my_actor.internal_map.find_closest_list(self.potential_resource, self.my_actor.view_terrain())
if closest:
self.item = item
self.path_to_resource = self.my_actor.internal_map.path_to(self.my_actor.view_terrain(), closest)
else:
self.done = True
else:
if self.my_actor.can_move:
try:
mc = self.path_to_resource.pop(0)
self.my_actor.move_to_cell(mc)
except AssertionError, e: #The path is obstructed, find a new one.
self.path_to_resource = None
except IndexError: #We are here, interact with the item that called this.
self.my_actor.interact(self.item)
self.done = True
return sag_mode
def quick_search_and_go( mode_names, mind_instance ):
'''Fills the given mind with search_and_go style modes for
the given mode_names. i.e. quick_search_and_go(['food','water'], <mindinstance>)
would add basic food and water search capabilities to your mind.
'''
for item in mode_names:
mind_instance.append( search_and_go_mode( item ) )
class ExploreMode( Mode ):
items_here = []
done = False #Continue forever
name = "explore"
lastcell = None
def __init__(self, need, my_map, my_actor):
#Explore all items here first.
self.items_here = copy.deepcopy(my_actor.view_terrain().items)
Mode.__init__(self, need, my_map, my_actor)
def make_move(self):
c = None #The current cell.
#If we have played with all the items here just move on.
if not self.items_here:
while self.my_actor.can_move:
try:
thiscell = self.my_actor.view_terrain()
c = self.my_actor.world.terrain.random_accessible_neighbor(thiscell,self.lastcell)
self.my_actor.move_to_cell(c)
self.lastcell = thiscell
except AssertionError:
continue #The cell given was not accessible, try again.
except RuntimeWarning:
pass #The actor just moved.
self.items_here = copy.deepcopy(c.items)
else:
while self.items_here:
self.my_actor.interact(self.items_here.pop())
class Mind( threading.Thread ):
'''The Mind reads information from the given maslow.Needs class,
decides the most important thing to do and acts on it using its
owner's body.
'''
_awake = True
current_need = None
modes = [ExploreMode]
def __init__(self, needs, owner, update_time=0.1, autostart=True):
'''Initializes the brain!
Paramaters:
needs -- An instance of maslow.Needs that the mind uses to
decide what mode to enter. (maslow.Needs)
owner -- The instance of world.Actor whose mind this is, used
in moving around and such. (world.Actor)
update_time -- The amount of time to wait between brain cycles
can be a function or float or int. If it is a
function the function should either wait for a
certain amount of time then return 0 or return
the number of seconds to wait.
Default: 0.1 (Function, float, int)
autostart -- Should the mind start as soon as it is
instanciated? If not it will just sit there like
a cold dead organ until its thread is started
using the start() function.
Default: True (boolean)
'''
self.needs = needs
self.owner = owner
self.update_time = update_time
threading.Thread.__init__(self)
#Start the thread automagically if desired.
if autostart:
self.start()
def append(self, item):
'''Add a Mode to the Mind.'''
self.modes.append(item)
def __getitem__(self, key):
'''Emulates a list or dictionary, called with the name of
the Mode. Raises IndexError if not found.'''
#Check for ints
if isinstance(key, int):
return self.modes[key]
#Check for strings and other ojbects
for e in self.modes:
if e.name == key:
return e
#else raise error
raise IndexError("%s is not a valid Mode!" % (str(key)))
def __len__(self):
'''Returns the number of modes.'''
return len(self.modes)
def run(self):
#Make sure awake is true before we start lest the developer
#tries to sleep then re-wake the thread for some reason.
self._awake = True
while self._awake:
#Handle update times for functions and numbers.
if hasattr(self.update_time, '__call__'):
ut = float( self.update_time() )
else:
ut = self.update_time
#Wait so we don't hog the CPU. What are we coming to? A
#world where AI doesn't rape your machine?
time.sleep(ut)
#Check for the current most pressing need.
urgent = self.needs.most_urgent(40)
if not urgent:
urgent = maslow.Need("explore", maslow.OTHER)
#If it is the same as the currently running one, go ahead.
if self.current_need and urgent.name == self.current_need.name and not self.current_need.done:
if DEBUGGING:
print("Calling make_move for %s" % (self.current_need.name))
self.current_need.make_move()
else:
#Just make a new need and set it as current.
#If the current need is the same as the last one, that probably means it couldn't be
#reached, try exploring.
if self.current_need and self.current_need.done and self.current_need.name == urgent.name:
urgent = maslow.Need("explore", maslow.OTHER)
if DEBUGGING:
print("Creating new %s"%(urgent.name))
self.current_need = self[urgent.name](urgent, self.owner.internal_map, self.owner)
self.current_need.make_move()
def sleep(self):
'''Kills the thread.'''
self._awake = False
| search_and_go_mode |
utils.py | import os
import secrets
from PIL import Image
from flask_blog import mail
from flask_mail import Message
from flask import current_app, url_for
def save_picture(form_picture):
|
def send_reset_email(user):
token = user.get_reset_token()
msg = Message('Password Reset Request',
sender='[email protected]',
recipients=[user.email])
token = user.get_reset_token()
msg = Message('Password Reset Request', recipients=[user.email])
# _external – if set to True, an absolute URL is generated
msg.body = f'''To reset your password, visit the following link:
{url_for('users.reset_token', token=token, _external=True)}
If you did not make this request then simply ignore this email and no changes will be made.
'''
mail.send(msg)
| random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(
current_app.root_path, 'static/profile_pics', picture_fn)
output_size = (125, 125)
i = Image.open(form_picture)
i.thumbnail(output_size)
i.save(picture_path)
return picture_fn |
daily.py | # -*- coding: utf-8 -*-
import sys
from watertools.Collect.GEOS.DataAccess import DownloadData
def main(Dir, Vars, Startdate, Enddate, latlim, lonlim, Waitbar = 1, data_type = ["mean"]):
|
if __name__ == '__main__':
main(sys.argv)
| """
This function downloads GEOS daily data for a given variable, time
interval, and spatial extent.
Keyword arguments:
Dir -- 'C:/file/to/path/'
Vars -- ['t2m', 'v2m']
Startdate -- 'yyyy-mm-dd'
Enddate -- 'yyyy-mm-dd'
latlim -- [ymin, ymax]
lonlim -- [xmin, xmax]
Waitbar -- 1 (Default) Will print a waitbar
"""
for Var in Vars:
if Waitbar == 1:
print('\nDownloading daily GEOS %s data for the period %s till %s' %(Var, Startdate, Enddate))
# Download data
DownloadData(Dir, Var, Startdate, Enddate, latlim, lonlim, "daily", '', Waitbar, data_type) |
exp10f.rs | use super::{exp2, exp2f, modff};
const LN10_F32: f32 = 3.32192809488736234787031942948939;
const LN10_F64: f64 = 3.32192809488736234787031942948939;
const P10: &[f32] = &[
1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,
];
#[inline]
#[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)]
pub extern "C" fn exp10f(x: f32) -> f32 | {
let (mut y, n) = modff(x);
let u = n.to_bits();
/* fabsf(n) < 8 without raising invalid on nan */
if (u >> 23 & 0xff) < 0x7f + 3 {
if y == 0.0 {
return P10[((n as isize) + 7) as usize];
}
y = exp2f(LN10_F32 * y);
return y * P10[((n as isize) + 7) as usize];
}
return exp2(LN10_F64 * (x as f64)) as f32;
} |
|
ImageSpecEnforcer.go | /*
Copyright 2021 Reactive Tech Limited.
"Reactive Tech Limited" is a company located in England, United Kingdom.
https://www.reactive-tech.io
Lead Developer: Alex Arica
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package statefulset_spec
import (
apps "k8s.io/api/apps/v1"
"reactive-tech.io/kubegres/controllers/ctx"
)
type ImageSpecEnforcer struct {
kubegresContext ctx.KubegresContext
}
func | (kubegresContext ctx.KubegresContext) ImageSpecEnforcer {
return ImageSpecEnforcer{kubegresContext: kubegresContext}
}
func (r *ImageSpecEnforcer) GetSpecName() string {
return "Image"
}
func (r *ImageSpecEnforcer) CheckForSpecDifference(statefulSet *apps.StatefulSet) StatefulSetSpecDifference {
current := statefulSet.Spec.Template.Spec.Containers[0].Image
expected := r.kubegresContext.Kubegres.Spec.Image
if current != expected {
return StatefulSetSpecDifference{
SpecName: r.GetSpecName(),
Current: current,
Expected: expected,
}
}
return StatefulSetSpecDifference{}
}
func (r *ImageSpecEnforcer) EnforceSpec(statefulSet *apps.StatefulSet) (wasSpecUpdated bool, err error) {
statefulSet.Spec.Template.Spec.Containers[0].Image = r.kubegresContext.Kubegres.Spec.Image
if len(statefulSet.Spec.Template.Spec.InitContainers) > 0 {
statefulSet.Spec.Template.Spec.InitContainers[0].Image = r.kubegresContext.Kubegres.Spec.Image
}
return true, nil
}
func (r *ImageSpecEnforcer) OnSpecEnforcedSuccessfully(statefulSet *apps.StatefulSet) error {
return nil
}
| CreateImageSpecEnforcer |
type_modulizer.py | __all__ = ('modulize',)
import sys
from types import FunctionType, GetSetDescriptorType, MappingProxyType, ModuleType
from .docs import has_docs
NoneType = type(None)
try:
from _weakref import ref as WeakrefType
except ImportError:
from weakref import ref as WeakrefType
# This 2 type can be function
WrapperDescriptorType = type(object.__ne__)
MethodDescriptorType = type(object.__format__)
DO_NOT_MODULIZE_TYPES = [MappingProxyType, GetSetDescriptorType]
if WrapperDescriptorType is not FunctionType:
DO_NOT_MODULIZE_TYPES.append(WrapperDescriptorType)
if MethodDescriptorType is not FunctionType:
DO_NOT_MODULIZE_TYPES.append(MethodDescriptorType)
DO_NOT_MODULIZE_TYPES = tuple(DO_NOT_MODULIZE_TYPES)
@has_docs
def | (old, globals_, source_module, module_name, module_path):
"""
Changes the given function's scopes and qualname if they were defined inside of a modulized class.
Parameters
----------
old : `function`
A function present inside of a modulized class.
globals_ : `dict` of (`str`, `Any`)
Global variables of the respective module.
source_module : `module`
The module, where the modulized class was defined.
module_name : `str`
The newly created module's name.
module_path : `str`
The newly created module's path.
Returns
-------
new : `function`
Newly recreated function if applicable.
"""
if old.__module__ != source_module:
return old
new = FunctionType(old.__code__, globals_, old.__name__, old.__defaults__, old.__closure__)
new.__module__ = module_path
qualname = old.__qualname__
if (qualname is not None) and (len(qualname) > len(module_name)) and qualname[len(module_name)] =='.' and \
qualname.startswith(module_name):
new.__qualname__ = qualname[len(module_name) + 1:]
return new
@has_docs
def _modulize_type(klass, globals_, source_module, module_name, module_path):
"""
Changes the given class's scopes and qualname if they were defined inside of a modulized class.
Parameters
----------
klass : `type`
A class present inside of a modulized class.
globals_ : `dict` of (`str`, `Any`)
Global variables of the respective module.
source_module : `module`
The module, where the modulized class was defined.
module_name : `str`
The newly created module's name.
module_path : `str`
The newly created module's path.
"""
if klass.__module__ != source_module:
return
qualname = klass.__qualname__
if (qualname is None) or (len(qualname) <= len(module_name)) or qualname[len(module_name)] != '.' \
or not qualname.startswith(module_name):
return
klass.__qualname__ = qualname[len(module_name) + 1:]
klass.__module__ = module_path
for name in dir(klass):
value = getattr(klass, name)
value_type = value.__class__
if value_type is FunctionType:
value = _modulize_function(value, globals_, source_module, module_name, module_path)
setattr(klass, name, value)
if issubclass(value_type, type):
_modulize_type(value, globals_, source_module, module_name, module_path)
@has_docs
def modulize(klass):
"""
Transforms the given class to a module.
Every functions and classes defined inside of given class, which are also present at transformation as well, will
have their global scope modified.
Parameters
----------
klass : `type`
The class to transform to module.
Returns
-------
result_module : `module`
The created module object.
Raises
------
TypeError
If `klass` is not given as `type`.
"""
if not isinstance(klass, type):
raise TypeError(
f'Only types can be modulized, got {klass.__class__.__name__}; {klass!r}.'
)
source_module = klass.__module__
module_name = klass.__name__
module_path = f'{klass.__module__}.{module_name}'
try:
result_module = sys.modules['module_path']
except KeyError:
result_module = ModuleType(module_path)
sys.modules[module_path] = result_module
globals_ = result_module.__dict__
globals_['__builtins__'] = __builtins__
else:
globals_ = result_module.__dict__
collected_names = []
for name in globals_.keys():
if name.startswith('__') and name.endswith('__'):
continue
collected_names.append(name)
for name in collected_names:
del globals_[name]
globals_['__doc__'] = None
for name in type.__dir__(klass):
if name.startswith('__') and name.endswith('__') and name != '__doc__':
continue
value = type.__getattribute__(klass, name)
value_type = type(value)
if value_type in DO_NOT_MODULIZE_TYPES:
continue
if value_type is FunctionType:
value = _modulize_function(value, globals_, source_module, module_name, module_path)
if issubclass(value_type, type):
_modulize_type(value, globals_, source_module, module_name, module_path)
ModuleType.__setattr__(result_module, name, value)
return result_module
| _modulize_function |
validators.js | const jwt = require('jsonwebtoken');
const Joi = require('joi');
const util = require('util');
const { statusCodes } = require('../constants');
const verifyToken = util.promisify(jwt.verify);
function initState(req, res, next) {
if (!req.state) {
req.state = {};
}
return next();
}
async function validateToken(req, res, next) {
const bearerHeader = req.headers.authorization;
if (!bearerHeader) {
return res.sendStatus(statusCodes.UNAUTHORIZED);
}
const token = bearerHeader.split(' ')[1];
try {
const authData = verifyToken(token, process.env.JWT_SECRET);
req.authData = authData;
return next();
}
catch (e) {
return res.sendStatus(statusCodes.UNAUTHORIZED);
}
}
function | (req, res, next) {
const { userId } = req.params;
console.log(req.headers);
if (!userId) {
return res.sendStatus(400);
}
// if (!bearerHeader) {
// return res.sendStatus(401);
// }
req.state.userId = userId;
return next();
}
function validateParams(schema) {
return (req, res, next) => {
const validation = Joi.validate(req.body, schema);
if (validation.error) {
return res.status(statusCodes.BAD_REQUEST).send(validation.error);
}
return next();
}
}
module.exports = {
validateToken,
setUserId,
initState,
validateParams
};
| setUserId |
version_test.go | package main
import (
"bytes"
"strings"
"testing"
"github.com/cnabio/duffle/pkg/version"
"github.com/stretchr/testify/assert"
)
func | (t *testing.T) {
buf := bytes.NewBuffer(nil)
showVersion(buf)
assert.Equal(t, version.Version, strings.TrimSpace(buf.String()))
}
| TestVersion |
App.js | import React from 'react'
import './App.css';
import Home from '../src/pages/Home'
import "./style/blog-css.css"
import {Switch, Route} from 'react-router-dom';
function | () {
return (
<>
<Switch>
<Route exact path='/' component={() => <Home/>} />
<Route path='/' component={() => <h1>Page not found</h1>} />
</Switch>
</>
);
}
export default App;
| App |
grammar.rs | // The Rust grammar sits in
// https://github.com/tree-sitter/tree-sitter-rust/blob/master/grammar.js
// We can use the playground to view the node kind:
// https://tree-sitter.github.io/tree-sitter/playground
pub type NodeKind = &'static str; | pub const FIELD_IDENTIFIER: NodeKind = "field_identifier";
pub const MOD_ITEM: NodeKind = "mod_item";
pub const ATTRIBUTE_ITEM: NodeKind = "attribute_item";
pub const META_ITEM: NodeKind = "meta_item";
pub const ARGUMENTS: NodeKind = "arguments"; |
pub const UNSAFE: NodeKind = "unsafe";
pub const INDEX_EXPRESSION: NodeKind = "index_expression";
pub const IDENTIFIER: NodeKind = "identifier"; |
fit_file_services.py | """In this module we provide services for working with fit files.
Resources
- fitparse package: [GitHub](https://github.com/dtcooper/python-fitparse) and \
[Docs](http://dtcooper.github.io/python-fitparse/)
- fitdecode pacakge: [GitHub](https://github.com/polyvertex/fitdecode) and \
[Read the Docs](https://fitdecode.readthedocs.io/en/latest/)
- [FIT on Wikipedia](https://wiki.openstreetmap.org/wiki/FIT)
- [Download FIT SDK](https://www.thisisant.com/resources/fit).
"""
from typing import Union
import fitparse
import pandas as pd
UNIT_CONVERSION = {
"speed": {"from": "10*6m/s", "to": "km/h", "factor": 0.0036,},
"enhanced_speed": {"from": "10*6m/s", "to": "km/h", "factor": 3.6,},
"altitude": {"from": "unknown", "to": "m", "factor": 0.03855343881175331,},
"position_long": {"from": "semicircles", "to": "degrees", "factor": (180.0 / 2 ** 31),},
"position_lat": {"from": "semicircles", "to": "degrees", "factor": (180.0 / 2 ** 31),},
}
def parse_fit_file(file: Union[fitparse.base.FitFile, bytes, str,]) -> pd.DataFrame:
"""Converts a fit_file to a dataframe
Args:
file (Union[fitparse.base.FitFile, bytes, str]): The fit file to parse
Raises:
ValueError: If the file is not in a supported format
Returns:
pd.DataFrame: A DataFrame with the data
"""
if isinstance(file, (bytes, str,),):
fit_file = fitparse.FitFile(file)
elif isinstance(file, fitparse.base.FitFile,):
fit_file = file
else:
raise ValueError(f"{type(file)} is not supported!")
return _parse_records(fit_file.get_messages("record"))
def _parse_records(records,):
data = [record.get_values() for record in records]
training_data = pd.DataFrame(data)
_convert_units(training_data)
return training_data
def | (training_data_row: pd.DataFrame,):
columns = set(UNIT_CONVERSION.keys()).intersection(set(training_data_row.columns))
for column in columns:
training_data_row[column] *= UNIT_CONVERSION[column]["factor"]
| _convert_units |
resources.py | from flask import abort, jsonify
from flask_restful import Resource
from flask_simplelogin import login_required
from test.models import Product
class ProductResource(Resource):
def get(self):
products = Product.query.all() or abort(204)
return jsonify(
{"products": [product.to_dict() for product in products]}
)
@login_required(basic=True, username="admin")
def post(self):
"""
Creates a new product.
Only admin user authenticated using basic auth can post
Basic takes base64 encripted username:password.
# curl -XPOST localhost:5000/api/v1/product/ \
# -H "Authorization: Basic Y2h1Y2s6bm9ycmlz" \
# -H "Content-Type: application/json"
"""
return NotImplementedError(
"Someone please complete this example and send a PR :)"
)
class ProductItemResource(Resource):
def get(self, product_id):
| product = Product.query.filter_by(id=product_id).first() or abort(404)
return jsonify(product.to_dict()) |
|
utils.py | from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"], deprecated = "auto")
def hash(password: str):
return pwd_context.hash(password)
def | (plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
| verify |
project.go | /*
Copyright 2022 Rancher Labs, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by main. DO NOT EDIT.
package v3
import (
"context"
"time"
"github.com/rancher/lasso/pkg/client"
"github.com/rancher/lasso/pkg/controller"
v3 "github.com/rancher/rancher/pkg/apis/management.cattle.io/v3"
"github.com/rancher/wrangler/pkg/apply"
"github.com/rancher/wrangler/pkg/condition"
"github.com/rancher/wrangler/pkg/generic"
"github.com/rancher/wrangler/pkg/kv"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
type ProjectHandler func(string, *v3.Project) (*v3.Project, error)
type ProjectController interface {
generic.ControllerMeta
ProjectClient
OnChange(ctx context.Context, name string, sync ProjectHandler)
OnRemove(ctx context.Context, name string, sync ProjectHandler)
Enqueue(namespace, name string)
EnqueueAfter(namespace, name string, duration time.Duration)
Cache() ProjectCache
}
type ProjectClient interface {
Create(*v3.Project) (*v3.Project, error)
Update(*v3.Project) (*v3.Project, error)
UpdateStatus(*v3.Project) (*v3.Project, error)
Delete(namespace, name string, options *metav1.DeleteOptions) error
Get(namespace, name string, options metav1.GetOptions) (*v3.Project, error)
List(namespace string, opts metav1.ListOptions) (*v3.ProjectList, error)
Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error)
Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v3.Project, err error)
}
type ProjectCache interface {
Get(namespace, name string) (*v3.Project, error)
List(namespace string, selector labels.Selector) ([]*v3.Project, error)
AddIndexer(indexName string, indexer ProjectIndexer)
GetByIndex(indexName, key string) ([]*v3.Project, error)
}
type ProjectIndexer func(obj *v3.Project) ([]string, error)
type projectController struct {
controller controller.SharedController
client *client.Client
gvk schema.GroupVersionKind
groupResource schema.GroupResource
}
func NewProjectController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ProjectController {
c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced)
return &projectController{
controller: c,
client: c.Client(),
gvk: gvk,
groupResource: schema.GroupResource{
Group: gvk.Group,
Resource: resource,
},
}
}
func FromProjectHandlerToHandler(sync ProjectHandler) generic.Handler {
return func(key string, obj runtime.Object) (ret runtime.Object, err error) {
var v *v3.Project
if obj == nil {
v, err = sync(key, nil)
} else {
v, err = sync(key, obj.(*v3.Project))
}
if v == nil {
return nil, err
}
return v, err
}
}
func (c *projectController) Updater() generic.Updater {
return func(obj runtime.Object) (runtime.Object, error) {
newObj, err := c.Update(obj.(*v3.Project))
if newObj == nil {
return nil, err
}
return newObj, err
}
}
func UpdateProjectDeepCopyOnChange(client ProjectClient, obj *v3.Project, handler func(obj *v3.Project) (*v3.Project, error)) (*v3.Project, error) {
if obj == nil {
return obj, nil
}
copyObj := obj.DeepCopy()
newObj, err := handler(copyObj)
if newObj != nil {
copyObj = newObj
}
if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) {
return client.Update(copyObj)
}
return copyObj, err
}
func (c *projectController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) {
c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler))
}
func (c *projectController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) {
c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler))
}
func (c *projectController) OnChange(ctx context.Context, name string, sync ProjectHandler) {
c.AddGenericHandler(ctx, name, FromProjectHandlerToHandler(sync))
}
func (c *projectController) OnRemove(ctx context.Context, name string, sync ProjectHandler) {
c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromProjectHandlerToHandler(sync)))
}
func (c *projectController) Enqueue(namespace, name string) {
c.controller.Enqueue(namespace, name)
}
func (c *projectController) EnqueueAfter(namespace, name string, duration time.Duration) {
c.controller.EnqueueAfter(namespace, name, duration)
}
func (c *projectController) Informer() cache.SharedIndexInformer {
return c.controller.Informer()
}
func (c *projectController) GroupVersionKind() schema.GroupVersionKind {
return c.gvk
}
func (c *projectController) Cache() ProjectCache {
return &projectCache{
indexer: c.Informer().GetIndexer(),
resource: c.groupResource,
}
}
func (c *projectController) Create(obj *v3.Project) (*v3.Project, error) {
result := &v3.Project{}
return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{})
}
func (c *projectController) Update(obj *v3.Project) (*v3.Project, error) {
result := &v3.Project{}
return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{})
}
func (c *projectController) UpdateStatus(obj *v3.Project) (*v3.Project, error) {
result := &v3.Project{}
return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{})
}
func (c *projectController) Delete(namespace, name string, options *metav1.DeleteOptions) error {
if options == nil {
options = &metav1.DeleteOptions{}
}
return c.client.Delete(context.TODO(), namespace, name, *options)
}
func (c *projectController) Get(namespace, name string, options metav1.GetOptions) (*v3.Project, error) {
result := &v3.Project{}
return result, c.client.Get(context.TODO(), namespace, name, result, options)
}
func (c *projectController) List(namespace string, opts metav1.ListOptions) (*v3.ProjectList, error) {
result := &v3.ProjectList{}
return result, c.client.List(context.TODO(), namespace, result, opts)
}
func (c *projectController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) {
return c.client.Watch(context.TODO(), namespace, opts)
}
func (c *projectController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v3.Project, error) {
result := &v3.Project{}
return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...)
}
type projectCache struct {
indexer cache.Indexer
resource schema.GroupResource
}
func (c *projectCache) Get(namespace, name string) (*v3.Project, error) {
obj, exists, err := c.indexer.GetByKey(namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(c.resource, name)
}
return obj.(*v3.Project), nil
}
func (c *projectCache) List(namespace string, selector labels.Selector) (ret []*v3.Project, err error) {
err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v3.Project))
})
return ret, err
}
func (c *projectCache) AddIndexer(indexName string, indexer ProjectIndexer) {
utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{
indexName: func(obj interface{}) (strings []string, e error) {
return indexer(obj.(*v3.Project))
},
}))
}
func (c *projectCache) GetByIndex(indexName, key string) (result []*v3.Project, err error) {
objs, err := c.indexer.ByIndex(indexName, key)
if err != nil {
return nil, err
}
result = make([]*v3.Project, 0, len(objs))
for _, obj := range objs {
result = append(result, obj.(*v3.Project))
}
return result, nil
}
type ProjectStatusHandler func(obj *v3.Project, status v3.ProjectStatus) (v3.ProjectStatus, error)
type ProjectGeneratingHandler func(obj *v3.Project, status v3.ProjectStatus) ([]runtime.Object, v3.ProjectStatus, error)
func RegisterProjectStatusHandler(ctx context.Context, controller ProjectController, condition condition.Cond, name string, handler ProjectStatusHandler) {
statusHandler := &projectStatusHandler{
client: controller,
condition: condition,
handler: handler,
}
controller.AddGenericHandler(ctx, name, FromProjectHandlerToHandler(statusHandler.sync))
}
func RegisterProjectGeneratingHandler(ctx context.Context, controller ProjectController, apply apply.Apply,
condition condition.Cond, name string, handler ProjectGeneratingHandler, opts *generic.GeneratingHandlerOptions) |
type projectStatusHandler struct {
client ProjectClient
condition condition.Cond
handler ProjectStatusHandler
}
func (a *projectStatusHandler) sync(key string, obj *v3.Project) (*v3.Project, error) {
if obj == nil {
return obj, nil
}
origStatus := obj.Status.DeepCopy()
obj = obj.DeepCopy()
newStatus, err := a.handler(obj, obj.Status)
if err != nil {
// Revert to old status on error
newStatus = *origStatus.DeepCopy()
}
if a.condition != "" {
if errors.IsConflict(err) {
a.condition.SetError(&newStatus, "", nil)
} else {
a.condition.SetError(&newStatus, "", err)
}
}
if !equality.Semantic.DeepEqual(origStatus, &newStatus) {
if a.condition != "" {
// Since status has changed, update the lastUpdatedTime
a.condition.LastUpdated(&newStatus, time.Now().UTC().Format(time.RFC3339))
}
var newErr error
obj.Status = newStatus
newObj, newErr := a.client.UpdateStatus(obj)
if err == nil {
err = newErr
}
if newErr == nil {
obj = newObj
}
}
return obj, err
}
type projectGeneratingHandler struct {
ProjectGeneratingHandler
apply apply.Apply
opts generic.GeneratingHandlerOptions
gvk schema.GroupVersionKind
name string
}
func (a *projectGeneratingHandler) Remove(key string, obj *v3.Project) (*v3.Project, error) {
if obj != nil {
return obj, nil
}
obj = &v3.Project{}
obj.Namespace, obj.Name = kv.RSplit(key, "/")
obj.SetGroupVersionKind(a.gvk)
return nil, generic.ConfigureApplyForObject(a.apply, obj, &a.opts).
WithOwner(obj).
WithSetID(a.name).
ApplyObjects()
}
func (a *projectGeneratingHandler) Handle(obj *v3.Project, status v3.ProjectStatus) (v3.ProjectStatus, error) {
if !obj.DeletionTimestamp.IsZero() {
return status, nil
}
objs, newStatus, err := a.ProjectGeneratingHandler(obj, status)
if err != nil {
return newStatus, err
}
return newStatus, generic.ConfigureApplyForObject(a.apply, obj, &a.opts).
WithOwner(obj).
WithSetID(a.name).
ApplyObjects(objs...)
}
| {
statusHandler := &projectGeneratingHandler{
ProjectGeneratingHandler: handler,
apply: apply,
name: name,
gvk: controller.GroupVersionKind(),
}
if opts != nil {
statusHandler.opts = *opts
}
controller.OnChange(ctx, name, statusHandler.Remove)
RegisterProjectStatusHandler(ctx, controller, condition, name, statusHandler.Handle)
} |
ruby_2_2_0.rs | /* automatically generated by rust-bindgen 0.59.2 */
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
pub const fn new(storage: Storage) -> Self {
Self { storage }
}
}
impl<Storage> __BindgenBitfieldUnit<Storage>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
#[inline]
pub fn get_bit(&self, index: usize) -> bool {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = self.storage.as_ref()[byte_index];
let bit_index = if cfg!(target_endian = "big") {
7 - (index % 8)
} else {
index % 8
};
let mask = 1 << bit_index;
byte & mask == mask
}
#[inline]
pub fn set_bit(&mut self, index: usize, val: bool) {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = &mut self.storage.as_mut()[byte_index];
let bit_index = if cfg!(target_endian = "big") {
7 - (index % 8)
} else {
index % 8
};
let mask = 1 << bit_index;
if val {
*byte |= mask;
} else {
*byte &= !mask;
}
}
#[inline]
pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
let mut val = 0;
for i in 0..(bit_width as usize) {
if self.get_bit(i + bit_offset) {
let index = if cfg!(target_endian = "big") {
bit_width as usize - 1 - i
} else {
i
};
val |= 1 << index;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!((bit_offset + (bit_width as usize)) / 8 <= self.storage.as_ref().len());
for i in 0..(bit_width as usize) {
let mask = 1 << i;
let val_bit_is_set = val & mask == mask;
let index = if cfg!(target_endian = "big") {
bit_width as usize - 1 - i
} else {
i
};
self.set_bit(index + bit_offset, val_bit_is_set);
}
}
}
pub type size_t = usize;
pub type __uint32_t = ::std::os::raw::c_uint;
pub type __clockid_t = ::std::os::raw::c_int;
pub type clockid_t = __clockid_t;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __sigset_t {
pub __val: [usize; 16usize],
}
#[test]
fn bindgen_test_layout___sigset_t() {
assert_eq!(
::std::mem::size_of::<__sigset_t>(),
128usize,
concat!("Size of: ", stringify!(__sigset_t))
);
assert_eq!(
::std::mem::align_of::<__sigset_t>(),
8usize,
concat!("Alignment of ", stringify!(__sigset_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__sigset_t>())).__val as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__sigset_t),
"::",
stringify!(__val)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_internal_list {
pub __prev: *mut __pthread_internal_list,
pub __next: *mut __pthread_internal_list,
}
#[test]
fn bindgen_test_layout___pthread_internal_list() {
assert_eq!(
::std::mem::size_of::<__pthread_internal_list>(),
16usize,
concat!("Size of: ", stringify!(__pthread_internal_list))
);
assert_eq!(
::std::mem::align_of::<__pthread_internal_list>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_internal_list))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_internal_list>())).__prev as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_internal_list),
"::",
stringify!(__prev)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_internal_list>())).__next as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(__pthread_internal_list),
"::",
stringify!(__next)
)
);
}
pub type __pthread_list_t = __pthread_internal_list;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_mutex_s {
pub __lock: ::std::os::raw::c_int,
pub __count: ::std::os::raw::c_uint,
pub __owner: ::std::os::raw::c_int,
pub __nusers: ::std::os::raw::c_uint,
pub __kind: ::std::os::raw::c_int,
pub __spins: ::std::os::raw::c_short,
pub __elision: ::std::os::raw::c_short,
pub __list: __pthread_list_t,
}
#[test]
fn bindgen_test_layout___pthread_mutex_s() {
assert_eq!(
::std::mem::size_of::<__pthread_mutex_s>(),
40usize,
concat!("Size of: ", stringify!(__pthread_mutex_s))
);
assert_eq!(
::std::mem::align_of::<__pthread_mutex_s>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_mutex_s))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__lock as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__count as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__count)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__owner as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__owner)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__nusers as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__nusers)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__kind as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__kind)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__spins as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__spins)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__elision as *const _ as usize },
22usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__elision)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_mutex_s>())).__list as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(__pthread_mutex_s),
"::",
stringify!(__list)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct __pthread_cond_s {
pub __bindgen_anon_1: __pthread_cond_s__bindgen_ty_1,
pub __bindgen_anon_2: __pthread_cond_s__bindgen_ty_2,
pub __g_refs: [::std::os::raw::c_uint; 2usize],
pub __g_size: [::std::os::raw::c_uint; 2usize],
pub __g1_orig_size: ::std::os::raw::c_uint,
pub __wrefs: ::std::os::raw::c_uint,
pub __g_signals: [::std::os::raw::c_uint; 2usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union __pthread_cond_s__bindgen_ty_1 {
pub __wseq: ::std::os::raw::c_ulonglong,
pub __wseq32: __pthread_cond_s__bindgen_ty_1__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_cond_s__bindgen_ty_1__bindgen_ty_1 {
pub __low: ::std::os::raw::c_uint,
pub __high: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>())).__low
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(__low)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1__bindgen_ty_1>())).__high
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(__high)
)
);
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(__pthread_cond_s__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s__bindgen_ty_1))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1>())).__wseq as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1),
"::",
stringify!(__wseq)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_1>())).__wseq32 as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_1),
"::",
stringify!(__wseq32)
)
);
}
impl ::std::fmt::Debug for __pthread_cond_s__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "__pthread_cond_s__bindgen_ty_1 {{ union }}")
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union __pthread_cond_s__bindgen_ty_2 {
pub __g1_start: ::std::os::raw::c_ulonglong,
pub __g1_start32: __pthread_cond_s__bindgen_ty_2__bindgen_ty_1,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __pthread_cond_s__bindgen_ty_2__bindgen_ty_1 {
pub __low: ::std::os::raw::c_uint,
pub __high: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>())).__low
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1),
"::",
stringify!(__low)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2__bindgen_ty_1>())).__high
as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2__bindgen_ty_1),
"::",
stringify!(__high)
)
);
}
#[test]
fn bindgen_test_layout___pthread_cond_s__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s__bindgen_ty_2>(),
8usize,
concat!("Size of: ", stringify!(__pthread_cond_s__bindgen_ty_2))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s__bindgen_ty_2>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s__bindgen_ty_2))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2>())).__g1_start as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2),
"::",
stringify!(__g1_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<__pthread_cond_s__bindgen_ty_2>())).__g1_start32 as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s__bindgen_ty_2),
"::",
stringify!(__g1_start32)
)
);
}
impl ::std::fmt::Debug for __pthread_cond_s__bindgen_ty_2 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "__pthread_cond_s__bindgen_ty_2 {{ union }}")
}
}
#[test]
fn bindgen_test_layout___pthread_cond_s() {
assert_eq!(
::std::mem::size_of::<__pthread_cond_s>(),
48usize,
concat!("Size of: ", stringify!(__pthread_cond_s))
);
assert_eq!(
::std::mem::align_of::<__pthread_cond_s>(),
8usize,
concat!("Alignment of ", stringify!(__pthread_cond_s))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_refs as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_refs)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_size as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g1_orig_size as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g1_orig_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__wrefs as *const _ as usize },
36usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__wrefs)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__pthread_cond_s>())).__g_signals as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(__pthread_cond_s),
"::",
stringify!(__g_signals)
)
);
}
impl ::std::fmt::Debug for __pthread_cond_s {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "__pthread_cond_s {{ __bindgen_anon_1: {:?}, __bindgen_anon_2: {:?}, __g_refs: {:?}, __g_size: {:?}, __g1_orig_size: {:?}, __wrefs: {:?}, __g_signals: {:?} }}" , self . __bindgen_anon_1 , self . __bindgen_anon_2 , self . __g_refs , self . __g_size , self . __g1_orig_size , self . __wrefs , self . __g_signals)
}
}
pub type pthread_t = usize;
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_mutex_t {
pub __data: __pthread_mutex_s,
pub __size: [::std::os::raw::c_char; 40usize],
pub __align: ::std::os::raw::c_long,
}
#[test]
fn bindgen_test_layout_pthread_mutex_t() {
assert_eq!(
::std::mem::size_of::<pthread_mutex_t>(),
40usize,
concat!("Size of: ", stringify!(pthread_mutex_t))
);
assert_eq!(
::std::mem::align_of::<pthread_mutex_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_mutex_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_mutex_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_mutex_t),
"::",
stringify!(__align)
)
);
}
impl ::std::fmt::Debug for pthread_mutex_t {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "pthread_mutex_t {{ union }}")
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_cond_t {
pub __data: __pthread_cond_s,
pub __size: [::std::os::raw::c_char; 48usize],
pub __align: ::std::os::raw::c_longlong,
}
#[test]
fn bindgen_test_layout_pthread_cond_t() {
assert_eq!(
::std::mem::size_of::<pthread_cond_t>(),
48usize,
concat!("Size of: ", stringify!(pthread_cond_t))
);
assert_eq!(
::std::mem::align_of::<pthread_cond_t>(),
8usize,
concat!("Alignment of ", stringify!(pthread_cond_t))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__data as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<pthread_cond_t>())).__align as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(pthread_cond_t),
"::",
stringify!(__align)
)
);
}
impl ::std::fmt::Debug for pthread_cond_t {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "pthread_cond_t {{ union }}")
}
}
pub type VALUE = usize;
pub type ID = usize;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct RBasic {
pub flags: VALUE,
pub klass: VALUE,
}
#[test]
fn bindgen_test_layout_RBasic() {
assert_eq!(
::std::mem::size_of::<RBasic>(),
16usize,
concat!("Size of: ", stringify!(RBasic))
);
assert_eq!(
::std::mem::align_of::<RBasic>(),
8usize,
concat!("Alignment of ", stringify!(RBasic))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RBasic>())).flags as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RBasic),
"::",
stringify!(flags)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RBasic>())).klass as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(RBasic),
"::",
stringify!(klass)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RString {
pub basic: RBasic,
pub as_: RString__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RString__bindgen_ty_1 {
pub heap: RString__bindgen_ty_1__bindgen_ty_1,
pub ary: [::std::os::raw::c_char; 24usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RString__bindgen_ty_1__bindgen_ty_1 {
pub len: ::std::os::raw::c_long,
pub ptr: *mut ::std::os::raw::c_char,
pub aux: RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
pub capa: ::std::os::raw::c_long,
pub shared: VALUE,
}
#[test]
fn bindgen_test_layout_RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>())).capa
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(capa)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>())).shared
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(shared)
)
);
}
impl ::std::fmt::Debug for RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RString__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {{ union }}"
)
}
}
#[test]
fn bindgen_test_layout_RString__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RString__bindgen_ty_1__bindgen_ty_1>(),
24usize,
concat!("Size of: ", stringify!(RString__bindgen_ty_1__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<RString__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RString__bindgen_ty_1__bindgen_ty_1>())).len as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(len)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RString__bindgen_ty_1__bindgen_ty_1>())).ptr as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(ptr)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RString__bindgen_ty_1__bindgen_ty_1>())).aux as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(aux)
)
);
}
impl ::std::fmt::Debug for RString__bindgen_ty_1__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RString__bindgen_ty_1__bindgen_ty_1 {{ len: {:?}, ptr: {:?}, aux: {:?} }}",
self.len, self.ptr, self.aux
)
}
}
#[test]
fn bindgen_test_layout_RString__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RString__bindgen_ty_1>(),
24usize,
concat!("Size of: ", stringify!(RString__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<RString__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(RString__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RString__bindgen_ty_1>())).heap as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1),
"::",
stringify!(heap)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RString__bindgen_ty_1>())).ary as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RString__bindgen_ty_1),
"::",
stringify!(ary)
)
);
}
impl ::std::fmt::Debug for RString__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "RString__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_RString() {
assert_eq!(
::std::mem::size_of::<RString>(),
40usize,
concat!("Size of: ", stringify!(RString))
);
assert_eq!(
::std::mem::align_of::<RString>(),
8usize,
concat!("Alignment of ", stringify!(RString))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RString>())).basic as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RString),
"::",
stringify!(basic)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RString>())).as_ as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(RString),
"::",
stringify!(as_)
)
);
}
impl ::std::fmt::Debug for RString {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RString {{ basic: {:?}, as: {:?} }}",
self.basic, self.as_
)
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RArray {
pub basic: RBasic,
pub as_: RArray__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RArray__bindgen_ty_1 {
pub heap: RArray__bindgen_ty_1__bindgen_ty_1,
pub ary: [VALUE; 3usize],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RArray__bindgen_ty_1__bindgen_ty_1 {
pub len: ::std::os::raw::c_long,
pub aux: RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1,
pub ptr: *const VALUE,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
pub capa: ::std::os::raw::c_long,
pub shared: VALUE,
}
#[test]
fn bindgen_test_layout_RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>())).capa
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(capa)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1>())).shared
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(shared)
)
);
}
impl ::std::fmt::Debug for RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RArray__bindgen_ty_1__bindgen_ty_1__bindgen_ty_1 {{ union }}"
)
}
}
#[test]
fn bindgen_test_layout_RArray__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RArray__bindgen_ty_1__bindgen_ty_1>(),
24usize,
concat!("Size of: ", stringify!(RArray__bindgen_ty_1__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<RArray__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RArray__bindgen_ty_1__bindgen_ty_1>())).len as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(len)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RArray__bindgen_ty_1__bindgen_ty_1>())).aux as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(aux)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<RArray__bindgen_ty_1__bindgen_ty_1>())).ptr as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(ptr)
)
);
}
impl ::std::fmt::Debug for RArray__bindgen_ty_1__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RArray__bindgen_ty_1__bindgen_ty_1 {{ len: {:?}, aux: {:?}, ptr: {:?} }}",
self.len, self.aux, self.ptr
)
}
}
#[test]
fn bindgen_test_layout_RArray__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RArray__bindgen_ty_1>(),
24usize,
concat!("Size of: ", stringify!(RArray__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<RArray__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(RArray__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RArray__bindgen_ty_1>())).heap as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1),
"::",
stringify!(heap)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RArray__bindgen_ty_1>())).ary as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RArray__bindgen_ty_1),
"::",
stringify!(ary)
)
);
}
impl ::std::fmt::Debug for RArray__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "RArray__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_RArray() {
assert_eq!(
::std::mem::size_of::<RArray>(),
40usize,
concat!("Size of: ", stringify!(RArray))
);
assert_eq!(
::std::mem::align_of::<RArray>(),
8usize,
concat!("Alignment of ", stringify!(RArray))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RArray>())).basic as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RArray),
"::",
stringify!(basic)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RArray>())).as_ as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(RArray),
"::",
stringify!(as_)
)
);
}
impl ::std::fmt::Debug for RArray {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RArray {{ basic: {:?}, as: {:?} }}",
self.basic, self.as_
)
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_global_variable {
_unused: [u8; 0],
}
pub type st_data_t = usize;
pub type st_index_t = st_data_t;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct st_hash_type {
pub compare: ::std::option::Option<unsafe extern "C" fn() -> ::std::os::raw::c_int>,
pub hash: ::std::option::Option<unsafe extern "C" fn() -> st_index_t>,
}
#[test]
fn bindgen_test_layout_st_hash_type() {
assert_eq!(
::std::mem::size_of::<st_hash_type>(),
16usize,
concat!("Size of: ", stringify!(st_hash_type))
);
assert_eq!(
::std::mem::align_of::<st_hash_type>(),
8usize,
concat!("Alignment of ", stringify!(st_hash_type))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_hash_type>())).compare as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(st_hash_type),
"::",
stringify!(compare)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_hash_type>())).hash as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(st_hash_type),
"::",
stringify!(hash)
)
);
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct st_table {
pub type_: *const st_hash_type,
pub num_bins: st_index_t,
pub _bitfield_align_1: [u64; 0],
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>,
pub as_: st_table__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union st_table__bindgen_ty_1 {
pub big: st_table__bindgen_ty_1__bindgen_ty_1,
pub packed: st_table__bindgen_ty_1__bindgen_ty_2,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct st_table__bindgen_ty_1__bindgen_ty_1 {
pub bins: *mut *mut st_table_entry,
pub head: *mut st_table_entry,
pub tail: *mut st_table_entry,
}
#[test]
fn bindgen_test_layout_st_table__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<st_table__bindgen_ty_1__bindgen_ty_1>(),
24usize,
concat!(
"Size of: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<st_table__bindgen_ty_1__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<st_table__bindgen_ty_1__bindgen_ty_1>())).bins as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(bins)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<st_table__bindgen_ty_1__bindgen_ty_1>())).head as *const _
as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(head)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<st_table__bindgen_ty_1__bindgen_ty_1>())).tail as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_1),
"::",
stringify!(tail)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct st_table__bindgen_ty_1__bindgen_ty_2 {
pub entries: *mut st_packed_entry,
pub real_entries: st_index_t,
}
#[test]
fn bindgen_test_layout_st_table__bindgen_ty_1__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<st_table__bindgen_ty_1__bindgen_ty_2>(),
16usize,
concat!(
"Size of: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_2)
)
);
assert_eq!(
::std::mem::align_of::<st_table__bindgen_ty_1__bindgen_ty_2>(),
8usize,
concat!(
"Alignment of ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_2)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<st_table__bindgen_ty_1__bindgen_ty_2>())).entries as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_2),
"::",
stringify!(entries)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<st_table__bindgen_ty_1__bindgen_ty_2>())).real_entries
as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1__bindgen_ty_2),
"::",
stringify!(real_entries)
)
);
}
#[test]
fn bindgen_test_layout_st_table__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<st_table__bindgen_ty_1>(),
24usize,
concat!("Size of: ", stringify!(st_table__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<st_table__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(st_table__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_table__bindgen_ty_1>())).big as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1),
"::",
stringify!(big)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_table__bindgen_ty_1>())).packed as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(st_table__bindgen_ty_1),
"::",
stringify!(packed)
)
);
}
impl ::std::fmt::Debug for st_table__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "st_table__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_st_table() {
assert_eq!(
::std::mem::size_of::<st_table>(),
48usize,
concat!("Size of: ", stringify!(st_table))
);
assert_eq!(
::std::mem::align_of::<st_table>(),
8usize,
concat!("Alignment of ", stringify!(st_table))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_table>())).type_ as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(st_table),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_table>())).num_bins as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(st_table),
"::",
stringify!(num_bins)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<st_table>())).as_ as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(st_table),
"::",
stringify!(as_)
)
);
}
impl ::std::fmt::Debug for st_table {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "st_table {{ type: {:?}, num_bins: {:?}, entries_packed : {:?}, num_entries : {:?}, as: {:?} }}" , self . type_ , self . num_bins , self . entries_packed () , self . num_entries () , self . as_)
}
}
impl st_table {
#[inline]
pub fn entries_packed(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) }
}
#[inline]
pub fn set_entries_packed(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(0usize, 1u8, val as u64)
}
}
#[inline]
pub fn num_entries(&self) -> st_index_t {
unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 63u8) as usize) }
}
#[inline]
pub fn set_num_entries(&mut self, val: st_index_t) {
unsafe {
let val: usize = ::std::mem::transmute(val);
self._bitfield_1.set(1usize, 63u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
entries_packed: ::std::os::raw::c_uint,
num_entries: st_index_t,
) -> __BindgenBitfieldUnit<[u8; 8usize]> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 8usize]> = Default::default();
__bindgen_bitfield_unit.set(0usize, 1u8, {
let entries_packed: u32 = unsafe { ::std::mem::transmute(entries_packed) };
entries_packed as u64
});
__bindgen_bitfield_unit.set(1usize, 63u8, {
let num_entries: usize = unsafe { ::std::mem::transmute(num_entries) };
num_entries as u64
});
__bindgen_bitfield_unit
}
}
pub type rb_unblock_function_t =
::std::option::Option<unsafe extern "C" fn(arg1: *mut ::std::os::raw::c_void)>;
pub type rb_event_flag_t = u32;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct RNode {
pub flags: VALUE,
pub nd_reserved: VALUE,
pub u1: RNode__bindgen_ty_1,
pub u2: RNode__bindgen_ty_2,
pub u3: RNode__bindgen_ty_3,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RNode__bindgen_ty_1 {
pub node: *mut RNode,
pub id: ID,
pub value: VALUE,
pub cfunc: ::std::option::Option<unsafe extern "C" fn() -> VALUE>,
pub tbl: *mut ID,
}
#[test]
fn bindgen_test_layout_RNode__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<RNode__bindgen_ty_1>(),
8usize,
concat!("Size of: ", stringify!(RNode__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<RNode__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(RNode__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_1>())).node as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_1),
"::",
stringify!(node)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_1>())).id as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_1),
"::",
stringify!(id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_1>())).value as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_1),
"::",
stringify!(value)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_1>())).cfunc as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_1),
"::",
stringify!(cfunc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_1>())).tbl as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_1),
"::",
stringify!(tbl)
)
);
}
impl ::std::fmt::Debug for RNode__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "RNode__bindgen_ty_1 {{ union }}")
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RNode__bindgen_ty_2 {
pub node: *mut RNode,
pub id: ID,
pub argc: ::std::os::raw::c_long,
pub value: VALUE,
}
#[test]
fn bindgen_test_layout_RNode__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<RNode__bindgen_ty_2>(),
8usize,
concat!("Size of: ", stringify!(RNode__bindgen_ty_2))
);
assert_eq!(
::std::mem::align_of::<RNode__bindgen_ty_2>(),
8usize,
concat!("Alignment of ", stringify!(RNode__bindgen_ty_2))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_2>())).node as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_2),
"::",
stringify!(node)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_2>())).id as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_2),
"::",
stringify!(id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_2>())).argc as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_2),
"::",
stringify!(argc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_2>())).value as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_2),
"::",
stringify!(value)
)
);
}
impl ::std::fmt::Debug for RNode__bindgen_ty_2 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "RNode__bindgen_ty_2 {{ union }}")
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union RNode__bindgen_ty_3 {
pub node: *mut RNode,
pub id: ID,
pub state: ::std::os::raw::c_long,
pub entry: *mut rb_global_entry,
pub args: *mut rb_args_info,
pub cnt: ::std::os::raw::c_long,
pub value: VALUE,
}
#[test]
fn bindgen_test_layout_RNode__bindgen_ty_3() {
assert_eq!(
::std::mem::size_of::<RNode__bindgen_ty_3>(),
8usize,
concat!("Size of: ", stringify!(RNode__bindgen_ty_3))
);
assert_eq!(
::std::mem::align_of::<RNode__bindgen_ty_3>(),
8usize,
concat!("Alignment of ", stringify!(RNode__bindgen_ty_3))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).node as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(node)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).id as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).state as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(state)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).entry as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(entry)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).args as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(args)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).cnt as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(cnt)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode__bindgen_ty_3>())).value as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode__bindgen_ty_3),
"::",
stringify!(value)
)
);
}
impl ::std::fmt::Debug for RNode__bindgen_ty_3 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "RNode__bindgen_ty_3 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_RNode() {
assert_eq!(
::std::mem::size_of::<RNode>(),
40usize,
concat!("Size of: ", stringify!(RNode))
);
assert_eq!(
::std::mem::align_of::<RNode>(),
8usize,
concat!("Alignment of ", stringify!(RNode))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode>())).flags as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(RNode),
"::",
stringify!(flags)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode>())).nd_reserved as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(RNode),
"::",
stringify!(nd_reserved)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode>())).u1 as *const _ as usize },
16usize,
concat!("Offset of field: ", stringify!(RNode), "::", stringify!(u1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode>())).u2 as *const _ as usize },
24usize,
concat!("Offset of field: ", stringify!(RNode), "::", stringify!(u2))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<RNode>())).u3 as *const _ as usize },
32usize,
concat!("Offset of field: ", stringify!(RNode), "::", stringify!(u3))
);
}
impl ::std::fmt::Debug for RNode {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"RNode {{ flags: {:?}, nd_reserved: {:?}, u1: {:?}, u2: {:?}, u3: {:?} }}",
self.flags, self.nd_reserved, self.u1, self.u2, self.u3
)
}
}
pub type NODE = RNode;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_global_entry {
pub var: *mut rb_global_variable,
pub id: ID,
}
#[test]
fn bindgen_test_layout_rb_global_entry() {
assert_eq!(
::std::mem::size_of::<rb_global_entry>(),
16usize,
concat!("Size of: ", stringify!(rb_global_entry))
);
assert_eq!(
::std::mem::align_of::<rb_global_entry>(),
8usize,
concat!("Alignment of ", stringify!(rb_global_entry))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_global_entry>())).var as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_global_entry),
"::",
stringify!(var)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_global_entry>())).id as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_global_entry),
"::",
stringify!(id)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_args_info {
pub pre_init: *mut NODE,
pub post_init: *mut NODE,
pub pre_args_num: ::std::os::raw::c_int,
pub post_args_num: ::std::os::raw::c_int,
pub first_post_arg: ID,
pub rest_arg: ID,
pub block_arg: ID,
pub kw_args: *mut NODE,
pub kw_rest_arg: *mut NODE,
pub opt_args: *mut NODE,
}
#[test]
fn bindgen_test_layout_rb_args_info() {
assert_eq!(
::std::mem::size_of::<rb_args_info>(),
72usize,
concat!("Size of: ", stringify!(rb_args_info))
);
assert_eq!(
::std::mem::align_of::<rb_args_info>(),
8usize,
concat!("Alignment of ", stringify!(rb_args_info))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).pre_init as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(pre_init)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).post_init as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(post_init)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).pre_args_num as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(pre_args_num)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).post_args_num as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(post_args_num)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).first_post_arg as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(first_post_arg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).rest_arg as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(rest_arg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).block_arg as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(block_arg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).kw_args as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(kw_args)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).kw_rest_arg as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(kw_rest_arg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_args_info>())).opt_args as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(rb_args_info),
"::",
stringify!(opt_args)
)
);
}
pub const ruby_id_types_RUBY_ID_STATIC_SYM: ruby_id_types = 1;
pub const ruby_id_types_RUBY_ID_LOCAL: ruby_id_types = 0;
pub const ruby_id_types_RUBY_ID_INSTANCE: ruby_id_types = 2;
pub const ruby_id_types_RUBY_ID_GLOBAL: ruby_id_types = 6;
pub const ruby_id_types_RUBY_ID_ATTRSET: ruby_id_types = 8;
pub const ruby_id_types_RUBY_ID_CONST: ruby_id_types = 10;
pub const ruby_id_types_RUBY_ID_CLASS: ruby_id_types = 12;
pub const ruby_id_types_RUBY_ID_JUNK: ruby_id_types = 14;
pub const ruby_id_types_RUBY_ID_INTERNAL: ruby_id_types = 14;
pub const ruby_id_types_RUBY_ID_SCOPE_SHIFT: ruby_id_types = 4;
pub const ruby_id_types_RUBY_ID_SCOPE_MASK: ruby_id_types = 14;
pub type ruby_id_types = ::std::os::raw::c_uint;
pub const ruby_method_ids_idDot2: ruby_method_ids = 128;
pub const ruby_method_ids_idDot3: ruby_method_ids = 129;
pub const ruby_method_ids_idUPlus: ruby_method_ids = 130;
pub const ruby_method_ids_idUMinus: ruby_method_ids = 131;
pub const ruby_method_ids_idPow: ruby_method_ids = 132;
pub const ruby_method_ids_idCmp: ruby_method_ids = 134;
pub const ruby_method_ids_idPLUS: ruby_method_ids = 43;
pub const ruby_method_ids_idMINUS: ruby_method_ids = 45;
pub const ruby_method_ids_idMULT: ruby_method_ids = 42;
pub const ruby_method_ids_idDIV: ruby_method_ids = 47;
pub const ruby_method_ids_idMOD: ruby_method_ids = 37;
pub const ruby_method_ids_idLT: ruby_method_ids = 60;
pub const ruby_method_ids_idLTLT: ruby_method_ids = 135;
pub const ruby_method_ids_idLE: ruby_method_ids = 137;
pub const ruby_method_ids_idGT: ruby_method_ids = 62;
pub const ruby_method_ids_idGTGT: ruby_method_ids = 136;
pub const ruby_method_ids_idGE: ruby_method_ids = 138;
pub const ruby_method_ids_idEq: ruby_method_ids = 139;
pub const ruby_method_ids_idEqq: ruby_method_ids = 140;
pub const ruby_method_ids_idNeq: ruby_method_ids = 141;
pub const ruby_method_ids_idNot: ruby_method_ids = 33;
pub const ruby_method_ids_idBackquote: ruby_method_ids = 96;
pub const ruby_method_ids_idEqTilde: ruby_method_ids = 142;
pub const ruby_method_ids_idNeqTilde: ruby_method_ids = 143;
pub const ruby_method_ids_idAREF: ruby_method_ids = 144;
pub const ruby_method_ids_idASET: ruby_method_ids = 145;
pub const ruby_method_ids_idCOLON2: ruby_method_ids = 146;
pub const ruby_method_ids_idANDOP: ruby_method_ids = 148;
pub const ruby_method_ids_idOROP: ruby_method_ids = 149;
pub const ruby_method_ids_tPRESERVED_ID_BEGIN: ruby_method_ids = 149;
pub const ruby_method_ids_idNULL: ruby_method_ids = 150;
pub const ruby_method_ids_idEmptyP: ruby_method_ids = 151;
pub const ruby_method_ids_idEqlP: ruby_method_ids = 152;
pub const ruby_method_ids_idRespond_to: ruby_method_ids = 153;
pub const ruby_method_ids_idRespond_to_missing: ruby_method_ids = 154;
pub const ruby_method_ids_idIFUNC: ruby_method_ids = 155;
pub const ruby_method_ids_idCFUNC: ruby_method_ids = 156;
pub const ruby_method_ids_id_core_set_method_alias: ruby_method_ids = 157;
pub const ruby_method_ids_id_core_set_variable_alias: ruby_method_ids = 158;
pub const ruby_method_ids_id_core_undef_method: ruby_method_ids = 159;
pub const ruby_method_ids_id_core_define_method: ruby_method_ids = 160;
pub const ruby_method_ids_id_core_define_singleton_method: ruby_method_ids = 161;
pub const ruby_method_ids_id_core_set_postexe: ruby_method_ids = 162;
pub const ruby_method_ids_id_core_hash_from_ary: ruby_method_ids = 163;
pub const ruby_method_ids_id_core_hash_merge_ary: ruby_method_ids = 164;
pub const ruby_method_ids_id_core_hash_merge_ptr: ruby_method_ids = 165;
pub const ruby_method_ids_id_core_hash_merge_kwd: ruby_method_ids = 166;
pub const ruby_method_ids_tPRESERVED_ID_END: ruby_method_ids = 167;
pub const ruby_method_ids_tFreeze: ruby_method_ids = 168;
pub const ruby_method_ids_tInspect: ruby_method_ids = 169;
pub const ruby_method_ids_tIntern: ruby_method_ids = 170;
pub const ruby_method_ids_tObject_id: ruby_method_ids = 171;
pub const ruby_method_ids_tConst_missing: ruby_method_ids = 172;
pub const ruby_method_ids_tMethodMissing: ruby_method_ids = 173;
pub const ruby_method_ids_tMethod_added: ruby_method_ids = 174;
pub const ruby_method_ids_tSingleton_method_added: ruby_method_ids = 175;
pub const ruby_method_ids_tMethod_removed: ruby_method_ids = 176;
pub const ruby_method_ids_tSingleton_method_removed: ruby_method_ids = 177;
pub const ruby_method_ids_tMethod_undefined: ruby_method_ids = 178;
pub const ruby_method_ids_tSingleton_method_undefined: ruby_method_ids = 179;
pub const ruby_method_ids_tLength: ruby_method_ids = 180;
pub const ruby_method_ids_tSize: ruby_method_ids = 181;
pub const ruby_method_ids_tGets: ruby_method_ids = 182;
pub const ruby_method_ids_tSucc: ruby_method_ids = 183;
pub const ruby_method_ids_tEach: ruby_method_ids = 184;
pub const ruby_method_ids_tProc: ruby_method_ids = 185;
pub const ruby_method_ids_tLambda: ruby_method_ids = 186;
pub const ruby_method_ids_tSend: ruby_method_ids = 187;
pub const ruby_method_ids_t__send__: ruby_method_ids = 188;
pub const ruby_method_ids_t__attached__: ruby_method_ids = 189;
pub const ruby_method_ids_tInitialize: ruby_method_ids = 190;
pub const ruby_method_ids_tInitialize_copy: ruby_method_ids = 191;
pub const ruby_method_ids_tInitialize_clone: ruby_method_ids = 192;
pub const ruby_method_ids_tInitialize_dup: ruby_method_ids = 193;
pub const ruby_method_ids_tTo_int: ruby_method_ids = 194;
pub const ruby_method_ids_tTo_ary: ruby_method_ids = 195;
pub const ruby_method_ids_tTo_str: ruby_method_ids = 196;
pub const ruby_method_ids_tTo_sym: ruby_method_ids = 197;
pub const ruby_method_ids_tTo_hash: ruby_method_ids = 198;
pub const ruby_method_ids_tTo_proc: ruby_method_ids = 199;
pub const ruby_method_ids_tTo_io: ruby_method_ids = 200;
pub const ruby_method_ids_tTo_a: ruby_method_ids = 201;
pub const ruby_method_ids_tTo_s: ruby_method_ids = 202;
pub const ruby_method_ids_tTo_i: ruby_method_ids = 203;
pub const ruby_method_ids_tBt: ruby_method_ids = 204;
pub const ruby_method_ids_tBt_locations: ruby_method_ids = 205;
pub const ruby_method_ids_tCall: ruby_method_ids = 206;
pub const ruby_method_ids_tMesg: ruby_method_ids = 207;
pub const ruby_method_ids_tException: ruby_method_ids = 208;
pub const ruby_method_ids_tUScore: ruby_method_ids = 209;
pub const ruby_method_ids_tNEXT_ID: ruby_method_ids = 210;
pub const ruby_method_ids_idFreeze: ruby_method_ids = 2689;
pub const ruby_method_ids_idInspect: ruby_method_ids = 2705;
pub const ruby_method_ids_idIntern: ruby_method_ids = 2721;
pub const ruby_method_ids_idObject_id: ruby_method_ids = 2737;
pub const ruby_method_ids_idConst_missing: ruby_method_ids = 2753;
pub const ruby_method_ids_idMethodMissing: ruby_method_ids = 2769;
pub const ruby_method_ids_idMethod_added: ruby_method_ids = 2785;
pub const ruby_method_ids_idSingleton_method_added: ruby_method_ids = 2801;
pub const ruby_method_ids_idMethod_removed: ruby_method_ids = 2817;
pub const ruby_method_ids_idSingleton_method_removed: ruby_method_ids = 2833;
pub const ruby_method_ids_idMethod_undefined: ruby_method_ids = 2849;
pub const ruby_method_ids_idSingleton_method_undefined: ruby_method_ids = 2865;
pub const ruby_method_ids_idLength: ruby_method_ids = 2881;
pub const ruby_method_ids_idSize: ruby_method_ids = 2897;
pub const ruby_method_ids_idGets: ruby_method_ids = 2913;
pub const ruby_method_ids_idSucc: ruby_method_ids = 2929;
pub const ruby_method_ids_idEach: ruby_method_ids = 2945;
pub const ruby_method_ids_idProc: ruby_method_ids = 2961;
pub const ruby_method_ids_idLambda: ruby_method_ids = 2977;
pub const ruby_method_ids_idSend: ruby_method_ids = 2993;
pub const ruby_method_ids_id__send__: ruby_method_ids = 3009;
pub const ruby_method_ids_id__attached__: ruby_method_ids = 3025;
pub const ruby_method_ids_idInitialize: ruby_method_ids = 3041;
pub const ruby_method_ids_idInitialize_copy: ruby_method_ids = 3057;
pub const ruby_method_ids_idInitialize_clone: ruby_method_ids = 3073;
pub const ruby_method_ids_idInitialize_dup: ruby_method_ids = 3089;
pub const ruby_method_ids_idTo_int: ruby_method_ids = 3105;
pub const ruby_method_ids_idTo_ary: ruby_method_ids = 3121;
pub const ruby_method_ids_idTo_str: ruby_method_ids = 3137;
pub const ruby_method_ids_idTo_sym: ruby_method_ids = 3153;
pub const ruby_method_ids_idTo_hash: ruby_method_ids = 3169;
pub const ruby_method_ids_idTo_proc: ruby_method_ids = 3185;
pub const ruby_method_ids_idTo_io: ruby_method_ids = 3201;
pub const ruby_method_ids_idTo_a: ruby_method_ids = 3217;
pub const ruby_method_ids_idTo_s: ruby_method_ids = 3233;
pub const ruby_method_ids_idTo_i: ruby_method_ids = 3249;
pub const ruby_method_ids_idBt: ruby_method_ids = 3265;
pub const ruby_method_ids_idBt_locations: ruby_method_ids = 3281;
pub const ruby_method_ids_idCall: ruby_method_ids = 3297;
pub const ruby_method_ids_idMesg: ruby_method_ids = 3313;
pub const ruby_method_ids_idException: ruby_method_ids = 3329;
pub const ruby_method_ids_idUScore: ruby_method_ids = 3345;
pub const ruby_method_ids_tLAST_OP_ID: ruby_method_ids = 166;
pub const ruby_method_ids_idLAST_OP_ID: ruby_method_ids = 10;
pub type ruby_method_ids = ::std::os::raw::c_uint;
pub type rb_serial_t = ::std::os::raw::c_ulonglong;
pub const rb_method_flag_t_NOEX_PUBLIC: rb_method_flag_t = 0;
pub const rb_method_flag_t_NOEX_NOSUPER: rb_method_flag_t = 1;
pub const rb_method_flag_t_NOEX_PRIVATE: rb_method_flag_t = 2;
pub const rb_method_flag_t_NOEX_PROTECTED: rb_method_flag_t = 4;
pub const rb_method_flag_t_NOEX_MASK: rb_method_flag_t = 6;
pub const rb_method_flag_t_NOEX_BASIC: rb_method_flag_t = 8;
pub const rb_method_flag_t_NOEX_UNDEF: rb_method_flag_t = 1;
pub const rb_method_flag_t_NOEX_MODFUNC: rb_method_flag_t = 18;
pub const rb_method_flag_t_NOEX_SUPER: rb_method_flag_t = 32;
pub const rb_method_flag_t_NOEX_VCALL: rb_method_flag_t = 64;
pub const rb_method_flag_t_NOEX_RESPONDS: rb_method_flag_t = 128;
pub const rb_method_flag_t_NOEX_BIT_WIDTH: rb_method_flag_t = 8;
pub const rb_method_flag_t_NOEX_SAFE_SHIFT_OFFSET: rb_method_flag_t = 8;
pub type rb_method_flag_t = ::std::os::raw::c_uint;
pub const rb_method_type_t_VM_METHOD_TYPE_ISEQ: rb_method_type_t = 0;
pub const rb_method_type_t_VM_METHOD_TYPE_CFUNC: rb_method_type_t = 1;
pub const rb_method_type_t_VM_METHOD_TYPE_ATTRSET: rb_method_type_t = 2;
pub const rb_method_type_t_VM_METHOD_TYPE_IVAR: rb_method_type_t = 3;
pub const rb_method_type_t_VM_METHOD_TYPE_BMETHOD: rb_method_type_t = 4;
pub const rb_method_type_t_VM_METHOD_TYPE_ZSUPER: rb_method_type_t = 5;
pub const rb_method_type_t_VM_METHOD_TYPE_UNDEF: rb_method_type_t = 6;
pub const rb_method_type_t_VM_METHOD_TYPE_NOTIMPLEMENTED: rb_method_type_t = 7;
pub const rb_method_type_t_VM_METHOD_TYPE_OPTIMIZED: rb_method_type_t = 8;
pub const rb_method_type_t_VM_METHOD_TYPE_MISSING: rb_method_type_t = 9;
pub const rb_method_type_t_VM_METHOD_TYPE_REFINED: rb_method_type_t = 10;
pub type rb_method_type_t = ::std::os::raw::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_method_cfunc_struct {
pub func: ::std::option::Option<unsafe extern "C" fn() -> VALUE>,
pub invoker: ::std::option::Option<
unsafe extern "C" fn(
func: ::std::option::Option<unsafe extern "C" fn() -> VALUE>,
recv: VALUE,
argc: ::std::os::raw::c_int,
argv: *const VALUE,
) -> VALUE,
>,
pub argc: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_method_cfunc_struct() {
assert_eq!(
::std::mem::size_of::<rb_method_cfunc_struct>(),
24usize,
concat!("Size of: ", stringify!(rb_method_cfunc_struct))
);
assert_eq!(
::std::mem::align_of::<rb_method_cfunc_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_method_cfunc_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_cfunc_struct>())).func as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_cfunc_struct),
"::",
stringify!(func)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_cfunc_struct>())).invoker as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_method_cfunc_struct),
"::",
stringify!(invoker)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_cfunc_struct>())).argc as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_method_cfunc_struct),
"::",
stringify!(argc)
)
);
}
pub type rb_method_cfunc_t = rb_method_cfunc_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_method_attr_struct {
pub id: ID,
pub location: VALUE,
}
#[test]
fn bindgen_test_layout_rb_method_attr_struct() {
assert_eq!(
::std::mem::size_of::<rb_method_attr_struct>(),
16usize,
concat!("Size of: ", stringify!(rb_method_attr_struct))
);
assert_eq!(
::std::mem::align_of::<rb_method_attr_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_method_attr_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_attr_struct>())).id as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_attr_struct),
"::",
stringify!(id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_attr_struct>())).location as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_method_attr_struct),
"::",
stringify!(location)
)
);
}
pub type rb_method_attr_t = rb_method_attr_struct;
pub type rb_iseq_t = rb_iseq_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_method_definition_struct {
pub type_: rb_method_type_t,
pub alias_count: ::std::os::raw::c_int,
pub original_id: ID,
pub body: rb_method_definition_struct__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union rb_method_definition_struct__bindgen_ty_1 {
pub iseq: *mut rb_iseq_t,
pub cfunc: rb_method_cfunc_t,
pub attr: rb_method_attr_t,
pub proc_: VALUE,
pub optimize_type: rb_method_definition_struct__bindgen_ty_1_method_optimized_type,
pub orig_me: *mut rb_method_entry_struct,
}
pub const rb_method_definition_struct__bindgen_ty_1_method_optimized_type_OPTIMIZED_METHOD_TYPE_SEND : rb_method_definition_struct__bindgen_ty_1_method_optimized_type = 0 ;
pub const rb_method_definition_struct__bindgen_ty_1_method_optimized_type_OPTIMIZED_METHOD_TYPE_CALL : rb_method_definition_struct__bindgen_ty_1_method_optimized_type = 1 ;
pub const rb_method_definition_struct__bindgen_ty_1_method_optimized_type_OPTIMIZED_METHOD_TYPE__MAX : rb_method_definition_struct__bindgen_ty_1_method_optimized_type = 2 ;
pub type rb_method_definition_struct__bindgen_ty_1_method_optimized_type = ::std::os::raw::c_uint;
#[test]
fn bindgen_test_layout_rb_method_definition_struct__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_method_definition_struct__bindgen_ty_1>(),
24usize,
concat!(
"Size of: ",
stringify!(rb_method_definition_struct__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<rb_method_definition_struct__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(rb_method_definition_struct__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).iseq as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(iseq)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).cfunc as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(cfunc)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).attr as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(attr)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).proc_ as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(proc_)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).optimize_type
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(optimize_type)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct__bindgen_ty_1>())).orig_me
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct__bindgen_ty_1),
"::",
stringify!(orig_me)
)
);
}
impl ::std::fmt::Debug for rb_method_definition_struct__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "rb_method_definition_struct__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_rb_method_definition_struct() {
assert_eq!(
::std::mem::size_of::<rb_method_definition_struct>(),
40usize,
concat!("Size of: ", stringify!(rb_method_definition_struct))
);
assert_eq!(
::std::mem::align_of::<rb_method_definition_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_method_definition_struct))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct>())).type_ as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct>())).alias_count as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct),
"::",
stringify!(alias_count)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct>())).original_id as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct),
"::",
stringify!(original_id)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_definition_struct>())).body as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_method_definition_struct),
"::",
stringify!(body)
)
);
}
impl ::std::fmt::Debug for rb_method_definition_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "rb_method_definition_struct {{ type: {:?}, alias_count: {:?}, original_id: {:?}, body: {:?} }}" , self . type_ , self . alias_count , self . original_id , self . body)
}
}
pub type rb_method_definition_t = rb_method_definition_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_method_entry_struct {
pub flag: rb_method_flag_t,
pub mark: ::std::os::raw::c_char,
pub def: *mut rb_method_definition_t,
pub called_id: ID,
pub klass: VALUE,
}
#[test]
fn bindgen_test_layout_rb_method_entry_struct() {
assert_eq!(
::std::mem::size_of::<rb_method_entry_struct>(),
32usize,
concat!("Size of: ", stringify!(rb_method_entry_struct))
);
assert_eq!(
::std::mem::align_of::<rb_method_entry_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_method_entry_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_entry_struct>())).flag as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_method_entry_struct),
"::",
stringify!(flag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_entry_struct>())).mark as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(rb_method_entry_struct),
"::",
stringify!(mark)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_entry_struct>())).def as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_method_entry_struct),
"::",
stringify!(def)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_method_entry_struct>())).called_id as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_method_entry_struct),
"::",
stringify!(called_id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_method_entry_struct>())).klass as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_method_entry_struct),
"::",
stringify!(klass)
)
);
}
pub type rb_method_entry_t = rb_method_entry_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct unlinked_method_entry_list_entry {
pub next: *mut unlinked_method_entry_list_entry,
pub me: *mut rb_method_entry_t,
}
#[test]
fn bindgen_test_layout_unlinked_method_entry_list_entry() {
assert_eq!(
::std::mem::size_of::<unlinked_method_entry_list_entry>(),
16usize,
concat!("Size of: ", stringify!(unlinked_method_entry_list_entry))
);
assert_eq!(
::std::mem::align_of::<unlinked_method_entry_list_entry>(),
8usize,
concat!(
"Alignment of ",
stringify!(unlinked_method_entry_list_entry)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<unlinked_method_entry_list_entry>())).next as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(unlinked_method_entry_list_entry),
"::",
stringify!(next)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<unlinked_method_entry_list_entry>())).me as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(unlinked_method_entry_list_entry),
"::",
stringify!(me)
)
);
}
pub type rb_atomic_t = ::std::os::raw::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct list_node {
pub next: *mut list_node,
pub prev: *mut list_node,
}
#[test]
fn bindgen_test_layout_list_node() {
assert_eq!(
::std::mem::size_of::<list_node>(),
16usize,
concat!("Size of: ", stringify!(list_node))
);
assert_eq!(
::std::mem::align_of::<list_node>(),
8usize,
concat!("Alignment of ", stringify!(list_node))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<list_node>())).next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(list_node),
"::",
stringify!(next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<list_node>())).prev as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(list_node),
"::",
stringify!(prev)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct list_head {
pub n: list_node,
}
#[test]
fn bindgen_test_layout_list_head() {
assert_eq!(
::std::mem::size_of::<list_head>(),
16usize,
concat!("Size of: ", stringify!(list_head))
);
assert_eq!(
::std::mem::align_of::<list_head>(),
8usize,
concat!("Alignment of ", stringify!(list_head))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<list_head>())).n as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(list_head),
"::",
stringify!(n)
)
);
}
pub type __jmp_buf = [::std::os::raw::c_long; 8usize];
pub type rb_nativethread_id_t = pthread_t;
pub type rb_nativethread_lock_t = pthread_mutex_t;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_thread_cond_struct {
pub cond: pthread_cond_t,
pub clockid: clockid_t,
}
#[test]
fn bindgen_test_layout_rb_thread_cond_struct() {
assert_eq!(
::std::mem::size_of::<rb_thread_cond_struct>(),
56usize,
concat!("Size of: ", stringify!(rb_thread_cond_struct))
);
assert_eq!(
::std::mem::align_of::<rb_thread_cond_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_thread_cond_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_cond_struct>())).cond as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_cond_struct),
"::",
stringify!(cond)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_cond_struct>())).clockid as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_cond_struct),
"::",
stringify!(clockid)
)
);
}
impl ::std::fmt::Debug for rb_thread_cond_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"rb_thread_cond_struct {{ cond: {:?}, clockid: {:?} }}",
self.cond, self.clockid
)
}
}
pub type rb_nativethread_cond_t = rb_thread_cond_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct native_thread_data_struct {
pub signal_thread_list: *mut ::std::os::raw::c_void,
pub sleep_cond: rb_nativethread_cond_t,
}
#[test]
fn bindgen_test_layout_native_thread_data_struct() {
assert_eq!(
::std::mem::size_of::<native_thread_data_struct>(),
64usize,
concat!("Size of: ", stringify!(native_thread_data_struct))
);
assert_eq!(
::std::mem::align_of::<native_thread_data_struct>(),
8usize,
concat!("Alignment of ", stringify!(native_thread_data_struct))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<native_thread_data_struct>())).signal_thread_list as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(native_thread_data_struct),
"::",
stringify!(signal_thread_list)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<native_thread_data_struct>())).sleep_cond as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(native_thread_data_struct),
"::",
stringify!(sleep_cond)
)
);
}
impl ::std::fmt::Debug for native_thread_data_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"native_thread_data_struct {{ signal_thread_list: {:?}, sleep_cond: {:?} }}",
self.signal_thread_list, self.sleep_cond
)
}
}
pub type native_thread_data_t = native_thread_data_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_global_vm_lock_struct {
pub acquired: ::std::os::raw::c_ulong,
pub lock: rb_nativethread_lock_t,
pub waiting: ::std::os::raw::c_ulong,
pub cond: rb_nativethread_cond_t,
pub switch_cond: rb_nativethread_cond_t,
pub switch_wait_cond: rb_nativethread_cond_t,
pub need_yield: ::std::os::raw::c_int,
pub wait_yield: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_global_vm_lock_struct() {
assert_eq!(
::std::mem::size_of::<rb_global_vm_lock_struct>(),
232usize,
concat!("Size of: ", stringify!(rb_global_vm_lock_struct))
);
assert_eq!(
::std::mem::align_of::<rb_global_vm_lock_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_global_vm_lock_struct))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).acquired as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(acquired)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_global_vm_lock_struct>())).lock as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(lock)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).waiting as *const _ as usize
},
48usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(waiting)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_global_vm_lock_struct>())).cond as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(cond)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).switch_cond as *const _ as usize
},
112usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(switch_cond)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).switch_wait_cond as *const _
as usize
},
168usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(switch_wait_cond)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).need_yield as *const _ as usize
},
224usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(need_yield)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_global_vm_lock_struct>())).wait_yield as *const _ as usize
},
228usize,
concat!(
"Offset of field: ",
stringify!(rb_global_vm_lock_struct),
"::",
stringify!(wait_yield)
)
);
}
impl ::std::fmt::Debug for rb_global_vm_lock_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "rb_global_vm_lock_struct {{ acquired: {:?}, lock: {:?}, waiting: {:?}, cond: {:?}, switch_cond: {:?}, switch_wait_cond: {:?}, need_yield: {:?}, wait_yield: {:?} }}" , self . acquired , self . lock , self . waiting , self . cond , self . switch_cond , self . switch_wait_cond , self . need_yield , self . wait_yield)
}
}
pub type rb_global_vm_lock_t = rb_global_vm_lock_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct __jmp_buf_tag {
pub __jmpbuf: __jmp_buf,
pub __mask_was_saved: ::std::os::raw::c_int,
pub __saved_mask: __sigset_t,
}
#[test]
fn bindgen_test_layout___jmp_buf_tag() {
assert_eq!(
::std::mem::size_of::<__jmp_buf_tag>(),
200usize,
concat!("Size of: ", stringify!(__jmp_buf_tag))
);
assert_eq!(
::std::mem::align_of::<__jmp_buf_tag>(),
8usize,
concat!("Alignment of ", stringify!(__jmp_buf_tag))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__jmp_buf_tag>())).__jmpbuf as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(__jmp_buf_tag),
"::",
stringify!(__jmpbuf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__jmp_buf_tag>())).__mask_was_saved as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(__jmp_buf_tag),
"::",
stringify!(__mask_was_saved)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<__jmp_buf_tag>())).__saved_mask as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(__jmp_buf_tag),
"::",
stringify!(__saved_mask)
)
);
}
pub type jmp_buf = [__jmp_buf_tag; 1usize];
pub type rb_num_t = usize;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_compile_data_ensure_node_stack {
_unused: [u8; 0],
}
pub type rb_compile_option_t = rb_compile_option_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct iseq_inline_cache_entry {
pub ic_serial: rb_serial_t,
pub ic_value: iseq_inline_cache_entry__bindgen_ty_1,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union iseq_inline_cache_entry__bindgen_ty_1 {
pub index: size_t,
pub value: VALUE,
}
#[test]
fn bindgen_test_layout_iseq_inline_cache_entry__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<iseq_inline_cache_entry__bindgen_ty_1>(),
8usize,
concat!(
"Size of: ",
stringify!(iseq_inline_cache_entry__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<iseq_inline_cache_entry__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(iseq_inline_cache_entry__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_cache_entry__bindgen_ty_1>())).index as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_cache_entry__bindgen_ty_1),
"::",
stringify!(index)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_cache_entry__bindgen_ty_1>())).value as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_cache_entry__bindgen_ty_1),
"::",
stringify!(value)
)
);
}
impl ::std::fmt::Debug for iseq_inline_cache_entry__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "iseq_inline_cache_entry__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_iseq_inline_cache_entry() {
assert_eq!(
::std::mem::size_of::<iseq_inline_cache_entry>(),
16usize,
concat!("Size of: ", stringify!(iseq_inline_cache_entry))
);
assert_eq!(
::std::mem::align_of::<iseq_inline_cache_entry>(),
8usize,
concat!("Alignment of ", stringify!(iseq_inline_cache_entry))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_cache_entry>())).ic_serial as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_cache_entry),
"::",
stringify!(ic_serial)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_cache_entry>())).ic_value as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_cache_entry),
"::",
stringify!(ic_value)
)
);
}
impl ::std::fmt::Debug for iseq_inline_cache_entry {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(
f,
"iseq_inline_cache_entry {{ ic_serial: {:?}, ic_value: {:?} }}",
self.ic_serial, self.ic_value
)
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union iseq_inline_storage_entry {
pub once: iseq_inline_storage_entry__bindgen_ty_1,
pub cache: iseq_inline_cache_entry,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_inline_storage_entry__bindgen_ty_1 {
pub running_thread: *mut rb_thread_struct,
pub value: VALUE,
}
#[test]
fn bindgen_test_layout_iseq_inline_storage_entry__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<iseq_inline_storage_entry__bindgen_ty_1>(),
16usize,
concat!(
"Size of: ",
stringify!(iseq_inline_storage_entry__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<iseq_inline_storage_entry__bindgen_ty_1>(),
8usize,
concat!(
"Alignment of ",
stringify!(iseq_inline_storage_entry__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_storage_entry__bindgen_ty_1>())).running_thread
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_storage_entry__bindgen_ty_1),
"::",
stringify!(running_thread)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_inline_storage_entry__bindgen_ty_1>())).value as *const _
as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_storage_entry__bindgen_ty_1),
"::",
stringify!(value)
)
);
}
#[test]
fn bindgen_test_layout_iseq_inline_storage_entry() {
assert_eq!(
::std::mem::size_of::<iseq_inline_storage_entry>(),
16usize,
concat!("Size of: ", stringify!(iseq_inline_storage_entry))
);
assert_eq!(
::std::mem::align_of::<iseq_inline_storage_entry>(),
8usize,
concat!("Alignment of ", stringify!(iseq_inline_storage_entry))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_inline_storage_entry>())).once as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_storage_entry),
"::",
stringify!(once)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_inline_storage_entry>())).cache as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_inline_storage_entry),
"::",
stringify!(cache)
)
);
}
impl ::std::fmt::Debug for iseq_inline_storage_entry {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "iseq_inline_storage_entry {{ union }}")
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_call_info_kw_arg_struct {
pub keyword_len: ::std::os::raw::c_int,
pub keywords: [ID; 1usize],
}
#[test]
fn bindgen_test_layout_rb_call_info_kw_arg_struct() {
assert_eq!(
::std::mem::size_of::<rb_call_info_kw_arg_struct>(),
16usize,
concat!("Size of: ", stringify!(rb_call_info_kw_arg_struct))
);
assert_eq!(
::std::mem::align_of::<rb_call_info_kw_arg_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_call_info_kw_arg_struct))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_kw_arg_struct>())).keyword_len as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_kw_arg_struct),
"::",
stringify!(keyword_len)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_kw_arg_struct>())).keywords as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_kw_arg_struct),
"::",
stringify!(keywords)
)
);
}
pub type rb_call_info_kw_arg_t = rb_call_info_kw_arg_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_call_info_struct {
pub mid: ID,
pub flag: ::std::os::raw::c_uint,
pub orig_argc: ::std::os::raw::c_int,
pub blockiseq: *mut rb_iseq_t,
pub kw_arg: *mut rb_call_info_kw_arg_t,
pub method_state: rb_serial_t,
pub class_serial: rb_serial_t,
pub klass: VALUE,
pub me: *const rb_method_entry_t,
pub defined_class: VALUE,
pub blockptr: *mut rb_block_struct,
pub recv: VALUE,
pub argc: ::std::os::raw::c_int,
pub aux: rb_call_info_struct__bindgen_ty_1,
pub call: ::std::option::Option<
unsafe extern "C" fn(
th: *mut rb_thread_struct,
cfp: *mut rb_control_frame_struct,
ci: *mut rb_call_info_struct,
) -> VALUE,
>,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union rb_call_info_struct__bindgen_ty_1 {
pub opt_pc: ::std::os::raw::c_int,
pub index: ::std::os::raw::c_int,
pub missing_reason: ::std::os::raw::c_int,
pub inc_sp: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_call_info_struct__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_call_info_struct__bindgen_ty_1>(),
4usize,
concat!("Size of: ", stringify!(rb_call_info_struct__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<rb_call_info_struct__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(rb_call_info_struct__bindgen_ty_1)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct__bindgen_ty_1>())).opt_pc as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct__bindgen_ty_1),
"::",
stringify!(opt_pc)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct__bindgen_ty_1>())).index as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct__bindgen_ty_1),
"::",
stringify!(index)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct__bindgen_ty_1>())).missing_reason as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct__bindgen_ty_1),
"::",
stringify!(missing_reason)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct__bindgen_ty_1>())).inc_sp as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct__bindgen_ty_1),
"::",
stringify!(inc_sp)
)
);
}
impl ::std::fmt::Debug for rb_call_info_struct__bindgen_ty_1 {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write!(f, "rb_call_info_struct__bindgen_ty_1 {{ union }}")
}
}
#[test]
fn bindgen_test_layout_rb_call_info_struct() |
impl ::std::fmt::Debug for rb_call_info_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "rb_call_info_struct {{ mid: {:?}, flag: {:?}, orig_argc: {:?}, blockiseq: {:?}, kw_arg: {:?}, method_state: {:?}, class_serial: {:?}, klass: {:?}, me: {:?}, defined_class: {:?}, blockptr: {:?}, recv: {:?}, argc: {:?}, aux: {:?}, call: {:?} }}" , self . mid , self . flag , self . orig_argc , self . blockiseq , self . kw_arg , self . method_state , self . class_serial , self . klass , self . me , self . defined_class , self . blockptr , self . recv , self . argc , self . aux , self . call)
}
}
pub type rb_call_info_t = rb_call_info_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_iseq_location_struct {
pub path: VALUE,
pub absolute_path: VALUE,
pub base_label: VALUE,
pub label: VALUE,
pub first_lineno: VALUE,
}
#[test]
fn bindgen_test_layout_rb_iseq_location_struct() {
assert_eq!(
::std::mem::size_of::<rb_iseq_location_struct>(),
40usize,
concat!("Size of: ", stringify!(rb_iseq_location_struct))
);
assert_eq!(
::std::mem::align_of::<rb_iseq_location_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_iseq_location_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_location_struct>())).path as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_location_struct),
"::",
stringify!(path)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_location_struct>())).absolute_path as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_location_struct),
"::",
stringify!(absolute_path)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_location_struct>())).base_label as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_location_struct),
"::",
stringify!(base_label)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_location_struct>())).label as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_location_struct),
"::",
stringify!(label)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_location_struct>())).first_lineno as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_location_struct),
"::",
stringify!(first_lineno)
)
);
}
pub type rb_iseq_location_t = rb_iseq_location_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_iseq_struct {
pub type_: rb_iseq_struct_iseq_type,
pub stack_max: ::std::os::raw::c_int,
pub location: rb_iseq_location_t,
pub iseq_encoded: *mut VALUE,
pub iseq_size: ::std::os::raw::c_uint,
pub line_info_size: ::std::os::raw::c_uint,
pub mark_ary: VALUE,
pub coverage: VALUE,
pub line_info_table: *mut iseq_line_info_entry,
pub local_table: *mut ID,
pub local_table_size: ::std::os::raw::c_int,
pub local_size: ::std::os::raw::c_int,
pub is_entries: *mut iseq_inline_storage_entry,
pub is_size: ::std::os::raw::c_int,
pub callinfo_size: ::std::os::raw::c_int,
pub callinfo_entries: *mut rb_call_info_t,
pub param: rb_iseq_struct__bindgen_ty_1,
pub catch_table: *mut iseq_catch_table,
pub parent_iseq: *mut rb_iseq_struct,
pub local_iseq: *mut rb_iseq_struct,
pub self_: VALUE,
pub orig: VALUE,
pub cref_stack: *mut NODE,
pub klass: VALUE,
pub defined_method_id: ID,
pub flip_cnt: rb_num_t,
pub compile_data: *mut iseq_compile_data,
pub iseq: *mut VALUE,
}
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_TOP: rb_iseq_struct_iseq_type = 0;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_METHOD: rb_iseq_struct_iseq_type = 1;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_BLOCK: rb_iseq_struct_iseq_type = 2;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_CLASS: rb_iseq_struct_iseq_type = 3;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_RESCUE: rb_iseq_struct_iseq_type = 4;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_ENSURE: rb_iseq_struct_iseq_type = 5;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_EVAL: rb_iseq_struct_iseq_type = 6;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_MAIN: rb_iseq_struct_iseq_type = 7;
pub const rb_iseq_struct_iseq_type_ISEQ_TYPE_DEFINED_GUARD: rb_iseq_struct_iseq_type = 8;
pub type rb_iseq_struct_iseq_type = ::std::os::raw::c_uint;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_iseq_struct__bindgen_ty_1 {
pub flags: rb_iseq_struct__bindgen_ty_1__bindgen_ty_1,
pub size: ::std::os::raw::c_int,
pub lead_num: ::std::os::raw::c_int,
pub opt_num: ::std::os::raw::c_int,
pub rest_start: ::std::os::raw::c_int,
pub post_start: ::std::os::raw::c_int,
pub post_num: ::std::os::raw::c_int,
pub block_start: ::std::os::raw::c_int,
pub opt_table: *mut VALUE,
pub keyword: *mut rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword,
}
#[repr(C)]
#[repr(align(4))]
#[derive(Debug, Copy, Clone)]
pub struct rb_iseq_struct__bindgen_ty_1__bindgen_ty_1 {
pub _bitfield_align_1: [u8; 0],
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 1usize]>,
pub __bindgen_padding_0: [u8; 3usize],
}
#[test]
fn bindgen_test_layout_rb_iseq_struct__bindgen_ty_1__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_iseq_struct__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Size of: ",
stringify!(rb_iseq_struct__bindgen_ty_1__bindgen_ty_1)
)
);
assert_eq!(
::std::mem::align_of::<rb_iseq_struct__bindgen_ty_1__bindgen_ty_1>(),
4usize,
concat!(
"Alignment of ",
stringify!(rb_iseq_struct__bindgen_ty_1__bindgen_ty_1)
)
);
}
impl rb_iseq_struct__bindgen_ty_1__bindgen_ty_1 {
#[inline]
pub fn has_lead(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(0usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_lead(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(0usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_opt(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(1usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_opt(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(1usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_rest(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(2usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_rest(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(2usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_post(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(3usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_post(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(3usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_kw(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(4usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_kw(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(4usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_kwrest(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(5usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_kwrest(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(5usize, 1u8, val as u64)
}
}
#[inline]
pub fn has_block(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(6usize, 1u8) as u32) }
}
#[inline]
pub fn set_has_block(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(6usize, 1u8, val as u64)
}
}
#[inline]
pub fn ambiguous_param0(&self) -> ::std::os::raw::c_uint {
unsafe { ::std::mem::transmute(self._bitfield_1.get(7usize, 1u8) as u32) }
}
#[inline]
pub fn set_ambiguous_param0(&mut self, val: ::std::os::raw::c_uint) {
unsafe {
let val: u32 = ::std::mem::transmute(val);
self._bitfield_1.set(7usize, 1u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
has_lead: ::std::os::raw::c_uint,
has_opt: ::std::os::raw::c_uint,
has_rest: ::std::os::raw::c_uint,
has_post: ::std::os::raw::c_uint,
has_kw: ::std::os::raw::c_uint,
has_kwrest: ::std::os::raw::c_uint,
has_block: ::std::os::raw::c_uint,
ambiguous_param0: ::std::os::raw::c_uint,
) -> __BindgenBitfieldUnit<[u8; 1usize]> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 1usize]> = Default::default();
__bindgen_bitfield_unit.set(0usize, 1u8, {
let has_lead: u32 = unsafe { ::std::mem::transmute(has_lead) };
has_lead as u64
});
__bindgen_bitfield_unit.set(1usize, 1u8, {
let has_opt: u32 = unsafe { ::std::mem::transmute(has_opt) };
has_opt as u64
});
__bindgen_bitfield_unit.set(2usize, 1u8, {
let has_rest: u32 = unsafe { ::std::mem::transmute(has_rest) };
has_rest as u64
});
__bindgen_bitfield_unit.set(3usize, 1u8, {
let has_post: u32 = unsafe { ::std::mem::transmute(has_post) };
has_post as u64
});
__bindgen_bitfield_unit.set(4usize, 1u8, {
let has_kw: u32 = unsafe { ::std::mem::transmute(has_kw) };
has_kw as u64
});
__bindgen_bitfield_unit.set(5usize, 1u8, {
let has_kwrest: u32 = unsafe { ::std::mem::transmute(has_kwrest) };
has_kwrest as u64
});
__bindgen_bitfield_unit.set(6usize, 1u8, {
let has_block: u32 = unsafe { ::std::mem::transmute(has_block) };
has_block as u64
});
__bindgen_bitfield_unit.set(7usize, 1u8, {
let ambiguous_param0: u32 = unsafe { ::std::mem::transmute(ambiguous_param0) };
ambiguous_param0 as u64
});
__bindgen_bitfield_unit
}
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword {
pub num: ::std::os::raw::c_int,
pub required_num: ::std::os::raw::c_int,
pub bits_start: ::std::os::raw::c_int,
pub rest_start: ::std::os::raw::c_int,
pub table: *mut ID,
pub default_values: *mut VALUE,
}
#[test]
fn bindgen_test_layout_rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword() {
assert_eq!(
::std::mem::size_of::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>(),
32usize,
concat!(
"Size of: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword)
)
);
assert_eq!(
::std::mem::align_of::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>(),
8usize,
concat!(
"Alignment of ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>())).num
as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(num)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>()))
.required_num as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(required_num)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>()))
.bits_start as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(bits_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>()))
.rest_start as *const _ as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(rest_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>())).table
as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(table)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword>()))
.default_values as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1_rb_iseq_param_keyword),
"::",
stringify!(default_values)
)
);
}
#[test]
fn bindgen_test_layout_rb_iseq_struct__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_iseq_struct__bindgen_ty_1>(),
48usize,
concat!("Size of: ", stringify!(rb_iseq_struct__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<rb_iseq_struct__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(rb_iseq_struct__bindgen_ty_1))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).flags as *const _ as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(flags)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).size as *const _ as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(size)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).lead_num as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(lead_num)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).opt_num as *const _ as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(opt_num)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).rest_start as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(rest_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).post_start as *const _ as usize
},
20usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(post_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).post_num as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(post_num)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).block_start as *const _
as usize
},
28usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(block_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).opt_table as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(opt_table)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct__bindgen_ty_1>())).keyword as *const _ as usize
},
40usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct__bindgen_ty_1),
"::",
stringify!(keyword)
)
);
}
#[test]
fn bindgen_test_layout_rb_iseq_struct() {
assert_eq!(
::std::mem::size_of::<rb_iseq_struct>(),
264usize,
concat!("Size of: ", stringify!(rb_iseq_struct))
);
assert_eq!(
::std::mem::align_of::<rb_iseq_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_iseq_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).type_ as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).stack_max as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(stack_max)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).location as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(location)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).iseq_encoded as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(iseq_encoded)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).iseq_size as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(iseq_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).line_info_size as *const _ as usize },
60usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(line_info_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).mark_ary as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(mark_ary)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).coverage as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(coverage)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).line_info_table as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(line_info_table)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).local_table as *const _ as usize },
88usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(local_table)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).local_table_size as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(local_table_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).local_size as *const _ as usize },
100usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(local_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).is_entries as *const _ as usize },
104usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(is_entries)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).is_size as *const _ as usize },
112usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(is_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).callinfo_size as *const _ as usize },
116usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(callinfo_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).callinfo_entries as *const _ as usize },
120usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(callinfo_entries)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).param as *const _ as usize },
128usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(param)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).catch_table as *const _ as usize },
176usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(catch_table)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).parent_iseq as *const _ as usize },
184usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(parent_iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).local_iseq as *const _ as usize },
192usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(local_iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).self_ as *const _ as usize },
200usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).orig as *const _ as usize },
208usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(orig)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).cref_stack as *const _ as usize },
216usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(cref_stack)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).klass as *const _ as usize },
224usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(klass)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_iseq_struct>())).defined_method_id as *const _ as usize
},
232usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(defined_method_id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).flip_cnt as *const _ as usize },
240usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(flip_cnt)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).compile_data as *const _ as usize },
248usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(compile_data)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_iseq_struct>())).iseq as *const _ as usize },
256usize,
concat!(
"Offset of field: ",
stringify!(rb_iseq_struct),
"::",
stringify!(iseq)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_objspace {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_hook_list_struct {
pub hooks: *mut rb_event_hook_struct,
pub events: rb_event_flag_t,
pub need_clean: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_hook_list_struct() {
assert_eq!(
::std::mem::size_of::<rb_hook_list_struct>(),
16usize,
concat!("Size of: ", stringify!(rb_hook_list_struct))
);
assert_eq!(
::std::mem::align_of::<rb_hook_list_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_hook_list_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_hook_list_struct>())).hooks as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_hook_list_struct),
"::",
stringify!(hooks)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_hook_list_struct>())).events as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_hook_list_struct),
"::",
stringify!(events)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_hook_list_struct>())).need_clean as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(rb_hook_list_struct),
"::",
stringify!(need_clean)
)
);
}
pub type rb_hook_list_t = rb_hook_list_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_vm_struct {
pub self_: VALUE,
pub gvl: rb_global_vm_lock_t,
pub thread_destruct_lock: rb_nativethread_lock_t,
pub main_thread: *mut rb_thread_struct,
pub running_thread: *mut rb_thread_struct,
pub living_threads: list_head,
pub living_thread_num: size_t,
pub thgroup_default: VALUE,
pub running: ::std::os::raw::c_int,
pub thread_abort_on_exception: ::std::os::raw::c_int,
pub trace_running: ::std::os::raw::c_int,
pub sleeper: ::std::os::raw::c_int,
pub mark_object_ary: VALUE,
pub special_exceptions: [VALUE; 4usize],
pub top_self: VALUE,
pub load_path: VALUE,
pub load_path_snapshot: VALUE,
pub load_path_check_cache: VALUE,
pub expanded_load_path: VALUE,
pub loaded_features: VALUE,
pub loaded_features_snapshot: VALUE,
pub loaded_features_index: *mut st_table,
pub loading_table: *mut st_table,
pub trap_list: [rb_vm_struct__bindgen_ty_1; 65usize],
pub event_hooks: rb_hook_list_t,
pub ensure_rollback_table: *mut st_table,
pub postponed_job_buffer: *mut rb_postponed_job_struct,
pub postponed_job_index: ::std::os::raw::c_int,
pub src_encoding_index: ::std::os::raw::c_int,
pub verbose: VALUE,
pub debug: VALUE,
pub orig_progname: VALUE,
pub progname: VALUE,
pub coverages: VALUE,
pub unlinked_method_entry_list: *mut unlinked_method_entry_list_entry,
pub defined_module_hash: VALUE,
pub objspace: *mut rb_objspace,
pub at_exit: RArray,
pub defined_strings: *mut VALUE,
pub frozen_strings: *mut st_table,
pub default_params: rb_vm_struct__bindgen_ty_2,
pub redefined_flag: [::std::os::raw::c_short; 22usize],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_vm_struct__bindgen_ty_1 {
pub cmd: VALUE,
pub safe: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_vm_struct__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_vm_struct__bindgen_ty_1>(),
16usize,
concat!("Size of: ", stringify!(rb_vm_struct__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<rb_vm_struct__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(rb_vm_struct__bindgen_ty_1))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_1>())).cmd as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_1),
"::",
stringify!(cmd)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_1>())).safe as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_1),
"::",
stringify!(safe)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_vm_struct__bindgen_ty_2 {
pub thread_vm_stack_size: size_t,
pub thread_machine_stack_size: size_t,
pub fiber_vm_stack_size: size_t,
pub fiber_machine_stack_size: size_t,
}
#[test]
fn bindgen_test_layout_rb_vm_struct__bindgen_ty_2() {
assert_eq!(
::std::mem::size_of::<rb_vm_struct__bindgen_ty_2>(),
32usize,
concat!("Size of: ", stringify!(rb_vm_struct__bindgen_ty_2))
);
assert_eq!(
::std::mem::align_of::<rb_vm_struct__bindgen_ty_2>(),
8usize,
concat!("Alignment of ", stringify!(rb_vm_struct__bindgen_ty_2))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_2>())).thread_vm_stack_size as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_2),
"::",
stringify!(thread_vm_stack_size)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_2>())).thread_machine_stack_size
as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_2),
"::",
stringify!(thread_machine_stack_size)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_2>())).fiber_vm_stack_size as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_2),
"::",
stringify!(fiber_vm_stack_size)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct__bindgen_ty_2>())).fiber_machine_stack_size
as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct__bindgen_ty_2),
"::",
stringify!(fiber_machine_stack_size)
)
);
}
#[test]
fn bindgen_test_layout_rb_vm_struct() {
assert_eq!(
::std::mem::size_of::<rb_vm_struct>(),
1736usize,
concat!("Size of: ", stringify!(rb_vm_struct))
);
assert_eq!(
::std::mem::align_of::<rb_vm_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_vm_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).self_ as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).gvl as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(gvl)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).thread_destruct_lock as *const _ as usize
},
240usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(thread_destruct_lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).main_thread as *const _ as usize },
280usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(main_thread)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).running_thread as *const _ as usize },
288usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(running_thread)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).living_threads as *const _ as usize },
296usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(living_threads)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).living_thread_num as *const _ as usize },
312usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(living_thread_num)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).thgroup_default as *const _ as usize },
320usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(thgroup_default)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).running as *const _ as usize },
328usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(running)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).thread_abort_on_exception as *const _ as usize
},
332usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(thread_abort_on_exception)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).trace_running as *const _ as usize },
336usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(trace_running)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).sleeper as *const _ as usize },
340usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(sleeper)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).mark_object_ary as *const _ as usize },
344usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(mark_object_ary)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).special_exceptions as *const _ as usize },
352usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(special_exceptions)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).top_self as *const _ as usize },
384usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(top_self)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).load_path as *const _ as usize },
392usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(load_path)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).load_path_snapshot as *const _ as usize },
400usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(load_path_snapshot)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).load_path_check_cache as *const _ as usize
},
408usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(load_path_check_cache)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).expanded_load_path as *const _ as usize },
416usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(expanded_load_path)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).loaded_features as *const _ as usize },
424usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(loaded_features)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).loaded_features_snapshot as *const _ as usize
},
432usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(loaded_features_snapshot)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).loaded_features_index as *const _ as usize
},
440usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(loaded_features_index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).loading_table as *const _ as usize },
448usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(loading_table)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).trap_list as *const _ as usize },
456usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(trap_list)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).event_hooks as *const _ as usize },
1496usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(event_hooks)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).ensure_rollback_table as *const _ as usize
},
1512usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(ensure_rollback_table)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).postponed_job_buffer as *const _ as usize
},
1520usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(postponed_job_buffer)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).postponed_job_index as *const _ as usize
},
1528usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(postponed_job_index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).src_encoding_index as *const _ as usize },
1532usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(src_encoding_index)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).verbose as *const _ as usize },
1536usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(verbose)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).debug as *const _ as usize },
1544usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(debug)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).orig_progname as *const _ as usize },
1552usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(orig_progname)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).progname as *const _ as usize },
1560usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(progname)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).coverages as *const _ as usize },
1568usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(coverages)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).unlinked_method_entry_list as *const _ as usize
},
1576usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(unlinked_method_entry_list)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_vm_struct>())).defined_module_hash as *const _ as usize
},
1584usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(defined_module_hash)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).objspace as *const _ as usize },
1592usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(objspace)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).at_exit as *const _ as usize },
1600usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(at_exit)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).defined_strings as *const _ as usize },
1640usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(defined_strings)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).frozen_strings as *const _ as usize },
1648usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(frozen_strings)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).default_params as *const _ as usize },
1656usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(default_params)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_struct>())).redefined_flag as *const _ as usize },
1688usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_struct),
"::",
stringify!(redefined_flag)
)
);
}
impl ::std::fmt::Debug for rb_vm_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "rb_vm_struct {{ self: {:?}, gvl: {:?}, thread_destruct_lock: {:?}, main_thread: {:?}, running_thread: {:?}, living_threads: {:?}, living_thread_num: {:?}, thgroup_default: {:?}, running: {:?}, thread_abort_on_exception: {:?}, trace_running: {:?}, sleeper: {:?}, mark_object_ary: {:?}, special_exceptions: {:?}, top_self: {:?}, load_path: {:?}, load_path_snapshot: {:?}, load_path_check_cache: {:?}, expanded_load_path: {:?}, loaded_features: {:?}, loaded_features_snapshot: {:?}, loaded_features_index: {:?}, loading_table: {:?}, trap_list: {:?}, event_hooks: {:?}, ensure_rollback_table: {:?}, postponed_job_buffer: {:?}, postponed_job_index: {:?}, src_encoding_index: {:?}, verbose: {:?}, debug: {:?}, orig_progname: {:?}, progname: {:?}, coverages: {:?}, unlinked_method_entry_list: {:?}, defined_module_hash: {:?}, objspace: {:?}, at_exit: {:?}, defined_strings: {:?}, frozen_strings: {:?}, default_params: {:?}, redefined_flag: {:?} }}" , self . self_ , self . gvl , self . thread_destruct_lock , self . main_thread , self . running_thread , self . living_threads , self . living_thread_num , self . thgroup_default , self . running , self . thread_abort_on_exception , self . trace_running , self . sleeper , self . mark_object_ary , self . special_exceptions , self . top_self , self . load_path , self . load_path_snapshot , self . load_path_check_cache , self . expanded_load_path , self . loaded_features , self . loaded_features_snapshot , self . loaded_features_index , self . loading_table , self . trap_list , self . event_hooks , self . ensure_rollback_table , self . postponed_job_buffer , self . postponed_job_index , self . src_encoding_index , self . verbose , self . debug , self . orig_progname , self . progname , self . coverages , self . unlinked_method_entry_list , self . defined_module_hash , self . objspace , self . at_exit , self . defined_strings , self . frozen_strings , self . default_params , self . redefined_flag)
}
}
pub type rb_vm_t = rb_vm_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_control_frame_struct {
pub pc: *mut VALUE,
pub sp: *mut VALUE,
pub iseq: *mut rb_iseq_t,
pub flag: VALUE,
pub self_: VALUE,
pub klass: VALUE,
pub ep: *mut VALUE,
pub block_iseq: *mut rb_iseq_t,
pub proc_: VALUE,
pub me: *const rb_method_entry_t,
}
#[test]
fn bindgen_test_layout_rb_control_frame_struct() {
assert_eq!(
::std::mem::size_of::<rb_control_frame_struct>(),
80usize,
concat!("Size of: ", stringify!(rb_control_frame_struct))
);
assert_eq!(
::std::mem::align_of::<rb_control_frame_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_control_frame_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).pc as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(pc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).sp as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(sp)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).iseq as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).flag as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(flag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).self_ as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).klass as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(klass)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).ep as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(ep)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_control_frame_struct>())).block_iseq as *const _ as usize
},
56usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(block_iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).proc_ as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(proc_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_control_frame_struct>())).me as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(rb_control_frame_struct),
"::",
stringify!(me)
)
);
}
pub type rb_control_frame_t = rb_control_frame_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_block_struct {
pub self_: VALUE,
pub klass: VALUE,
pub ep: *mut VALUE,
pub iseq: *mut rb_iseq_t,
pub proc_: VALUE,
}
#[test]
fn bindgen_test_layout_rb_block_struct() {
assert_eq!(
::std::mem::size_of::<rb_block_struct>(),
40usize,
concat!("Size of: ", stringify!(rb_block_struct))
);
assert_eq!(
::std::mem::align_of::<rb_block_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_block_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_block_struct>())).self_ as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_block_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_block_struct>())).klass as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_block_struct),
"::",
stringify!(klass)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_block_struct>())).ep as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_block_struct),
"::",
stringify!(ep)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_block_struct>())).iseq as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_block_struct),
"::",
stringify!(iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_block_struct>())).proc_ as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(rb_block_struct),
"::",
stringify!(proc_)
)
);
}
pub type rb_block_t = rb_block_struct;
pub const rb_thread_status_THREAD_RUNNABLE: rb_thread_status = 0;
pub const rb_thread_status_THREAD_STOPPED: rb_thread_status = 1;
pub const rb_thread_status_THREAD_STOPPED_FOREVER: rb_thread_status = 2;
pub const rb_thread_status_THREAD_KILLED: rb_thread_status = 3;
pub type rb_thread_status = ::std::os::raw::c_uint;
pub type rb_jmpbuf_t = jmp_buf;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_vm_tag {
pub tag: VALUE,
pub retval: VALUE,
pub buf: rb_jmpbuf_t,
pub prev: *mut rb_vm_tag,
}
#[test]
fn bindgen_test_layout_rb_vm_tag() {
assert_eq!(
::std::mem::size_of::<rb_vm_tag>(),
224usize,
concat!("Size of: ", stringify!(rb_vm_tag))
);
assert_eq!(
::std::mem::align_of::<rb_vm_tag>(),
8usize,
concat!("Alignment of ", stringify!(rb_vm_tag))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_tag>())).tag as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_tag),
"::",
stringify!(tag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_tag>())).retval as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_tag),
"::",
stringify!(retval)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_tag>())).buf as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_tag),
"::",
stringify!(buf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_tag>())).prev as *const _ as usize },
216usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_tag),
"::",
stringify!(prev)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_vm_protect_tag {
pub prev: *mut rb_vm_protect_tag,
}
#[test]
fn bindgen_test_layout_rb_vm_protect_tag() {
assert_eq!(
::std::mem::size_of::<rb_vm_protect_tag>(),
8usize,
concat!("Size of: ", stringify!(rb_vm_protect_tag))
);
assert_eq!(
::std::mem::align_of::<rb_vm_protect_tag>(),
8usize,
concat!("Alignment of ", stringify!(rb_vm_protect_tag))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_vm_protect_tag>())).prev as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_vm_protect_tag),
"::",
stringify!(prev)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_unblock_callback {
pub func: rb_unblock_function_t,
pub arg: *mut ::std::os::raw::c_void,
}
#[test]
fn bindgen_test_layout_rb_unblock_callback() {
assert_eq!(
::std::mem::size_of::<rb_unblock_callback>(),
16usize,
concat!("Size of: ", stringify!(rb_unblock_callback))
);
assert_eq!(
::std::mem::align_of::<rb_unblock_callback>(),
8usize,
concat!("Alignment of ", stringify!(rb_unblock_callback))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_unblock_callback>())).func as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_unblock_callback),
"::",
stringify!(func)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_unblock_callback>())).arg as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_unblock_callback),
"::",
stringify!(arg)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_mutex_struct {
_unused: [u8; 0],
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_thread_list_struct {
pub next: *mut rb_thread_list_struct,
pub th: *mut rb_thread_struct,
}
#[test]
fn bindgen_test_layout_rb_thread_list_struct() {
assert_eq!(
::std::mem::size_of::<rb_thread_list_struct>(),
16usize,
concat!("Size of: ", stringify!(rb_thread_list_struct))
);
assert_eq!(
::std::mem::align_of::<rb_thread_list_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_thread_list_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_list_struct>())).next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_list_struct),
"::",
stringify!(next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_list_struct>())).th as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_list_struct),
"::",
stringify!(th)
)
);
}
pub type rb_thread_list_t = rb_thread_list_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_ensure_entry {
pub marker: VALUE,
pub e_proc: ::std::option::Option<unsafe extern "C" fn() -> VALUE>,
pub data2: VALUE,
}
#[test]
fn bindgen_test_layout_rb_ensure_entry() {
assert_eq!(
::std::mem::size_of::<rb_ensure_entry>(),
24usize,
concat!("Size of: ", stringify!(rb_ensure_entry))
);
assert_eq!(
::std::mem::align_of::<rb_ensure_entry>(),
8usize,
concat!("Alignment of ", stringify!(rb_ensure_entry))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_ensure_entry>())).marker as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_ensure_entry),
"::",
stringify!(marker)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_ensure_entry>())).e_proc as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_ensure_entry),
"::",
stringify!(e_proc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_ensure_entry>())).data2 as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_ensure_entry),
"::",
stringify!(data2)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_ensure_list {
pub next: *mut rb_ensure_list,
pub entry: rb_ensure_entry,
}
#[test]
fn bindgen_test_layout_rb_ensure_list() {
assert_eq!(
::std::mem::size_of::<rb_ensure_list>(),
32usize,
concat!("Size of: ", stringify!(rb_ensure_list))
);
assert_eq!(
::std::mem::align_of::<rb_ensure_list>(),
8usize,
concat!("Alignment of ", stringify!(rb_ensure_list))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_ensure_list>())).next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_ensure_list),
"::",
stringify!(next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_ensure_list>())).entry as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_ensure_list),
"::",
stringify!(entry)
)
);
}
pub type rb_ensure_list_t = rb_ensure_list;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_fiber_struct {
_unused: [u8; 0],
}
pub type rb_fiber_t = rb_fiber_struct;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct rb_thread_struct {
pub vmlt_node: list_node,
pub self_: VALUE,
pub vm: *mut rb_vm_t,
pub stack: *mut VALUE,
pub stack_size: size_t,
pub cfp: *mut rb_control_frame_t,
pub safe_level: ::std::os::raw::c_int,
pub raised_flag: ::std::os::raw::c_int,
pub last_status: VALUE,
pub state: ::std::os::raw::c_int,
pub waiting_fd: ::std::os::raw::c_int,
pub passed_block: *const rb_block_t,
pub passed_bmethod_me: *const rb_method_entry_t,
pub passed_ci: *mut rb_call_info_t,
pub top_self: VALUE,
pub top_wrapper: VALUE,
pub base_block: *mut rb_block_t,
pub root_lep: *mut VALUE,
pub root_svar: VALUE,
pub thread_id: rb_nativethread_id_t,
pub status: rb_thread_status,
pub to_kill: ::std::os::raw::c_int,
pub priority: ::std::os::raw::c_int,
pub mark_stack_len: ::std::os::raw::c_int,
pub native_thread_data: native_thread_data_t,
pub blocking_region_buffer: *mut ::std::os::raw::c_void,
pub thgroup: VALUE,
pub value: VALUE,
pub errinfo: VALUE,
pub pending_interrupt_queue: VALUE,
pub pending_interrupt_mask_stack: VALUE,
pub pending_interrupt_queue_checked: ::std::os::raw::c_int,
pub interrupt_flag: rb_atomic_t,
pub interrupt_mask: ::std::os::raw::c_ulong,
pub interrupt_lock: rb_nativethread_lock_t,
pub interrupt_cond: rb_nativethread_cond_t,
pub unblock: rb_unblock_callback,
pub locking_mutex: VALUE,
pub keeping_mutexes: *mut rb_mutex_struct,
pub tag: *mut rb_vm_tag,
pub protect_tag: *mut rb_vm_protect_tag,
pub parse_in_eval: ::std::os::raw::c_int,
pub mild_compile_error: ::std::os::raw::c_int,
pub local_storage: *mut st_table,
pub local_storage_recursive_hash: VALUE,
pub local_storage_recursive_hash_for_trace: VALUE,
pub join_list: *mut rb_thread_list_t,
pub first_proc: VALUE,
pub first_args: VALUE,
pub first_func: ::std::option::Option<unsafe extern "C" fn() -> VALUE>,
pub machine: rb_thread_struct__bindgen_ty_1,
pub stat_insn_usage: VALUE,
pub event_hooks: rb_hook_list_t,
pub trace_arg: *mut rb_trace_arg_struct,
pub fiber: *mut rb_fiber_t,
pub root_fiber: *mut rb_fiber_t,
pub root_jmpbuf: rb_jmpbuf_t,
pub ensure_list: *mut rb_ensure_list_t,
pub method_missing_reason: ::std::os::raw::c_int,
pub abort_on_exception: ::std::os::raw::c_int,
pub altstack: *mut ::std::os::raw::c_void,
pub running_time_us: ::std::os::raw::c_ulong,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_thread_struct__bindgen_ty_1 {
pub stack_start: *mut VALUE,
pub stack_end: *mut VALUE,
pub stack_maxsize: size_t,
pub regs: jmp_buf,
}
#[test]
fn bindgen_test_layout_rb_thread_struct__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<rb_thread_struct__bindgen_ty_1>(),
224usize,
concat!("Size of: ", stringify!(rb_thread_struct__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<rb_thread_struct__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(rb_thread_struct__bindgen_ty_1))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct__bindgen_ty_1>())).stack_start as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct__bindgen_ty_1),
"::",
stringify!(stack_start)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct__bindgen_ty_1>())).stack_end as *const _
as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct__bindgen_ty_1),
"::",
stringify!(stack_end)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct__bindgen_ty_1>())).stack_maxsize as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct__bindgen_ty_1),
"::",
stringify!(stack_maxsize)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct__bindgen_ty_1>())).regs as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct__bindgen_ty_1),
"::",
stringify!(regs)
)
);
}
#[test]
fn bindgen_test_layout_rb_thread_struct() {
assert_eq!(
::std::mem::size_of::<rb_thread_struct>(),
1008usize,
concat!("Size of: ", stringify!(rb_thread_struct))
);
assert_eq!(
::std::mem::align_of::<rb_thread_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_thread_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).vmlt_node as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(vmlt_node)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).self_ as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).vm as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(vm)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).stack as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(stack)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).stack_size as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(stack_size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).cfp as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(cfp)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).safe_level as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(safe_level)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).raised_flag as *const _ as usize },
60usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(raised_flag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).last_status as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(last_status)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).state as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(state)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).waiting_fd as *const _ as usize },
76usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(waiting_fd)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).passed_block as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(passed_block)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).passed_bmethod_me as *const _ as usize
},
88usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(passed_bmethod_me)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).passed_ci as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(passed_ci)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).top_self as *const _ as usize },
104usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(top_self)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).top_wrapper as *const _ as usize },
112usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(top_wrapper)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).base_block as *const _ as usize },
120usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(base_block)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).root_lep as *const _ as usize },
128usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(root_lep)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).root_svar as *const _ as usize },
136usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(root_svar)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).thread_id as *const _ as usize },
144usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(thread_id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).status as *const _ as usize },
152usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(status)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).to_kill as *const _ as usize },
156usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(to_kill)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).priority as *const _ as usize },
160usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(priority)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).mark_stack_len as *const _ as usize },
164usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(mark_stack_len)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).native_thread_data as *const _ as usize
},
168usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(native_thread_data)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).blocking_region_buffer as *const _ as usize
},
232usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(blocking_region_buffer)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).thgroup as *const _ as usize },
240usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(thgroup)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).value as *const _ as usize },
248usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(value)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).errinfo as *const _ as usize },
256usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(errinfo)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).pending_interrupt_queue as *const _
as usize
},
264usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(pending_interrupt_queue)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).pending_interrupt_mask_stack as *const _
as usize
},
272usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(pending_interrupt_mask_stack)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).pending_interrupt_queue_checked as *const _
as usize
},
280usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(pending_interrupt_queue_checked)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).interrupt_flag as *const _ as usize },
284usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(interrupt_flag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).interrupt_mask as *const _ as usize },
288usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(interrupt_mask)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).interrupt_lock as *const _ as usize },
296usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(interrupt_lock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).interrupt_cond as *const _ as usize },
336usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(interrupt_cond)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).unblock as *const _ as usize },
392usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(unblock)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).locking_mutex as *const _ as usize },
408usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(locking_mutex)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).keeping_mutexes as *const _ as usize
},
416usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(keeping_mutexes)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).tag as *const _ as usize },
424usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(tag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).protect_tag as *const _ as usize },
432usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(protect_tag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).parse_in_eval as *const _ as usize },
440usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(parse_in_eval)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).mild_compile_error as *const _ as usize
},
444usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(mild_compile_error)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).local_storage as *const _ as usize },
448usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(local_storage)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).local_storage_recursive_hash as *const _
as usize
},
456usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(local_storage_recursive_hash)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).local_storage_recursive_hash_for_trace
as *const _ as usize
},
464usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(local_storage_recursive_hash_for_trace)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).join_list as *const _ as usize },
472usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(join_list)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).first_proc as *const _ as usize },
480usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(first_proc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).first_args as *const _ as usize },
488usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(first_args)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).first_func as *const _ as usize },
496usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(first_func)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).machine as *const _ as usize },
504usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(machine)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).stat_insn_usage as *const _ as usize
},
728usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(stat_insn_usage)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).event_hooks as *const _ as usize },
736usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(event_hooks)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).trace_arg as *const _ as usize },
752usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(trace_arg)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).fiber as *const _ as usize },
760usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(fiber)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).root_fiber as *const _ as usize },
768usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(root_fiber)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).root_jmpbuf as *const _ as usize },
776usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(root_jmpbuf)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).ensure_list as *const _ as usize },
976usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(ensure_list)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).method_missing_reason as *const _ as usize
},
984usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(method_missing_reason)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).abort_on_exception as *const _ as usize
},
988usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(abort_on_exception)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_thread_struct>())).altstack as *const _ as usize },
992usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(altstack)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_thread_struct>())).running_time_us as *const _ as usize
},
1000usize,
concat!(
"Offset of field: ",
stringify!(rb_thread_struct),
"::",
stringify!(running_time_us)
)
);
}
impl ::std::fmt::Debug for rb_thread_struct {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
write ! (f , "rb_thread_struct {{ vmlt_node: {:?}, self: {:?}, vm: {:?}, stack: {:?}, stack_size: {:?}, cfp: {:?}, safe_level: {:?}, raised_flag: {:?}, last_status: {:?}, state: {:?}, waiting_fd: {:?}, passed_block: {:?}, passed_bmethod_me: {:?}, passed_ci: {:?}, top_self: {:?}, top_wrapper: {:?}, base_block: {:?}, root_lep: {:?}, root_svar: {:?}, thread_id: {:?}, status: {:?}, to_kill: {:?}, priority: {:?}, mark_stack_len: {:?}, native_thread_data: {:?}, blocking_region_buffer: {:?}, thgroup: {:?}, value: {:?}, errinfo: {:?}, pending_interrupt_queue: {:?}, pending_interrupt_mask_stack: {:?}, pending_interrupt_queue_checked: {:?}, interrupt_flag: {:?}, interrupt_mask: {:?}, interrupt_lock: {:?}, interrupt_cond: {:?}, unblock: {:?}, locking_mutex: {:?}, keeping_mutexes: {:?}, tag: {:?}, protect_tag: {:?}, parse_in_eval: {:?}, mild_compile_error: {:?}, local_storage: {:?}, local_storage_recursive_hash: {:?}, local_storage_recursive_hash_for_trace: {:?}, join_list: {:?}, first_proc: {:?}, first_args: {:?}, first_func: {:?}, machine: {:?}, stat_insn_usage: {:?}, event_hooks: {:?}, trace_arg: {:?}, fiber: {:?}, root_fiber: {:?}, root_jmpbuf: {:?}, ensure_list: {:?}, method_missing_reason: {:?}, abort_on_exception: {:?}, altstack: {:?}, running_time_us: {:?} }}" , self . vmlt_node , self . self_ , self . vm , self . stack , self . stack_size , self . cfp , self . safe_level , self . raised_flag , self . last_status , self . state , self . waiting_fd , self . passed_block , self . passed_bmethod_me , self . passed_ci , self . top_self , self . top_wrapper , self . base_block , self . root_lep , self . root_svar , self . thread_id , self . status , self . to_kill , self . priority , self . mark_stack_len , self . native_thread_data , self . blocking_region_buffer , self . thgroup , self . value , self . errinfo , self . pending_interrupt_queue , self . pending_interrupt_mask_stack , self . pending_interrupt_queue_checked , self . interrupt_flag , self . interrupt_mask , self . interrupt_lock , self . interrupt_cond , self . unblock , self . locking_mutex , self . keeping_mutexes , self . tag , self . protect_tag , self . parse_in_eval , self . mild_compile_error , self . local_storage , self . local_storage_recursive_hash , self . local_storage_recursive_hash_for_trace , self . join_list , self . first_proc , self . first_args , self . first_func , self . machine , self . stat_insn_usage , self . event_hooks , self . trace_arg , self . fiber , self . root_fiber , self . root_jmpbuf , self . ensure_list , self . method_missing_reason , self . abort_on_exception , self . altstack , self . running_time_us)
}
}
pub type rb_thread_t = rb_thread_struct;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_trace_arg_struct {
pub event: rb_event_flag_t,
pub th: *mut rb_thread_t,
pub cfp: *mut rb_control_frame_t,
pub self_: VALUE,
pub id: ID,
pub klass: VALUE,
pub data: VALUE,
pub klass_solved: ::std::os::raw::c_int,
pub lineno: ::std::os::raw::c_int,
pub path: VALUE,
}
#[test]
fn bindgen_test_layout_rb_trace_arg_struct() {
assert_eq!(
::std::mem::size_of::<rb_trace_arg_struct>(),
72usize,
concat!("Size of: ", stringify!(rb_trace_arg_struct))
);
assert_eq!(
::std::mem::align_of::<rb_trace_arg_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_trace_arg_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).event as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(event)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).th as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(th)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).cfp as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(cfp)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).self_ as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(self_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).id as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(id)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).klass as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(klass)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).data as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(data)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_trace_arg_struct>())).klass_solved as *const _ as usize
},
56usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(klass_solved)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).lineno as *const _ as usize },
60usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(lineno)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_trace_arg_struct>())).path as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(rb_trace_arg_struct),
"::",
stringify!(path)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_compile_option_struct {
pub inline_const_cache: ::std::os::raw::c_int,
pub peephole_optimization: ::std::os::raw::c_int,
pub tailcall_optimization: ::std::os::raw::c_int,
pub specialized_instruction: ::std::os::raw::c_int,
pub operands_unification: ::std::os::raw::c_int,
pub instructions_unification: ::std::os::raw::c_int,
pub stack_caching: ::std::os::raw::c_int,
pub trace_instruction: ::std::os::raw::c_int,
pub debug_level: ::std::os::raw::c_int,
}
#[test]
fn bindgen_test_layout_rb_compile_option_struct() {
assert_eq!(
::std::mem::size_of::<rb_compile_option_struct>(),
36usize,
concat!("Size of: ", stringify!(rb_compile_option_struct))
);
assert_eq!(
::std::mem::align_of::<rb_compile_option_struct>(),
4usize,
concat!("Alignment of ", stringify!(rb_compile_option_struct))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).inline_const_cache as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(inline_const_cache)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).peephole_optimization as *const _
as usize
},
4usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(peephole_optimization)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).tailcall_optimization as *const _
as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(tailcall_optimization)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).specialized_instruction as *const _
as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(specialized_instruction)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).operands_unification as *const _
as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(operands_unification)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).instructions_unification
as *const _ as usize
},
20usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(instructions_unification)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).stack_caching as *const _ as usize
},
24usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(stack_caching)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).trace_instruction as *const _
as usize
},
28usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(trace_instruction)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_compile_option_struct>())).debug_level as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(rb_compile_option_struct),
"::",
stringify!(debug_level)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_line_info_entry {
pub position: ::std::os::raw::c_uint,
pub line_no: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout_iseq_line_info_entry() {
assert_eq!(
::std::mem::size_of::<iseq_line_info_entry>(),
8usize,
concat!("Size of: ", stringify!(iseq_line_info_entry))
);
assert_eq!(
::std::mem::align_of::<iseq_line_info_entry>(),
4usize,
concat!("Alignment of ", stringify!(iseq_line_info_entry))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_line_info_entry>())).position as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_line_info_entry),
"::",
stringify!(position)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_line_info_entry>())).line_no as *const _ as usize },
4usize,
concat!(
"Offset of field: ",
stringify!(iseq_line_info_entry),
"::",
stringify!(line_no)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_catch_table_entry {
pub type_: iseq_catch_table_entry_catch_type,
pub iseq: VALUE,
pub start: ::std::os::raw::c_uint,
pub end: ::std::os::raw::c_uint,
pub cont: ::std::os::raw::c_uint,
pub sp: ::std::os::raw::c_uint,
}
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_RESCUE: iseq_catch_table_entry_catch_type =
3;
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_ENSURE: iseq_catch_table_entry_catch_type =
5;
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_RETRY: iseq_catch_table_entry_catch_type = 7;
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_BREAK: iseq_catch_table_entry_catch_type = 9;
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_REDO: iseq_catch_table_entry_catch_type = 11;
pub const iseq_catch_table_entry_catch_type_CATCH_TYPE_NEXT: iseq_catch_table_entry_catch_type = 13;
pub type iseq_catch_table_entry_catch_type = ::std::os::raw::c_uint;
#[test]
fn bindgen_test_layout_iseq_catch_table_entry() {
assert_eq!(
::std::mem::size_of::<iseq_catch_table_entry>(),
32usize,
concat!("Size of: ", stringify!(iseq_catch_table_entry))
);
assert_eq!(
::std::mem::align_of::<iseq_catch_table_entry>(),
8usize,
concat!("Alignment of ", stringify!(iseq_catch_table_entry))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).type_ as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(type_)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).iseq as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(iseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).start as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(start)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).end as *const _ as usize },
20usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(end)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).cont as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(cont)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table_entry>())).sp as *const _ as usize },
28usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table_entry),
"::",
stringify!(sp)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_catch_table {
pub size: ::std::os::raw::c_int,
pub entries: [iseq_catch_table_entry; 1usize],
}
#[test]
fn bindgen_test_layout_iseq_catch_table() {
assert_eq!(
::std::mem::size_of::<iseq_catch_table>(),
40usize,
concat!("Size of: ", stringify!(iseq_catch_table))
);
assert_eq!(
::std::mem::align_of::<iseq_catch_table>(),
8usize,
concat!("Alignment of ", stringify!(iseq_catch_table))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table>())).size as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table),
"::",
stringify!(size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_catch_table>())).entries as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_catch_table),
"::",
stringify!(entries)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_compile_data_storage {
pub next: *mut iseq_compile_data_storage,
pub pos: ::std::os::raw::c_uint,
pub size: ::std::os::raw::c_uint,
pub buff: [::std::os::raw::c_char; 1usize],
}
#[test]
fn bindgen_test_layout_iseq_compile_data_storage() {
assert_eq!(
::std::mem::size_of::<iseq_compile_data_storage>(),
24usize,
concat!("Size of: ", stringify!(iseq_compile_data_storage))
);
assert_eq!(
::std::mem::align_of::<iseq_compile_data_storage>(),
8usize,
concat!("Alignment of ", stringify!(iseq_compile_data_storage))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data_storage>())).next as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data_storage),
"::",
stringify!(next)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data_storage>())).pos as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data_storage),
"::",
stringify!(pos)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data_storage>())).size as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data_storage),
"::",
stringify!(size)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data_storage>())).buff as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data_storage),
"::",
stringify!(buff)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_compile_data {
pub err_info: VALUE,
pub mark_ary: VALUE,
pub catch_table_ary: VALUE,
pub start_label: *mut iseq_label_data,
pub end_label: *mut iseq_label_data,
pub redo_label: *mut iseq_label_data,
pub current_block: VALUE,
pub ensure_node: VALUE,
pub for_iseq: VALUE,
pub ensure_node_stack: *mut iseq_compile_data_ensure_node_stack,
pub loopval_popped: ::std::os::raw::c_int,
pub cached_const: ::std::os::raw::c_int,
pub storage_head: *mut iseq_compile_data_storage,
pub storage_current: *mut iseq_compile_data_storage,
pub last_line: ::std::os::raw::c_int,
pub last_coverable_line: ::std::os::raw::c_int,
pub label_no: ::std::os::raw::c_int,
pub node_level: ::std::os::raw::c_int,
pub option: *const rb_compile_option_t,
}
#[test]
fn bindgen_test_layout_iseq_compile_data() {
assert_eq!(
::std::mem::size_of::<iseq_compile_data>(),
128usize,
concat!("Size of: ", stringify!(iseq_compile_data))
);
assert_eq!(
::std::mem::align_of::<iseq_compile_data>(),
8usize,
concat!("Alignment of ", stringify!(iseq_compile_data))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).err_info as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(err_info)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).mark_ary as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(mark_ary)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_compile_data>())).catch_table_ary as *const _ as usize
},
16usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(catch_table_ary)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).start_label as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(start_label)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).end_label as *const _ as usize },
32usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(end_label)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).redo_label as *const _ as usize },
40usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(redo_label)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).current_block as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(current_block)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).ensure_node as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(ensure_node)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).for_iseq as *const _ as usize },
64usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(for_iseq)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_compile_data>())).ensure_node_stack as *const _ as usize
},
72usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(ensure_node_stack)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_compile_data>())).loopval_popped as *const _ as usize
},
80usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(loopval_popped)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).cached_const as *const _ as usize },
84usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(cached_const)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).storage_head as *const _ as usize },
88usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(storage_head)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_compile_data>())).storage_current as *const _ as usize
},
96usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(storage_current)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).last_line as *const _ as usize },
104usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(last_line)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<iseq_compile_data>())).last_coverable_line as *const _ as usize
},
108usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(last_coverable_line)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).label_no as *const _ as usize },
112usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(label_no)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).node_level as *const _ as usize },
116usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(node_level)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<iseq_compile_data>())).option as *const _ as usize },
120usize,
concat!(
"Offset of field: ",
stringify!(iseq_compile_data),
"::",
stringify!(option)
)
);
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct st_table_entry {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct st_packed_entry {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_event_hook_struct {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct rb_postponed_job_struct {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct iseq_label_data {
pub _address: u8,
}
| {
assert_eq!(
::std::mem::size_of::<rb_call_info_struct>(),
104usize,
concat!("Size of: ", stringify!(rb_call_info_struct))
);
assert_eq!(
::std::mem::align_of::<rb_call_info_struct>(),
8usize,
concat!("Alignment of ", stringify!(rb_call_info_struct))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).mid as *const _ as usize },
0usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(mid)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).flag as *const _ as usize },
8usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(flag)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).orig_argc as *const _ as usize },
12usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(orig_argc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).blockiseq as *const _ as usize },
16usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(blockiseq)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).kw_arg as *const _ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(kw_arg)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct>())).method_state as *const _ as usize
},
32usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(method_state)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct>())).class_serial as *const _ as usize
},
40usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(class_serial)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).klass as *const _ as usize },
48usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(klass)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).me as *const _ as usize },
56usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(me)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rb_call_info_struct>())).defined_class as *const _ as usize
},
64usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(defined_class)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).blockptr as *const _ as usize },
72usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(blockptr)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).recv as *const _ as usize },
80usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(recv)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).argc as *const _ as usize },
88usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(argc)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).aux as *const _ as usize },
92usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(aux)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<rb_call_info_struct>())).call as *const _ as usize },
96usize,
concat!(
"Offset of field: ",
stringify!(rb_call_info_struct),
"::",
stringify!(call)
)
);
} |
rtc.rs | ::bobbin_mcu::periph!( RTC, Rtc, RTC_PERIPH, RtcPeriph, RTC_OWNED, RTC_REF_COUNT, 0x40002800, 0x00, 0x19);
// Gate { name: None, gate_type: Some("RST"), periph: Some("RCC"), register: Some("BDCR"), field: Some("BDRST"), description: None }
impl ::bobbin_mcu::gate::GateRst for Rtc {
#[inline]
fn gate_rst(&self) -> ::bobbin_bits::U1 { ::rcc::RCC.bdcr().bdrst() }
#[inline]
fn set_gate_rst<V: Into<::bobbin_bits::U1>>(&self, value: V) -> &Self {
::rcc::RCC.with_bdcr(|r| r.set_bdrst(value));
self
}
}
// Gate { name: None, gate_type: Some("EN"), periph: Some("RCC"), register: Some("BDCR"), field: Some("RTCEN"), description: None }
impl ::bobbin_mcu::gate::GateEn for Rtc {
#[inline]
fn gate_en(&self) -> ::bobbin_bits::U1 { ::rcc::RCC.bdcr().rtcen() }
#[inline]
fn set_gate_en<V: Into<::bobbin_bits::U1>>(&self, value: V) -> &Self {
::rcc::RCC.with_bdcr(|r| r.set_rtcen(value));
self
}
}
// Gate { name: None, gate_type: Some("SLEEP_EN"), periph: Some("RCC"), register: Some("APB1SMENR1"), field: Some("RTCAPBSMEN"), description: None }
impl ::bobbin_mcu::gate::GateSleepEn for Rtc {
#[inline]
fn gate_sleep_en(&self) -> ::bobbin_bits::U1 { ::rcc::RCC.apb1smenr1().rtcapbsmen() }
#[inline]
fn set_gate_sleep_en<V: Into<::bobbin_bits::U1>>(&self, value: V) -> &Self {
::rcc::RCC.with_apb1smenr1(|r| r.set_rtcapbsmen(value));
self
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[doc="RTC Peripheral"]
pub struct RtcPeriph(pub usize);
impl RtcPeriph {
#[doc="Get the TR Register."]
#[inline] pub fn tr_reg(&self) -> ::bobbin_mcu::register::Register<Tr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Tr, 0x0)
}
#[doc="Get the *mut pointer for the TR register."]
#[inline] pub fn tr_mut(&self) -> *mut Tr {
self.tr_reg().ptr()
}
#[doc="Get the *const pointer for the TR register."]
#[inline] pub fn tr_ptr(&self) -> *const Tr {
self.tr_reg().ptr()
}
#[doc="Read the TR register."]
#[inline] pub fn tr(&self) -> Tr {
self.tr_reg().read()
}
#[doc="Write the TR register."]
#[inline] pub fn write_tr(&self, value: Tr) -> &Self {
self.tr_reg().write(value);
self
}
#[doc="Set the TR register."]
#[inline] pub fn set_tr<F: FnOnce(Tr) -> Tr>(&self, f: F) -> &Self {
self.tr_reg().set(f);
self
}
#[doc="Modify the TR register."]
#[inline] pub fn with_tr<F: FnOnce(Tr) -> Tr>(&self, f: F) -> &Self {
self.tr_reg().with(f);
self
}
#[doc="Get the DR Register."]
#[inline] pub fn dr_reg(&self) -> ::bobbin_mcu::register::Register<Dr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Dr, 0x4)
}
#[doc="Get the *mut pointer for the DR register."]
#[inline] pub fn dr_mut(&self) -> *mut Dr {
self.dr_reg().ptr()
}
#[doc="Get the *const pointer for the DR register."]
#[inline] pub fn dr_ptr(&self) -> *const Dr {
self.dr_reg().ptr()
}
#[doc="Read the DR register."]
#[inline] pub fn dr(&self) -> Dr {
self.dr_reg().read()
}
#[doc="Write the DR register."]
#[inline] pub fn write_dr(&self, value: Dr) -> &Self {
self.dr_reg().write(value);
self
}
#[doc="Set the DR register."]
#[inline] pub fn set_dr<F: FnOnce(Dr) -> Dr>(&self, f: F) -> &Self {
self.dr_reg().set(f);
self
}
#[doc="Modify the DR register."]
#[inline] pub fn with_dr<F: FnOnce(Dr) -> Dr>(&self, f: F) -> &Self {
self.dr_reg().with(f);
self
}
#[doc="Get the CR Register."]
#[inline] pub fn cr_reg(&self) -> ::bobbin_mcu::register::Register<Cr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Cr, 0x8)
}
#[doc="Get the *mut pointer for the CR register."]
#[inline] pub fn cr_mut(&self) -> *mut Cr {
self.cr_reg().ptr()
}
#[doc="Get the *const pointer for the CR register."]
#[inline] pub fn cr_ptr(&self) -> *const Cr {
self.cr_reg().ptr()
}
#[doc="Read the CR register."]
#[inline] pub fn cr(&self) -> Cr {
self.cr_reg().read()
}
#[doc="Write the CR register."]
#[inline] pub fn write_cr(&self, value: Cr) -> &Self {
self.cr_reg().write(value);
self
}
#[doc="Set the CR register."]
#[inline] pub fn set_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) -> &Self {
self.cr_reg().set(f);
self
}
#[doc="Modify the CR register."]
#[inline] pub fn with_cr<F: FnOnce(Cr) -> Cr>(&self, f: F) -> &Self {
self.cr_reg().with(f);
self
}
#[doc="Get the ISR Register."]
#[inline] pub fn isr_reg(&self) -> ::bobbin_mcu::register::Register<Isr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Isr, 0xc)
}
#[doc="Get the *mut pointer for the ISR register."]
#[inline] pub fn isr_mut(&self) -> *mut Isr {
self.isr_reg().ptr()
}
#[doc="Get the *const pointer for the ISR register."]
#[inline] pub fn isr_ptr(&self) -> *const Isr {
self.isr_reg().ptr()
}
#[doc="Read the ISR register."]
#[inline] pub fn isr(&self) -> Isr {
self.isr_reg().read()
}
#[doc="Write the ISR register."]
#[inline] pub fn write_isr(&self, value: Isr) -> &Self {
self.isr_reg().write(value);
self
}
#[doc="Set the ISR register."]
#[inline] pub fn set_isr<F: FnOnce(Isr) -> Isr>(&self, f: F) -> &Self {
self.isr_reg().set(f);
self
}
#[doc="Modify the ISR register."]
#[inline] pub fn with_isr<F: FnOnce(Isr) -> Isr>(&self, f: F) -> &Self {
self.isr_reg().with(f);
self
}
#[doc="Get the PRER Register."]
#[inline] pub fn prer_reg(&self) -> ::bobbin_mcu::register::Register<Prer> {
::bobbin_mcu::register::Register::new(self.0 as *mut Prer, 0x10)
}
#[doc="Get the *mut pointer for the PRER register."]
#[inline] pub fn prer_mut(&self) -> *mut Prer {
self.prer_reg().ptr()
}
#[doc="Get the *const pointer for the PRER register."]
#[inline] pub fn prer_ptr(&self) -> *const Prer {
self.prer_reg().ptr()
}
#[doc="Read the PRER register."]
#[inline] pub fn prer(&self) -> Prer {
self.prer_reg().read()
}
#[doc="Write the PRER register."]
#[inline] pub fn write_prer(&self, value: Prer) -> &Self {
self.prer_reg().write(value);
self
}
#[doc="Set the PRER register."]
#[inline] pub fn set_prer<F: FnOnce(Prer) -> Prer>(&self, f: F) -> &Self {
self.prer_reg().set(f);
self
}
#[doc="Modify the PRER register."]
#[inline] pub fn with_prer<F: FnOnce(Prer) -> Prer>(&self, f: F) -> &Self {
self.prer_reg().with(f);
self
}
#[doc="Get the WUTR Register."]
#[inline] pub fn wutr_reg(&self) -> ::bobbin_mcu::register::Register<Wutr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Wutr, 0x14)
}
#[doc="Get the *mut pointer for the WUTR register."]
#[inline] pub fn wutr_mut(&self) -> *mut Wutr {
self.wutr_reg().ptr()
}
#[doc="Get the *const pointer for the WUTR register."]
#[inline] pub fn wutr_ptr(&self) -> *const Wutr {
self.wutr_reg().ptr()
}
#[doc="Read the WUTR register."]
#[inline] pub fn wutr(&self) -> Wutr {
self.wutr_reg().read()
}
#[doc="Write the WUTR register."]
#[inline] pub fn write_wutr(&self, value: Wutr) -> &Self {
self.wutr_reg().write(value);
self
}
#[doc="Set the WUTR register."]
#[inline] pub fn set_wutr<F: FnOnce(Wutr) -> Wutr>(&self, f: F) -> &Self {
self.wutr_reg().set(f);
self
}
#[doc="Modify the WUTR register."]
#[inline] pub fn with_wutr<F: FnOnce(Wutr) -> Wutr>(&self, f: F) -> &Self {
self.wutr_reg().with(f);
self
}
#[doc="Get the ALRMAR Register."]
#[inline] pub fn alrmar_reg(&self) -> ::bobbin_mcu::register::Register<Alrmar> {
::bobbin_mcu::register::Register::new(self.0 as *mut Alrmar, 0x1c)
}
#[doc="Get the *mut pointer for the ALRMAR register."]
#[inline] pub fn alrmar_mut(&self) -> *mut Alrmar {
self.alrmar_reg().ptr()
}
#[doc="Get the *const pointer for the ALRMAR register."]
#[inline] pub fn alrmar_ptr(&self) -> *const Alrmar {
self.alrmar_reg().ptr()
}
#[doc="Read the ALRMAR register."]
#[inline] pub fn alrmar(&self) -> Alrmar {
self.alrmar_reg().read()
}
#[doc="Write the ALRMAR register."]
#[inline] pub fn write_alrmar(&self, value: Alrmar) -> &Self {
self.alrmar_reg().write(value);
self
}
#[doc="Set the ALRMAR register."]
#[inline] pub fn set_alrmar<F: FnOnce(Alrmar) -> Alrmar>(&self, f: F) -> &Self {
self.alrmar_reg().set(f);
self
}
#[doc="Modify the ALRMAR register."]
#[inline] pub fn with_alrmar<F: FnOnce(Alrmar) -> Alrmar>(&self, f: F) -> &Self {
self.alrmar_reg().with(f);
self
}
#[doc="Get the ALRMBR Register."]
#[inline] pub fn alrmbr_reg(&self) -> ::bobbin_mcu::register::Register<Alrmbr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Alrmbr, 0x20)
}
#[doc="Get the *mut pointer for the ALRMBR register."]
#[inline] pub fn alrmbr_mut(&self) -> *mut Alrmbr {
self.alrmbr_reg().ptr()
}
#[doc="Get the *const pointer for the ALRMBR register."]
#[inline] pub fn alrmbr_ptr(&self) -> *const Alrmbr {
self.alrmbr_reg().ptr()
}
#[doc="Read the ALRMBR register."]
#[inline] pub fn alrmbr(&self) -> Alrmbr {
self.alrmbr_reg().read()
}
#[doc="Write the ALRMBR register."]
#[inline] pub fn write_alrmbr(&self, value: Alrmbr) -> &Self {
self.alrmbr_reg().write(value);
self
}
#[doc="Set the ALRMBR register."]
#[inline] pub fn set_alrmbr<F: FnOnce(Alrmbr) -> Alrmbr>(&self, f: F) -> &Self {
self.alrmbr_reg().set(f);
self
}
#[doc="Modify the ALRMBR register."]
#[inline] pub fn with_alrmbr<F: FnOnce(Alrmbr) -> Alrmbr>(&self, f: F) -> &Self {
self.alrmbr_reg().with(f);
self
}
#[doc="Get the WPR Register."]
#[inline] pub fn wpr_reg(&self) -> ::bobbin_mcu::register::Register<Wpr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Wpr, 0x24)
}
#[doc="Get the *mut pointer for the WPR register."]
#[inline] pub fn wpr_mut(&self) -> *mut Wpr {
self.wpr_reg().ptr()
}
#[doc="Get the *const pointer for the WPR register."]
#[inline] pub fn wpr_ptr(&self) -> *const Wpr {
self.wpr_reg().ptr()
}
#[doc="Write the WPR register."]
#[inline] pub fn write_wpr(&self, value: Wpr) -> &Self {
self.wpr_reg().write(value);
self
}
#[doc="Set the WPR register."]
#[inline] pub fn set_wpr<F: FnOnce(Wpr) -> Wpr>(&self, f: F) -> &Self {
self.wpr_reg().set(f);
self
}
#[doc="Get the SSR Register."]
#[inline] pub fn ssr_reg(&self) -> ::bobbin_mcu::register::Register<Ssr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Ssr, 0x28)
}
#[doc="Get the *mut pointer for the SSR register."]
#[inline] pub fn ssr_mut(&self) -> *mut Ssr {
self.ssr_reg().ptr()
}
#[doc="Get the *const pointer for the SSR register."]
#[inline] pub fn ssr_ptr(&self) -> *const Ssr {
self.ssr_reg().ptr()
}
#[doc="Read the SSR register."]
#[inline] pub fn ssr(&self) -> Ssr {
self.ssr_reg().read()
}
#[doc="Get the SHIFTR Register."]
#[inline] pub fn shiftr_reg(&self) -> ::bobbin_mcu::register::Register<Shiftr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Shiftr, 0x2c)
}
#[doc="Get the *mut pointer for the SHIFTR register."]
#[inline] pub fn shiftr_mut(&self) -> *mut Shiftr {
self.shiftr_reg().ptr()
}
#[doc="Get the *const pointer for the SHIFTR register."]
#[inline] pub fn shiftr_ptr(&self) -> *const Shiftr {
self.shiftr_reg().ptr()
}
#[doc="Write the SHIFTR register."]
#[inline] pub fn write_shiftr(&self, value: Shiftr) -> &Self {
self.shiftr_reg().write(value);
self
}
#[doc="Set the SHIFTR register."]
#[inline] pub fn set_shiftr<F: FnOnce(Shiftr) -> Shiftr>(&self, f: F) -> &Self {
self.shiftr_reg().set(f);
self
}
#[doc="Get the TSTR Register."]
#[inline] pub fn tstr_reg(&self) -> ::bobbin_mcu::register::Register<Tstr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Tstr, 0x30)
}
#[doc="Get the *mut pointer for the TSTR register."]
#[inline] pub fn tstr_mut(&self) -> *mut Tstr {
self.tstr_reg().ptr()
}
#[doc="Get the *const pointer for the TSTR register."]
#[inline] pub fn tstr_ptr(&self) -> *const Tstr {
self.tstr_reg().ptr()
}
#[doc="Read the TSTR register."]
#[inline] pub fn tstr(&self) -> Tstr {
self.tstr_reg().read()
}
#[doc="Get the TSDR Register."]
#[inline] pub fn tsdr_reg(&self) -> ::bobbin_mcu::register::Register<Tsdr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Tsdr, 0x34)
}
#[doc="Get the *mut pointer for the TSDR register."]
#[inline] pub fn tsdr_mut(&self) -> *mut Tsdr {
self.tsdr_reg().ptr()
}
#[doc="Get the *const pointer for the TSDR register."]
#[inline] pub fn tsdr_ptr(&self) -> *const Tsdr {
self.tsdr_reg().ptr()
}
#[doc="Read the TSDR register."]
#[inline] pub fn tsdr(&self) -> Tsdr {
self.tsdr_reg().read()
}
#[doc="Get the TSSSR Register."]
#[inline] pub fn tsssr_reg(&self) -> ::bobbin_mcu::register::Register<Tsssr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Tsssr, 0x38)
}
#[doc="Get the *mut pointer for the TSSSR register."]
#[inline] pub fn tsssr_mut(&self) -> *mut Tsssr {
self.tsssr_reg().ptr()
}
#[doc="Get the *const pointer for the TSSSR register."]
#[inline] pub fn tsssr_ptr(&self) -> *const Tsssr {
self.tsssr_reg().ptr()
}
#[doc="Read the TSSSR register."]
#[inline] pub fn tsssr(&self) -> Tsssr {
self.tsssr_reg().read()
}
#[doc="Get the CALR Register."]
#[inline] pub fn calr_reg(&self) -> ::bobbin_mcu::register::Register<Calr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Calr, 0x3c)
}
#[doc="Get the *mut pointer for the CALR register."]
#[inline] pub fn calr_mut(&self) -> *mut Calr {
self.calr_reg().ptr()
}
#[doc="Get the *const pointer for the CALR register."]
#[inline] pub fn calr_ptr(&self) -> *const Calr {
self.calr_reg().ptr()
}
#[doc="Read the CALR register."]
#[inline] pub fn calr(&self) -> Calr {
self.calr_reg().read()
}
#[doc="Write the CALR register."]
#[inline] pub fn write_calr(&self, value: Calr) -> &Self {
self.calr_reg().write(value);
self
}
#[doc="Set the CALR register."]
#[inline] pub fn set_calr<F: FnOnce(Calr) -> Calr>(&self, f: F) -> &Self {
self.calr_reg().set(f);
self
}
#[doc="Modify the CALR register."]
#[inline] pub fn with_calr<F: FnOnce(Calr) -> Calr>(&self, f: F) -> &Self {
self.calr_reg().with(f);
self
}
#[doc="Get the TAMPCR Register."]
#[inline] pub fn tampcr_reg(&self) -> ::bobbin_mcu::register::Register<Tampcr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Tampcr, 0x40)
}
#[doc="Get the *mut pointer for the TAMPCR register."]
#[inline] pub fn tampcr_mut(&self) -> *mut Tampcr {
self.tampcr_reg().ptr()
}
#[doc="Get the *const pointer for the TAMPCR register."]
#[inline] pub fn tampcr_ptr(&self) -> *const Tampcr {
self.tampcr_reg().ptr()
}
#[doc="Read the TAMPCR register."]
#[inline] pub fn tampcr(&self) -> Tampcr {
self.tampcr_reg().read()
}
#[doc="Write the TAMPCR register."]
#[inline] pub fn write_tampcr(&self, value: Tampcr) -> &Self {
self.tampcr_reg().write(value);
self
}
#[doc="Set the TAMPCR register."]
#[inline] pub fn set_tampcr<F: FnOnce(Tampcr) -> Tampcr>(&self, f: F) -> &Self {
self.tampcr_reg().set(f);
self
}
#[doc="Modify the TAMPCR register."]
#[inline] pub fn with_tampcr<F: FnOnce(Tampcr) -> Tampcr>(&self, f: F) -> &Self {
self.tampcr_reg().with(f);
self
}
#[doc="Get the ALRMASSR Register."]
#[inline] pub fn alrmassr_reg(&self) -> ::bobbin_mcu::register::Register<Alrmassr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Alrmassr, 0x44)
}
#[doc="Get the *mut pointer for the ALRMASSR register."]
#[inline] pub fn alrmassr_mut(&self) -> *mut Alrmassr {
self.alrmassr_reg().ptr()
}
#[doc="Get the *const pointer for the ALRMASSR register."]
#[inline] pub fn alrmassr_ptr(&self) -> *const Alrmassr {
self.alrmassr_reg().ptr()
}
#[doc="Read the ALRMASSR register."]
#[inline] pub fn alrmassr(&self) -> Alrmassr {
self.alrmassr_reg().read()
}
#[doc="Write the ALRMASSR register."]
#[inline] pub fn write_alrmassr(&self, value: Alrmassr) -> &Self {
self.alrmassr_reg().write(value);
self
}
#[doc="Set the ALRMASSR register."]
#[inline] pub fn set_alrmassr<F: FnOnce(Alrmassr) -> Alrmassr>(&self, f: F) -> &Self {
self.alrmassr_reg().set(f);
self
}
#[doc="Modify the ALRMASSR register."]
#[inline] pub fn with_alrmassr<F: FnOnce(Alrmassr) -> Alrmassr>(&self, f: F) -> &Self {
self.alrmassr_reg().with(f);
self
}
#[doc="Get the ALRMBSSR Register."]
#[inline] pub fn alrmbssr_reg(&self) -> ::bobbin_mcu::register::Register<Alrmbssr> {
::bobbin_mcu::register::Register::new(self.0 as *mut Alrmbssr, 0x48)
}
#[doc="Get the *mut pointer for the ALRMBSSR register."]
#[inline] pub fn alrmbssr_mut(&self) -> *mut Alrmbssr {
self.alrmbssr_reg().ptr()
}
#[doc="Get the *const pointer for the ALRMBSSR register."]
#[inline] pub fn alrmbssr_ptr(&self) -> *const Alrmbssr {
self.alrmbssr_reg().ptr()
}
#[doc="Read the ALRMBSSR register."]
#[inline] pub fn alrmbssr(&self) -> Alrmbssr {
self.alrmbssr_reg().read()
}
#[doc="Write the ALRMBSSR register."]
#[inline] pub fn write_alrmbssr(&self, value: Alrmbssr) -> &Self {
self.alrmbssr_reg().write(value);
self
}
#[doc="Set the ALRMBSSR register."]
#[inline] pub fn set_alrmbssr<F: FnOnce(Alrmbssr) -> Alrmbssr>(&self, f: F) -> &Self {
self.alrmbssr_reg().set(f);
self
}
#[doc="Modify the ALRMBSSR register."]
#[inline] pub fn with_alrmbssr<F: FnOnce(Alrmbssr) -> Alrmbssr>(&self, f: F) -> &Self {
self.alrmbssr_reg().with(f);
self
}
#[doc="Get the OR Register."]
#[inline] pub fn or_reg(&self) -> ::bobbin_mcu::register::Register<Or> {
::bobbin_mcu::register::Register::new(self.0 as *mut Or, 0x4c)
}
#[doc="Get the *mut pointer for the OR register."]
#[inline] pub fn or_mut(&self) -> *mut Or {
self.or_reg().ptr()
}
#[doc="Get the *const pointer for the OR register."]
#[inline] pub fn or_ptr(&self) -> *const Or {
self.or_reg().ptr()
}
#[doc="Read the OR register."]
#[inline] pub fn or(&self) -> Or {
self.or_reg().read()
}
#[doc="Write the OR register."]
#[inline] pub fn write_or(&self, value: Or) -> &Self {
self.or_reg().write(value);
self
}
#[doc="Set the OR register."]
#[inline] pub fn set_or<F: FnOnce(Or) -> Or>(&self, f: F) -> &Self {
self.or_reg().set(f);
self
}
#[doc="Modify the OR register."]
#[inline] pub fn with_or<F: FnOnce(Or) -> Or>(&self, f: F) -> &Self {
self.or_reg().with(f);
self
}
#[doc="Get the BKP0R Register."]
#[inline] pub fn bkp0r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp0r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp0r, 0x50)
}
#[doc="Get the *mut pointer for the BKP0R register."]
#[inline] pub fn bkp0r_mut(&self) -> *mut Bkp0r {
self.bkp0r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP0R register."]
#[inline] pub fn bkp0r_ptr(&self) -> *const Bkp0r {
self.bkp0r_reg().ptr()
}
#[doc="Read the BKP0R register."]
#[inline] pub fn bkp0r(&self) -> Bkp0r {
self.bkp0r_reg().read()
}
#[doc="Write the BKP0R register."]
#[inline] pub fn write_bkp0r(&self, value: Bkp0r) -> &Self {
self.bkp0r_reg().write(value);
self
}
#[doc="Set the BKP0R register."]
#[inline] pub fn set_bkp0r<F: FnOnce(Bkp0r) -> Bkp0r>(&self, f: F) -> &Self {
self.bkp0r_reg().set(f);
self
}
#[doc="Modify the BKP0R register."]
#[inline] pub fn with_bkp0r<F: FnOnce(Bkp0r) -> Bkp0r>(&self, f: F) -> &Self {
self.bkp0r_reg().with(f);
self
}
#[doc="Get the BKP1R Register."]
#[inline] pub fn bkp1r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp1r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp1r, 0x54)
}
#[doc="Get the *mut pointer for the BKP1R register."]
#[inline] pub fn bkp1r_mut(&self) -> *mut Bkp1r {
self.bkp1r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP1R register."]
#[inline] pub fn bkp1r_ptr(&self) -> *const Bkp1r {
self.bkp1r_reg().ptr()
}
#[doc="Read the BKP1R register."]
#[inline] pub fn bkp1r(&self) -> Bkp1r {
self.bkp1r_reg().read()
}
#[doc="Write the BKP1R register."]
#[inline] pub fn write_bkp1r(&self, value: Bkp1r) -> &Self {
self.bkp1r_reg().write(value);
self
}
#[doc="Set the BKP1R register."]
#[inline] pub fn set_bkp1r<F: FnOnce(Bkp1r) -> Bkp1r>(&self, f: F) -> &Self {
self.bkp1r_reg().set(f);
self
}
#[doc="Modify the BKP1R register."]
#[inline] pub fn with_bkp1r<F: FnOnce(Bkp1r) -> Bkp1r>(&self, f: F) -> &Self {
self.bkp1r_reg().with(f);
self
}
#[doc="Get the BKP2R Register."]
#[inline] pub fn bkp2r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp2r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp2r, 0x58)
}
#[doc="Get the *mut pointer for the BKP2R register."]
#[inline] pub fn bkp2r_mut(&self) -> *mut Bkp2r {
self.bkp2r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP2R register."]
#[inline] pub fn bkp2r_ptr(&self) -> *const Bkp2r {
self.bkp2r_reg().ptr()
}
#[doc="Read the BKP2R register."]
#[inline] pub fn bkp2r(&self) -> Bkp2r {
self.bkp2r_reg().read()
}
#[doc="Write the BKP2R register."]
#[inline] pub fn write_bkp2r(&self, value: Bkp2r) -> &Self {
self.bkp2r_reg().write(value);
self
}
#[doc="Set the BKP2R register."]
#[inline] pub fn set_bkp2r<F: FnOnce(Bkp2r) -> Bkp2r>(&self, f: F) -> &Self {
self.bkp2r_reg().set(f);
self
}
#[doc="Modify the BKP2R register."]
#[inline] pub fn with_bkp2r<F: FnOnce(Bkp2r) -> Bkp2r>(&self, f: F) -> &Self {
self.bkp2r_reg().with(f);
self
}
#[doc="Get the BKP3R Register."]
#[inline] pub fn bkp3r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp3r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp3r, 0x5c)
}
#[doc="Get the *mut pointer for the BKP3R register."]
#[inline] pub fn bkp3r_mut(&self) -> *mut Bkp3r {
self.bkp3r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP3R register."]
#[inline] pub fn bkp3r_ptr(&self) -> *const Bkp3r {
self.bkp3r_reg().ptr()
}
#[doc="Read the BKP3R register."]
#[inline] pub fn bkp3r(&self) -> Bkp3r {
self.bkp3r_reg().read()
}
#[doc="Write the BKP3R register."]
#[inline] pub fn write_bkp3r(&self, value: Bkp3r) -> &Self {
self.bkp3r_reg().write(value);
self
}
#[doc="Set the BKP3R register."]
#[inline] pub fn set_bkp3r<F: FnOnce(Bkp3r) -> Bkp3r>(&self, f: F) -> &Self {
self.bkp3r_reg().set(f);
self
}
#[doc="Modify the BKP3R register."]
#[inline] pub fn with_bkp3r<F: FnOnce(Bkp3r) -> Bkp3r>(&self, f: F) -> &Self {
self.bkp3r_reg().with(f);
self
}
#[doc="Get the BKP4R Register."]
#[inline] pub fn bkp4r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp4r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp4r, 0x60)
}
#[doc="Get the *mut pointer for the BKP4R register."]
#[inline] pub fn bkp4r_mut(&self) -> *mut Bkp4r {
self.bkp4r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP4R register."]
#[inline] pub fn bkp4r_ptr(&self) -> *const Bkp4r {
self.bkp4r_reg().ptr()
}
#[doc="Read the BKP4R register."]
#[inline] pub fn bkp4r(&self) -> Bkp4r {
self.bkp4r_reg().read()
}
#[doc="Write the BKP4R register."]
#[inline] pub fn write_bkp4r(&self, value: Bkp4r) -> &Self {
self.bkp4r_reg().write(value);
self
}
#[doc="Set the BKP4R register."]
#[inline] pub fn set_bkp4r<F: FnOnce(Bkp4r) -> Bkp4r>(&self, f: F) -> &Self {
self.bkp4r_reg().set(f);
self
}
#[doc="Modify the BKP4R register."]
#[inline] pub fn with_bkp4r<F: FnOnce(Bkp4r) -> Bkp4r>(&self, f: F) -> &Self {
self.bkp4r_reg().with(f);
self
}
#[doc="Get the BKP5R Register."]
#[inline] pub fn bkp5r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp5r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp5r, 0x64)
}
#[doc="Get the *mut pointer for the BKP5R register."]
#[inline] pub fn bkp5r_mut(&self) -> *mut Bkp5r {
self.bkp5r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP5R register."]
#[inline] pub fn bkp5r_ptr(&self) -> *const Bkp5r {
self.bkp5r_reg().ptr()
}
#[doc="Read the BKP5R register."]
#[inline] pub fn bkp5r(&self) -> Bkp5r {
self.bkp5r_reg().read()
}
#[doc="Write the BKP5R register."]
#[inline] pub fn write_bkp5r(&self, value: Bkp5r) -> &Self {
self.bkp5r_reg().write(value);
self
}
#[doc="Set the BKP5R register."]
#[inline] pub fn set_bkp5r<F: FnOnce(Bkp5r) -> Bkp5r>(&self, f: F) -> &Self {
self.bkp5r_reg().set(f);
self
}
#[doc="Modify the BKP5R register."]
#[inline] pub fn with_bkp5r<F: FnOnce(Bkp5r) -> Bkp5r>(&self, f: F) -> &Self {
self.bkp5r_reg().with(f);
self
}
#[doc="Get the BKP6R Register."]
#[inline] pub fn bkp6r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp6r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp6r, 0x68)
}
#[doc="Get the *mut pointer for the BKP6R register."]
#[inline] pub fn bkp6r_mut(&self) -> *mut Bkp6r {
self.bkp6r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP6R register."]
#[inline] pub fn bkp6r_ptr(&self) -> *const Bkp6r {
self.bkp6r_reg().ptr()
}
#[doc="Read the BKP6R register."]
#[inline] pub fn bkp6r(&self) -> Bkp6r {
self.bkp6r_reg().read()
}
#[doc="Write the BKP6R register."]
#[inline] pub fn write_bkp6r(&self, value: Bkp6r) -> &Self {
self.bkp6r_reg().write(value);
self
}
#[doc="Set the BKP6R register."]
#[inline] pub fn set_bkp6r<F: FnOnce(Bkp6r) -> Bkp6r>(&self, f: F) -> &Self {
self.bkp6r_reg().set(f);
self
}
#[doc="Modify the BKP6R register."]
#[inline] pub fn with_bkp6r<F: FnOnce(Bkp6r) -> Bkp6r>(&self, f: F) -> &Self {
self.bkp6r_reg().with(f);
self
}
#[doc="Get the BKP7R Register."]
#[inline] pub fn bkp7r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp7r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp7r, 0x6c)
}
#[doc="Get the *mut pointer for the BKP7R register."]
#[inline] pub fn bkp7r_mut(&self) -> *mut Bkp7r {
self.bkp7r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP7R register."]
#[inline] pub fn bkp7r_ptr(&self) -> *const Bkp7r {
self.bkp7r_reg().ptr()
}
#[doc="Read the BKP7R register."]
#[inline] pub fn bkp7r(&self) -> Bkp7r {
self.bkp7r_reg().read()
}
#[doc="Write the BKP7R register."]
#[inline] pub fn write_bkp7r(&self, value: Bkp7r) -> &Self {
self.bkp7r_reg().write(value);
self
}
#[doc="Set the BKP7R register."]
#[inline] pub fn set_bkp7r<F: FnOnce(Bkp7r) -> Bkp7r>(&self, f: F) -> &Self {
self.bkp7r_reg().set(f);
self
}
#[doc="Modify the BKP7R register."]
#[inline] pub fn with_bkp7r<F: FnOnce(Bkp7r) -> Bkp7r>(&self, f: F) -> &Self {
self.bkp7r_reg().with(f);
self
}
#[doc="Get the BKP8R Register."]
#[inline] pub fn bkp8r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp8r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp8r, 0x70)
}
#[doc="Get the *mut pointer for the BKP8R register."]
#[inline] pub fn bkp8r_mut(&self) -> *mut Bkp8r {
self.bkp8r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP8R register."]
#[inline] pub fn bkp8r_ptr(&self) -> *const Bkp8r {
self.bkp8r_reg().ptr()
}
#[doc="Read the BKP8R register."]
#[inline] pub fn bkp8r(&self) -> Bkp8r {
self.bkp8r_reg().read()
}
#[doc="Write the BKP8R register."]
#[inline] pub fn write_bkp8r(&self, value: Bkp8r) -> &Self {
self.bkp8r_reg().write(value);
self
}
#[doc="Set the BKP8R register."]
#[inline] pub fn set_bkp8r<F: FnOnce(Bkp8r) -> Bkp8r>(&self, f: F) -> &Self {
self.bkp8r_reg().set(f);
self
}
#[doc="Modify the BKP8R register."]
#[inline] pub fn with_bkp8r<F: FnOnce(Bkp8r) -> Bkp8r>(&self, f: F) -> &Self {
self.bkp8r_reg().with(f);
self
}
#[doc="Get the BKP9R Register."]
#[inline] pub fn bkp9r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp9r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp9r, 0x74)
}
#[doc="Get the *mut pointer for the BKP9R register."]
#[inline] pub fn bkp9r_mut(&self) -> *mut Bkp9r {
self.bkp9r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP9R register."]
#[inline] pub fn bkp9r_ptr(&self) -> *const Bkp9r {
self.bkp9r_reg().ptr()
}
#[doc="Read the BKP9R register."]
#[inline] pub fn bkp9r(&self) -> Bkp9r {
self.bkp9r_reg().read()
}
#[doc="Write the BKP9R register."]
#[inline] pub fn write_bkp9r(&self, value: Bkp9r) -> &Self {
self.bkp9r_reg().write(value);
self
}
#[doc="Set the BKP9R register."]
#[inline] pub fn set_bkp9r<F: FnOnce(Bkp9r) -> Bkp9r>(&self, f: F) -> &Self {
self.bkp9r_reg().set(f);
self
}
#[doc="Modify the BKP9R register."]
#[inline] pub fn with_bkp9r<F: FnOnce(Bkp9r) -> Bkp9r>(&self, f: F) -> &Self {
self.bkp9r_reg().with(f);
self
}
#[doc="Get the BKP10R Register."]
#[inline] pub fn bkp10r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp10r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp10r, 0x78)
}
#[doc="Get the *mut pointer for the BKP10R register."]
#[inline] pub fn bkp10r_mut(&self) -> *mut Bkp10r {
self.bkp10r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP10R register."]
#[inline] pub fn bkp10r_ptr(&self) -> *const Bkp10r {
self.bkp10r_reg().ptr()
}
#[doc="Read the BKP10R register."]
#[inline] pub fn bkp10r(&self) -> Bkp10r {
self.bkp10r_reg().read()
}
#[doc="Write the BKP10R register."]
#[inline] pub fn write_bkp10r(&self, value: Bkp10r) -> &Self {
self.bkp10r_reg().write(value);
self
}
#[doc="Set the BKP10R register."]
#[inline] pub fn set_bkp10r<F: FnOnce(Bkp10r) -> Bkp10r>(&self, f: F) -> &Self {
self.bkp10r_reg().set(f);
self
}
#[doc="Modify the BKP10R register."]
#[inline] pub fn with_bkp10r<F: FnOnce(Bkp10r) -> Bkp10r>(&self, f: F) -> &Self {
self.bkp10r_reg().with(f);
self
}
#[doc="Get the BKP11R Register."]
#[inline] pub fn bkp11r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp11r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp11r, 0x7c)
}
#[doc="Get the *mut pointer for the BKP11R register."]
#[inline] pub fn bkp11r_mut(&self) -> *mut Bkp11r {
self.bkp11r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP11R register."]
#[inline] pub fn bkp11r_ptr(&self) -> *const Bkp11r {
self.bkp11r_reg().ptr()
}
#[doc="Read the BKP11R register."]
#[inline] pub fn bkp11r(&self) -> Bkp11r {
self.bkp11r_reg().read()
}
#[doc="Write the BKP11R register."]
#[inline] pub fn write_bkp11r(&self, value: Bkp11r) -> &Self {
self.bkp11r_reg().write(value);
self
}
#[doc="Set the BKP11R register."]
#[inline] pub fn set_bkp11r<F: FnOnce(Bkp11r) -> Bkp11r>(&self, f: F) -> &Self {
self.bkp11r_reg().set(f);
self
}
#[doc="Modify the BKP11R register."]
#[inline] pub fn with_bkp11r<F: FnOnce(Bkp11r) -> Bkp11r>(&self, f: F) -> &Self {
self.bkp11r_reg().with(f);
self
}
#[doc="Get the BKP12R Register."]
#[inline] pub fn bkp12r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp12r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp12r, 0x80)
}
#[doc="Get the *mut pointer for the BKP12R register."]
#[inline] pub fn bkp12r_mut(&self) -> *mut Bkp12r {
self.bkp12r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP12R register."]
#[inline] pub fn bkp12r_ptr(&self) -> *const Bkp12r {
self.bkp12r_reg().ptr()
}
#[doc="Read the BKP12R register."]
#[inline] pub fn bkp12r(&self) -> Bkp12r {
self.bkp12r_reg().read()
}
#[doc="Write the BKP12R register."]
#[inline] pub fn write_bkp12r(&self, value: Bkp12r) -> &Self {
self.bkp12r_reg().write(value);
self
}
#[doc="Set the BKP12R register."]
#[inline] pub fn set_bkp12r<F: FnOnce(Bkp12r) -> Bkp12r>(&self, f: F) -> &Self {
self.bkp12r_reg().set(f);
self
}
#[doc="Modify the BKP12R register."]
#[inline] pub fn with_bkp12r<F: FnOnce(Bkp12r) -> Bkp12r>(&self, f: F) -> &Self {
self.bkp12r_reg().with(f);
self
}
#[doc="Get the BKP13R Register."]
#[inline] pub fn bkp13r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp13r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp13r, 0x84)
}
#[doc="Get the *mut pointer for the BKP13R register."]
#[inline] pub fn bkp13r_mut(&self) -> *mut Bkp13r {
self.bkp13r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP13R register."]
#[inline] pub fn bkp13r_ptr(&self) -> *const Bkp13r {
self.bkp13r_reg().ptr()
}
#[doc="Read the BKP13R register."]
#[inline] pub fn bkp13r(&self) -> Bkp13r {
self.bkp13r_reg().read()
}
#[doc="Write the BKP13R register."]
#[inline] pub fn write_bkp13r(&self, value: Bkp13r) -> &Self {
self.bkp13r_reg().write(value);
self
}
#[doc="Set the BKP13R register."]
#[inline] pub fn set_bkp13r<F: FnOnce(Bkp13r) -> Bkp13r>(&self, f: F) -> &Self {
self.bkp13r_reg().set(f);
self
}
#[doc="Modify the BKP13R register."]
#[inline] pub fn with_bkp13r<F: FnOnce(Bkp13r) -> Bkp13r>(&self, f: F) -> &Self {
self.bkp13r_reg().with(f);
self
}
#[doc="Get the BKP14R Register."]
#[inline] pub fn bkp14r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp14r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp14r, 0x88)
}
#[doc="Get the *mut pointer for the BKP14R register."]
#[inline] pub fn bkp14r_mut(&self) -> *mut Bkp14r {
self.bkp14r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP14R register."]
#[inline] pub fn bkp14r_ptr(&self) -> *const Bkp14r {
self.bkp14r_reg().ptr()
}
#[doc="Read the BKP14R register."]
#[inline] pub fn bkp14r(&self) -> Bkp14r {
self.bkp14r_reg().read()
}
#[doc="Write the BKP14R register."]
#[inline] pub fn write_bkp14r(&self, value: Bkp14r) -> &Self {
self.bkp14r_reg().write(value);
self
}
#[doc="Set the BKP14R register."]
#[inline] pub fn set_bkp14r<F: FnOnce(Bkp14r) -> Bkp14r>(&self, f: F) -> &Self {
self.bkp14r_reg().set(f);
self
}
#[doc="Modify the BKP14R register."]
#[inline] pub fn with_bkp14r<F: FnOnce(Bkp14r) -> Bkp14r>(&self, f: F) -> &Self {
self.bkp14r_reg().with(f);
self
}
#[doc="Get the BKP15R Register."]
#[inline] pub fn bkp15r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp15r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp15r, 0x8c)
}
#[doc="Get the *mut pointer for the BKP15R register."]
#[inline] pub fn bkp15r_mut(&self) -> *mut Bkp15r {
self.bkp15r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP15R register."]
#[inline] pub fn bkp15r_ptr(&self) -> *const Bkp15r {
self.bkp15r_reg().ptr()
}
#[doc="Read the BKP15R register."]
#[inline] pub fn bkp15r(&self) -> Bkp15r {
self.bkp15r_reg().read()
}
#[doc="Write the BKP15R register."]
#[inline] pub fn write_bkp15r(&self, value: Bkp15r) -> &Self {
self.bkp15r_reg().write(value);
self
}
#[doc="Set the BKP15R register."]
#[inline] pub fn set_bkp15r<F: FnOnce(Bkp15r) -> Bkp15r>(&self, f: F) -> &Self {
self.bkp15r_reg().set(f);
self
}
#[doc="Modify the BKP15R register."]
#[inline] pub fn with_bkp15r<F: FnOnce(Bkp15r) -> Bkp15r>(&self, f: F) -> &Self {
self.bkp15r_reg().with(f);
self
}
#[doc="Get the BKP16R Register."]
#[inline] pub fn bkp16r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp16r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp16r, 0x90)
}
#[doc="Get the *mut pointer for the BKP16R register."]
#[inline] pub fn bkp16r_mut(&self) -> *mut Bkp16r {
self.bkp16r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP16R register."]
#[inline] pub fn bkp16r_ptr(&self) -> *const Bkp16r {
self.bkp16r_reg().ptr()
}
#[doc="Read the BKP16R register."]
#[inline] pub fn bkp16r(&self) -> Bkp16r {
self.bkp16r_reg().read()
}
#[doc="Write the BKP16R register."]
#[inline] pub fn write_bkp16r(&self, value: Bkp16r) -> &Self {
self.bkp16r_reg().write(value);
self
}
#[doc="Set the BKP16R register."]
#[inline] pub fn set_bkp16r<F: FnOnce(Bkp16r) -> Bkp16r>(&self, f: F) -> &Self {
self.bkp16r_reg().set(f);
self
}
#[doc="Modify the BKP16R register."]
#[inline] pub fn with_bkp16r<F: FnOnce(Bkp16r) -> Bkp16r>(&self, f: F) -> &Self {
self.bkp16r_reg().with(f);
self
}
#[doc="Get the BKP17R Register."]
#[inline] pub fn bkp17r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp17r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp17r, 0x94)
}
#[doc="Get the *mut pointer for the BKP17R register."]
#[inline] pub fn bkp17r_mut(&self) -> *mut Bkp17r {
self.bkp17r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP17R register."]
#[inline] pub fn bkp17r_ptr(&self) -> *const Bkp17r {
self.bkp17r_reg().ptr()
}
#[doc="Read the BKP17R register."]
#[inline] pub fn bkp17r(&self) -> Bkp17r {
self.bkp17r_reg().read()
}
#[doc="Write the BKP17R register."]
#[inline] pub fn write_bkp17r(&self, value: Bkp17r) -> &Self {
self.bkp17r_reg().write(value);
self
}
#[doc="Set the BKP17R register."]
#[inline] pub fn set_bkp17r<F: FnOnce(Bkp17r) -> Bkp17r>(&self, f: F) -> &Self {
self.bkp17r_reg().set(f);
self
}
#[doc="Modify the BKP17R register."]
#[inline] pub fn with_bkp17r<F: FnOnce(Bkp17r) -> Bkp17r>(&self, f: F) -> &Self {
self.bkp17r_reg().with(f);
self
}
#[doc="Get the BKP18R Register."]
#[inline] pub fn bkp18r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp18r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp18r, 0x98)
}
#[doc="Get the *mut pointer for the BKP18R register."]
#[inline] pub fn bkp18r_mut(&self) -> *mut Bkp18r {
self.bkp18r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP18R register."]
#[inline] pub fn bkp18r_ptr(&self) -> *const Bkp18r {
self.bkp18r_reg().ptr()
}
#[doc="Read the BKP18R register."]
#[inline] pub fn bkp18r(&self) -> Bkp18r {
self.bkp18r_reg().read()
}
#[doc="Write the BKP18R register."]
#[inline] pub fn write_bkp18r(&self, value: Bkp18r) -> &Self {
self.bkp18r_reg().write(value);
self
}
#[doc="Set the BKP18R register."]
#[inline] pub fn set_bkp18r<F: FnOnce(Bkp18r) -> Bkp18r>(&self, f: F) -> &Self {
self.bkp18r_reg().set(f);
self
}
#[doc="Modify the BKP18R register."]
#[inline] pub fn with_bkp18r<F: FnOnce(Bkp18r) -> Bkp18r>(&self, f: F) -> &Self {
self.bkp18r_reg().with(f);
self
}
#[doc="Get the BKP19R Register."]
#[inline] pub fn bkp19r_reg(&self) -> ::bobbin_mcu::register::Register<Bkp19r> {
::bobbin_mcu::register::Register::new(self.0 as *mut Bkp19r, 0x9c)
}
#[doc="Get the *mut pointer for the BKP19R register."]
#[inline] pub fn bkp19r_mut(&self) -> *mut Bkp19r {
self.bkp19r_reg().ptr()
}
#[doc="Get the *const pointer for the BKP19R register."]
#[inline] pub fn bkp19r_ptr(&self) -> *const Bkp19r {
self.bkp19r_reg().ptr()
}
#[doc="Read the BKP19R register."]
#[inline] pub fn bkp19r(&self) -> Bkp19r {
self.bkp19r_reg().read()
}
#[doc="Write the BKP19R register."]
#[inline] pub fn write_bkp19r(&self, value: Bkp19r) -> &Self {
self.bkp19r_reg().write(value);
self
}
#[doc="Set the BKP19R register."]
#[inline] pub fn set_bkp19r<F: FnOnce(Bkp19r) -> Bkp19r>(&self, f: F) -> &Self {
self.bkp19r_reg().set(f);
self
}
#[doc="Modify the BKP19R register."]
#[inline] pub fn with_bkp19r<F: FnOnce(Bkp19r) -> Bkp19r>(&self, f: F) -> &Self {
self.bkp19r_reg().with(f);
self
}
}
#[doc="time register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Tr(pub u32);
impl Tr {
#[doc="AM/PM notation"]
#[inline] pub fn pm(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 22) & 0x1) as u8) } // [22]
}
#[doc="Returns true if PM != 0"]
#[inline] pub fn test_pm(&self) -> bool {
self.pm() != 0
}
#[doc="Sets the PM field."]
#[inline] pub fn set_pm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 22);
self.0 |= value << 22;
self
}
#[doc="Hour tens in BCD format"]
#[inline] pub fn ht(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x3) as u8) } // [21:20]
}
#[doc="Returns true if HT != 0"]
#[inline] pub fn test_ht(&self) -> bool {
self.ht() != 0
}
#[doc="Sets the HT field."]
#[inline] pub fn set_ht<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 20);
self.0 |= value << 20;
self
}
#[doc="Hour units in BCD format"]
#[inline] pub fn hu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xf) as u8) } // [19:16]
}
#[doc="Returns true if HU != 0"]
#[inline] pub fn test_hu(&self) -> bool {
self.hu() != 0
}
#[doc="Sets the HU field."]
#[inline] pub fn set_hu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 16);
self.0 |= value << 16;
self
}
#[doc="Minute tens in BCD format"]
#[inline] pub fn mnt(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x7) as u8) } // [14:12]
}
#[doc="Returns true if MNT != 0"]
#[inline] pub fn test_mnt(&self) -> bool {
self.mnt() != 0
}
#[doc="Sets the MNT field."]
#[inline] pub fn set_mnt<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 12);
self.0 |= value << 12;
self
}
#[doc="Minute units in BCD format"]
#[inline] pub fn mnu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MNU != 0"]
#[inline] pub fn test_mnu(&self) -> bool {
self.mnu() != 0
}
#[doc="Sets the MNU field."]
#[inline] pub fn set_mnu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Second tens in BCD format"]
#[inline] pub fn st(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x7) as u8) } // [6:4]
}
#[doc="Returns true if ST != 0"]
#[inline] pub fn test_st(&self) -> bool {
self.st() != 0
}
#[doc="Sets the ST field."]
#[inline] pub fn set_st<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 4);
self.0 |= value << 4;
self
}
#[doc="Second units in BCD format"]
#[inline] pub fn su(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if SU != 0"]
#[inline] pub fn test_su(&self) -> bool {
self.su() != 0
}
#[doc="Sets the SU field."]
#[inline] pub fn set_su<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Tr {
#[inline]
fn from(other: u32) -> Self {
Tr(other)
}
}
impl ::core::fmt::Display for Tr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Tr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.pm() != 0 { try!(write!(f, " pm"))}
if self.ht() != 0 { try!(write!(f, " ht=0x{:x}", self.ht()))}
if self.hu() != 0 { try!(write!(f, " hu=0x{:x}", self.hu()))}
if self.mnt() != 0 { try!(write!(f, " mnt=0x{:x}", self.mnt()))}
if self.mnu() != 0 { try!(write!(f, " mnu=0x{:x}", self.mnu()))}
if self.st() != 0 { try!(write!(f, " st=0x{:x}", self.st()))}
if self.su() != 0 { try!(write!(f, " su=0x{:x}", self.su()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="date register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Dr(pub u32);
impl Dr {
#[doc="Year tens in BCD format"]
#[inline] pub fn yt(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0xf) as u8) } // [23:20]
}
#[doc="Returns true if YT != 0"]
#[inline] pub fn test_yt(&self) -> bool {
self.yt() != 0
}
#[doc="Sets the YT field."]
#[inline] pub fn set_yt<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 20);
self.0 |= value << 20;
self
}
#[doc="Year units in BCD format"]
#[inline] pub fn yu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xf) as u8) } // [19:16]
}
#[doc="Returns true if YU != 0"]
#[inline] pub fn test_yu(&self) -> bool {
self.yu() != 0
}
#[doc="Sets the YU field."]
#[inline] pub fn set_yu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 16);
self.0 |= value << 16;
self
}
#[doc="Week day units"]
#[inline] pub fn wdu(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x7) as u8) } // [15:13]
}
#[doc="Returns true if WDU != 0"]
#[inline] pub fn test_wdu(&self) -> bool {
self.wdu() != 0
}
#[doc="Sets the WDU field."]
#[inline] pub fn set_wdu<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 13);
self.0 |= value << 13;
self
}
#[doc="Month tens in BCD format"]
#[inline] pub fn mt(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x1) as u8) } // [12]
}
#[doc="Returns true if MT != 0"]
#[inline] pub fn test_mt(&self) -> bool {
self.mt() != 0
}
#[doc="Sets the MT field."]
#[inline] pub fn set_mt<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 12);
self.0 |= value << 12;
self
}
#[doc="Month units in BCD format"]
#[inline] pub fn mu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MU != 0"]
#[inline] pub fn test_mu(&self) -> bool {
self.mu() != 0
}
#[doc="Sets the MU field."]
#[inline] pub fn set_mu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Date tens in BCD format"]
#[inline] pub fn dt(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x3) as u8) } // [5:4]
}
#[doc="Returns true if DT != 0"]
#[inline] pub fn test_dt(&self) -> bool {
self.dt() != 0
}
#[doc="Sets the DT field."]
#[inline] pub fn set_dt<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 4);
self.0 |= value << 4;
self
}
#[doc="Date units in BCD format"]
#[inline] pub fn du(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if DU != 0"]
#[inline] pub fn test_du(&self) -> bool {
self.du() != 0
}
#[doc="Sets the DU field."]
#[inline] pub fn set_du<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Dr {
#[inline]
fn from(other: u32) -> Self {
Dr(other)
}
}
impl ::core::fmt::Display for Dr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Dr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.yt() != 0 { try!(write!(f, " yt=0x{:x}", self.yt()))}
if self.yu() != 0 { try!(write!(f, " yu=0x{:x}", self.yu()))}
if self.wdu() != 0 { try!(write!(f, " wdu=0x{:x}", self.wdu()))}
if self.mt() != 0 { try!(write!(f, " mt"))}
if self.mu() != 0 { try!(write!(f, " mu=0x{:x}", self.mu()))}
if self.dt() != 0 { try!(write!(f, " dt=0x{:x}", self.dt()))}
if self.du() != 0 { try!(write!(f, " du=0x{:x}", self.du()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="control register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Cr(pub u32);
impl Cr {
#[doc="Wakeup clock selection"]
#[inline] pub fn wcksel(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7) as u8) } // [2:0]
}
#[doc="Returns true if WCKSEL != 0"]
#[inline] pub fn test_wcksel(&self) -> bool {
self.wcksel() != 0
}
#[doc="Sets the WCKSEL field."]
#[inline] pub fn set_wcksel<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 0);
self.0 |= value << 0;
self
}
#[doc="Time-stamp event active edge"]
#[inline] pub fn tsedge(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3]
}
#[doc="Returns true if TSEDGE != 0"]
#[inline] pub fn test_tsedge(&self) -> bool {
self.tsedge() != 0
}
#[doc="Sets the TSEDGE field."]
#[inline] pub fn set_tsedge<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 3);
self.0 |= value << 3;
self
}
#[doc="Reference clock detection enable (50 or 60 Hz)"]
#[inline] pub fn refckon(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if REFCKON != 0"]
#[inline] pub fn test_refckon(&self) -> bool {
self.refckon() != 0
}
#[doc="Sets the REFCKON field."]
#[inline] pub fn set_refckon<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="Bypass the shadow registers"]
#[inline] pub fn bypshad(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5]
}
#[doc="Returns true if BYPSHAD != 0"]
#[inline] pub fn test_bypshad(&self) -> bool {
self.bypshad() != 0
}
#[doc="Sets the BYPSHAD field."]
#[inline] pub fn set_bypshad<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 5);
self.0 |= value << 5;
self
}
#[doc="Hour format"]
#[inline] pub fn fmt(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 6) & 0x1) as u8) } // [6]
}
#[doc="Returns true if FMT != 0"]
#[inline] pub fn test_fmt(&self) -> bool {
self.fmt() != 0
}
#[doc="Sets the FMT field."]
#[inline] pub fn set_fmt<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 6);
self.0 |= value << 6;
self
}
#[doc="Alarm A enable"]
#[inline] pub fn alrae(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0x1) as u8) } // [8]
}
#[doc="Returns true if ALRAE != 0"]
#[inline] pub fn test_alrae(&self) -> bool {
self.alrae() != 0
}
#[doc="Sets the ALRAE field."]
#[inline] pub fn set_alrae<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 8);
self.0 |= value << 8;
self
}
#[doc="Alarm B enable"]
#[inline] pub fn alrbe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 9) & 0x1) as u8) } // [9]
}
#[doc="Returns true if ALRBE != 0"]
#[inline] pub fn test_alrbe(&self) -> bool {
self.alrbe() != 0
}
#[doc="Sets the ALRBE field."]
#[inline] pub fn set_alrbe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 9);
self.0 |= value << 9;
self
}
#[doc="Wakeup timer enable"]
#[inline] pub fn wute(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 10) & 0x1) as u8) } // [10]
}
#[doc="Returns true if WUTE != 0"]
#[inline] pub fn test_wute(&self) -> bool {
self.wute() != 0
}
#[doc="Sets the WUTE field."]
#[inline] pub fn set_wute<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 10);
self.0 |= value << 10;
self
}
#[doc="Time stamp enable"]
#[inline] pub fn tse(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 11) & 0x1) as u8) } // [11]
}
#[doc="Returns true if TSE != 0"]
#[inline] pub fn test_tse(&self) -> bool {
self.tse() != 0
}
#[doc="Sets the TSE field."]
#[inline] pub fn set_tse<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 11);
self.0 |= value << 11;
self
}
#[doc="Alarm A interrupt enable"]
#[inline] pub fn alraie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x1) as u8) } // [12]
}
#[doc="Returns true if ALRAIE != 0"]
#[inline] pub fn test_alraie(&self) -> bool {
self.alraie() != 0
}
#[doc="Sets the ALRAIE field."]
#[inline] pub fn set_alraie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 12);
self.0 |= value << 12;
self
}
#[doc="Alarm B interrupt enable"]
#[inline] pub fn alrbie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x1) as u8) } // [13]
}
#[doc="Returns true if ALRBIE != 0"]
#[inline] pub fn test_alrbie(&self) -> bool {
self.alrbie() != 0
}
#[doc="Sets the ALRBIE field."]
#[inline] pub fn set_alrbie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 13);
self.0 |= value << 13;
self
}
#[doc="Wakeup timer interrupt enable"]
#[inline] pub fn wutie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 14) & 0x1) as u8) } // [14]
}
#[doc="Returns true if WUTIE != 0"]
#[inline] pub fn test_wutie(&self) -> bool {
self.wutie() != 0
}
#[doc="Sets the WUTIE field."]
#[inline] pub fn set_wutie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 14);
self.0 |= value << 14;
self
}
#[doc="Time-stamp interrupt enable"]
#[inline] pub fn tsie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if TSIE != 0"]
#[inline] pub fn test_tsie(&self) -> bool {
self.tsie() != 0
}
#[doc="Sets the TSIE field."]
#[inline] pub fn set_tsie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Add 1 hour (summer time change)"]
#[inline] pub fn add1h(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x1) as u8) } // [16]
}
#[doc="Returns true if ADD1H != 0"]
#[inline] pub fn test_add1h(&self) -> bool {
self.add1h() != 0
}
#[doc="Sets the ADD1H field."]
#[inline] pub fn set_add1h<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 16);
self.0 |= value << 16;
self
}
#[doc="Subtract 1 hour (winter time change)"]
#[inline] pub fn sub1h(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 17) & 0x1) as u8) } // [17]
}
#[doc="Returns true if SUB1H != 0"]
#[inline] pub fn test_sub1h(&self) -> bool {
self.sub1h() != 0
}
#[doc="Sets the SUB1H field."]
#[inline] pub fn set_sub1h<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 17);
self.0 |= value << 17;
self
}
#[doc="Backup"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 18) & 0x1) as u8) } // [18]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 18);
self.0 |= value << 18;
self
}
#[doc="Calibration output selection"]
#[inline] pub fn cosel(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 19) & 0x1) as u8) } // [19]
}
#[doc="Returns true if COSEL != 0"]
#[inline] pub fn test_cosel(&self) -> bool {
self.cosel() != 0
}
#[doc="Sets the COSEL field."]
#[inline] pub fn set_cosel<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 19);
self.0 |= value << 19;
self
}
#[doc="Output polarity"]
#[inline] pub fn pol(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x1) as u8) } // [20]
}
#[doc="Returns true if POL != 0"]
#[inline] pub fn test_pol(&self) -> bool {
self.pol() != 0
}
#[doc="Sets the POL field."]
#[inline] pub fn set_pol<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 20);
self.0 |= value << 20;
self
}
#[doc="Output selection"]
#[inline] pub fn osel(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 21) & 0x3) as u8) } // [22:21]
}
#[doc="Returns true if OSEL != 0"]
#[inline] pub fn test_osel(&self) -> bool {
self.osel() != 0
}
#[doc="Sets the OSEL field."]
#[inline] pub fn set_osel<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 21);
self.0 |= value << 21;
self
}
#[doc="Calibration output enable"]
#[inline] pub fn coe(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 23) & 0x1) as u8) } // [23]
}
#[doc="Returns true if COE != 0"]
#[inline] pub fn test_coe(&self) -> bool {
self.coe() != 0
}
#[doc="Sets the COE field."]
#[inline] pub fn set_coe<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 23);
self.0 |= value << 23;
self
}
#[doc="timestamp on internal event enable"]
#[inline] pub fn itse(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0x1) as u8) } // [24]
}
#[doc="Returns true if ITSE != 0"]
#[inline] pub fn test_itse(&self) -> bool {
self.itse() != 0
}
#[doc="Sets the ITSE field."]
#[inline] pub fn set_itse<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 24);
self.0 |= value << 24;
self
}
}
impl From<u32> for Cr {
#[inline]
fn from(other: u32) -> Self {
Cr(other)
}
}
impl ::core::fmt::Display for Cr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Cr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.wcksel() != 0 { try!(write!(f, " wcksel=0x{:x}", self.wcksel()))}
if self.tsedge() != 0 { try!(write!(f, " tsedge"))}
if self.refckon() != 0 { try!(write!(f, " refckon"))}
if self.bypshad() != 0 { try!(write!(f, " bypshad"))}
if self.fmt() != 0 { try!(write!(f, " fmt"))}
if self.alrae() != 0 { try!(write!(f, " alrae"))}
if self.alrbe() != 0 { try!(write!(f, " alrbe"))}
if self.wute() != 0 { try!(write!(f, " wute"))}
if self.tse() != 0 { try!(write!(f, " tse"))}
if self.alraie() != 0 { try!(write!(f, " alraie"))}
if self.alrbie() != 0 { try!(write!(f, " alrbie"))}
if self.wutie() != 0 { try!(write!(f, " wutie"))}
if self.tsie() != 0 { try!(write!(f, " tsie"))}
if self.add1h() != 0 { try!(write!(f, " add1h"))}
if self.sub1h() != 0 { try!(write!(f, " sub1h"))}
if self.bkp() != 0 { try!(write!(f, " bkp"))}
if self.cosel() != 0 { try!(write!(f, " cosel"))}
if self.pol() != 0 { try!(write!(f, " pol"))}
if self.osel() != 0 { try!(write!(f, " osel=0x{:x}", self.osel()))}
if self.coe() != 0 { try!(write!(f, " coe"))}
if self.itse() != 0 { try!(write!(f, " itse"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="initialization and status register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Isr(pub u32);
impl Isr {
#[doc="Alarm A write flag"]
#[inline] pub fn alrawf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0]
}
#[doc="Returns true if ALRAWF != 0"]
#[inline] pub fn test_alrawf(&self) -> bool {
self.alrawf() != 0
}
#[doc="Sets the ALRAWF field."]
#[inline] pub fn set_alrawf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 0);
self.0 |= value << 0;
self
}
#[doc="Alarm B write flag"]
#[inline] pub fn alrbwf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1]
}
#[doc="Returns true if ALRBWF != 0"]
#[inline] pub fn test_alrbwf(&self) -> bool {
self.alrbwf() != 0
}
#[doc="Sets the ALRBWF field."]
#[inline] pub fn set_alrbwf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 1);
self.0 |= value << 1;
self
}
#[doc="Wakeup timer write flag"]
#[inline] pub fn wutwf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2]
}
#[doc="Returns true if WUTWF != 0"]
#[inline] pub fn test_wutwf(&self) -> bool {
self.wutwf() != 0
}
#[doc="Sets the WUTWF field."]
#[inline] pub fn set_wutwf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 2);
self.0 |= value << 2;
self
}
#[doc="Shift operation pending"]
#[inline] pub fn shpf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3]
}
#[doc="Returns true if SHPF != 0"]
#[inline] pub fn test_shpf(&self) -> bool {
self.shpf() != 0
}
#[doc="Sets the SHPF field."]
#[inline] pub fn set_shpf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 3);
self.0 |= value << 3;
self
}
#[doc="Initialization status flag"]
#[inline] pub fn inits(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if INITS != 0"]
#[inline] pub fn test_inits(&self) -> bool {
self.inits() != 0
}
#[doc="Sets the INITS field."]
#[inline] pub fn set_inits<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="Registers synchronization flag"]
#[inline] pub fn rsf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5]
}
#[doc="Returns true if RSF != 0"]
#[inline] pub fn test_rsf(&self) -> bool {
self.rsf() != 0
}
#[doc="Sets the RSF field."]
#[inline] pub fn set_rsf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 5);
self.0 |= value << 5;
self
}
#[doc="Initialization flag"]
#[inline] pub fn initf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 6) & 0x1) as u8) } // [6]
}
#[doc="Returns true if INITF != 0"]
#[inline] pub fn test_initf(&self) -> bool {
self.initf() != 0
}
#[doc="Sets the INITF field."]
#[inline] pub fn set_initf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 6);
self.0 |= value << 6;
self
}
#[doc="Initialization mode"]
#[inline] pub fn init(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if INIT != 0"]
#[inline] pub fn test_init(&self) -> bool {
self.init() != 0
}
#[doc="Sets the INIT field."]
#[inline] pub fn set_init<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
#[doc="Alarm A flag"]
#[inline] pub fn alraf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0x1) as u8) } // [8]
}
#[doc="Returns true if ALRAF != 0"]
#[inline] pub fn test_alraf(&self) -> bool {
self.alraf() != 0
}
#[doc="Sets the ALRAF field."]
#[inline] pub fn set_alraf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 8);
self.0 |= value << 8;
self
}
#[doc="Alarm B flag"]
#[inline] pub fn alrbf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 9) & 0x1) as u8) } // [9]
}
#[doc="Returns true if ALRBF != 0"]
#[inline] pub fn test_alrbf(&self) -> bool {
self.alrbf() != 0
}
#[doc="Sets the ALRBF field."]
#[inline] pub fn set_alrbf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 9);
self.0 |= value << 9;
self
}
#[doc="Wakeup timer flag"]
#[inline] pub fn wutf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 10) & 0x1) as u8) } // [10]
}
#[doc="Returns true if WUTF != 0"]
#[inline] pub fn test_wutf(&self) -> bool {
self.wutf() != 0
}
#[doc="Sets the WUTF field."]
#[inline] pub fn set_wutf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 10);
self.0 |= value << 10;
self
}
#[doc="Time-stamp flag"]
#[inline] pub fn tsf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 11) & 0x1) as u8) } // [11]
}
#[doc="Returns true if TSF != 0"]
#[inline] pub fn test_tsf(&self) -> bool {
self.tsf() != 0
}
#[doc="Sets the TSF field."]
#[inline] pub fn set_tsf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 11);
self.0 |= value << 11;
self
}
#[doc="Time-stamp overflow flag"]
#[inline] pub fn tsovf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x1) as u8) } // [12]
}
#[doc="Returns true if TSOVF != 0"]
#[inline] pub fn test_tsovf(&self) -> bool {
self.tsovf() != 0
}
#[doc="Sets the TSOVF field."]
#[inline] pub fn set_tsovf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 12);
self.0 |= value << 12;
self
}
#[doc="Tamper detection flag"]
#[inline] pub fn tamp1f(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x1) as u8) } // [13]
}
#[doc="Returns true if TAMP1F != 0"]
#[inline] pub fn test_tamp1f(&self) -> bool {
self.tamp1f() != 0
}
#[doc="Sets the TAMP1F field."]
#[inline] pub fn set_tamp1f<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 13);
self.0 |= value << 13;
self
}
#[doc="RTC_TAMP2 detection flag"]
#[inline] pub fn tamp2f(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 14) & 0x1) as u8) } // [14]
}
#[doc="Returns true if TAMP2F != 0"]
#[inline] pub fn test_tamp2f(&self) -> bool {
self.tamp2f() != 0
}
#[doc="Sets the TAMP2F field."]
#[inline] pub fn set_tamp2f<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 14);
self.0 |= value << 14;
self
}
#[doc="RTC_TAMP3 detection flag"]
#[inline] pub fn tamp3f(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if TAMP3F != 0"]
#[inline] pub fn test_tamp3f(&self) -> bool {
self.tamp3f() != 0
}
#[doc="Sets the TAMP3F field."]
#[inline] pub fn set_tamp3f<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Recalibration pending Flag"]
#[inline] pub fn recalpf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x1) as u8) } // [16]
}
#[doc="Returns true if RECALPF != 0"]
#[inline] pub fn test_recalpf(&self) -> bool {
self.recalpf() != 0
}
#[doc="Sets the RECALPF field."]
#[inline] pub fn set_recalpf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 16);
self.0 |= value << 16;
self
}
#[doc="INTERNAL TIME-STAMP FLAG"]
#[inline] pub fn itsf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 17) & 0x1) as u8) } // [17]
}
#[doc="Returns true if ITSF != 0"]
#[inline] pub fn test_itsf(&self) -> bool {
self.itsf() != 0
}
#[doc="Sets the ITSF field."]
#[inline] pub fn set_itsf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 17);
self.0 |= value << 17;
self
}
}
impl From<u32> for Isr {
#[inline]
fn from(other: u32) -> Self {
Isr(other)
}
}
impl ::core::fmt::Display for Isr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Isr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.alrawf() != 0 { try!(write!(f, " alrawf"))}
if self.alrbwf() != 0 { try!(write!(f, " alrbwf"))}
if self.wutwf() != 0 { try!(write!(f, " wutwf"))}
if self.shpf() != 0 { try!(write!(f, " shpf"))}
if self.inits() != 0 { try!(write!(f, " inits"))}
if self.rsf() != 0 { try!(write!(f, " rsf"))}
if self.initf() != 0 { try!(write!(f, " initf"))}
if self.init() != 0 { try!(write!(f, " init"))}
if self.alraf() != 0 { try!(write!(f, " alraf"))}
if self.alrbf() != 0 { try!(write!(f, " alrbf"))}
if self.wutf() != 0 { try!(write!(f, " wutf"))}
if self.tsf() != 0 { try!(write!(f, " tsf"))}
if self.tsovf() != 0 { try!(write!(f, " tsovf"))}
if self.tamp1f() != 0 { try!(write!(f, " tamp1f"))}
if self.tamp2f() != 0 { try!(write!(f, " tamp2f"))}
if self.tamp3f() != 0 { try!(write!(f, " tamp3f"))}
if self.recalpf() != 0 { try!(write!(f, " recalpf"))}
if self.itsf() != 0 { try!(write!(f, " itsf"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="prescaler register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Prer(pub u32);
impl Prer {
#[doc="Asynchronous prescaler factor"]
#[inline] pub fn prediv_a(&self) -> ::bobbin_bits::U7 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x7f) as u8) } // [22:16]
}
#[doc="Returns true if PREDIV_A != 0"]
#[inline] pub fn test_prediv_a(&self) -> bool {
self.prediv_a() != 0
}
#[doc="Sets the PREDIV_A field."]
#[inline] pub fn set_prediv_a<V: Into<::bobbin_bits::U7>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U7 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7f << 16);
self.0 |= value << 16;
self
}
#[doc="Synchronous prescaler factor"]
#[inline] pub fn prediv_s(&self) -> ::bobbin_bits::U15 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7fff) as u16) } // [14:0]
}
#[doc="Returns true if PREDIV_S != 0"]
#[inline] pub fn test_prediv_s(&self) -> bool {
self.prediv_s() != 0
}
#[doc="Sets the PREDIV_S field."]
#[inline] pub fn set_prediv_s<V: Into<::bobbin_bits::U15>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U15 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7fff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Prer {
#[inline]
fn from(other: u32) -> Self {
Prer(other)
}
}
impl ::core::fmt::Display for Prer {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Prer {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.prediv_a() != 0 { try!(write!(f, " prediv_a=0x{:x}", self.prediv_a()))}
if self.prediv_s() != 0 { try!(write!(f, " prediv_s=0x{:x}", self.prediv_s()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="wakeup timer register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Wutr(pub u32);
impl Wutr {
#[doc="Wakeup auto-reload value bits"]
#[inline] pub fn wut(&self) -> ::bobbin_bits::U16 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffff) as u16) } // [15:0]
}
#[doc="Returns true if WUT != 0"]
#[inline] pub fn test_wut(&self) -> bool {
self.wut() != 0
}
#[doc="Sets the WUT field."]
#[inline] pub fn set_wut<V: Into<::bobbin_bits::U16>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U16 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Wutr {
#[inline]
fn from(other: u32) -> Self {
Wutr(other)
}
}
impl ::core::fmt::Display for Wutr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Wutr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.wut() != 0 { try!(write!(f, " wut=0x{:x}", self.wut()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="alarm A register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Alrmar(pub u32);
impl Alrmar {
#[doc="Alarm A date mask"]
#[inline] pub fn msk4(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 31) & 0x1) as u8) } // [31]
}
#[doc="Returns true if MSK4 != 0"]
#[inline] pub fn test_msk4(&self) -> bool {
self.msk4() != 0
}
#[doc="Sets the MSK4 field."]
#[inline] pub fn set_msk4<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 31);
self.0 |= value << 31;
self
}
#[doc="Week day selection"]
#[inline] pub fn wdsel(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 30) & 0x1) as u8) } // [30]
}
#[doc="Returns true if WDSEL != 0"]
#[inline] pub fn test_wdsel(&self) -> bool {
self.wdsel() != 0
}
#[doc="Sets the WDSEL field."]
#[inline] pub fn set_wdsel<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 30);
self.0 |= value << 30;
self
}
#[doc="Date tens in BCD format"]
#[inline] pub fn dt(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 28) & 0x3) as u8) } // [29:28]
}
#[doc="Returns true if DT != 0"]
#[inline] pub fn test_dt(&self) -> bool {
self.dt() != 0
}
#[doc="Sets the DT field."]
#[inline] pub fn set_dt<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 28);
self.0 |= value << 28;
self
}
#[doc="Date units or day in BCD format"]
#[inline] pub fn du(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xf) as u8) } // [27:24]
}
#[doc="Returns true if DU != 0"]
#[inline] pub fn test_du(&self) -> bool {
self.du() != 0
}
#[doc="Sets the DU field."]
#[inline] pub fn set_du<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 24);
self.0 |= value << 24;
self
}
#[doc="Alarm A hours mask"]
#[inline] pub fn msk3(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 23) & 0x1) as u8) } // [23]
}
#[doc="Returns true if MSK3 != 0"]
#[inline] pub fn test_msk3(&self) -> bool {
self.msk3() != 0
}
#[doc="Sets the MSK3 field."]
#[inline] pub fn set_msk3<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 23);
self.0 |= value << 23;
self
}
#[doc="AM/PM notation"]
#[inline] pub fn pm(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 22) & 0x1) as u8) } // [22]
}
#[doc="Returns true if PM != 0"]
#[inline] pub fn test_pm(&self) -> bool {
self.pm() != 0
}
#[doc="Sets the PM field."]
#[inline] pub fn set_pm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 22);
self.0 |= value << 22;
self
}
#[doc="Hour tens in BCD format"]
#[inline] pub fn ht(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x3) as u8) } // [21:20]
}
#[doc="Returns true if HT != 0"]
#[inline] pub fn test_ht(&self) -> bool {
self.ht() != 0
}
#[doc="Sets the HT field."]
#[inline] pub fn set_ht<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 20);
self.0 |= value << 20;
self
}
#[doc="Hour units in BCD format"]
#[inline] pub fn hu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xf) as u8) } // [19:16]
}
#[doc="Returns true if HU != 0"]
#[inline] pub fn test_hu(&self) -> bool {
self.hu() != 0
}
#[doc="Sets the HU field."]
#[inline] pub fn set_hu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 16);
self.0 |= value << 16;
self
}
#[doc="Alarm A minutes mask"]
#[inline] pub fn msk2(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if MSK2 != 0"]
#[inline] pub fn test_msk2(&self) -> bool {
self.msk2() != 0
}
#[doc="Sets the MSK2 field."]
#[inline] pub fn set_msk2<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Minute tens in BCD format"]
#[inline] pub fn mnt(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x7) as u8) } // [14:12]
}
#[doc="Returns true if MNT != 0"]
#[inline] pub fn test_mnt(&self) -> bool {
self.mnt() != 0
}
#[doc="Sets the MNT field."]
#[inline] pub fn set_mnt<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 12);
self.0 |= value << 12;
self
}
#[doc="Minute units in BCD format"]
#[inline] pub fn mnu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MNU != 0"]
#[inline] pub fn test_mnu(&self) -> bool {
self.mnu() != 0
}
#[doc="Sets the MNU field."]
#[inline] pub fn set_mnu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Alarm A seconds mask"]
#[inline] pub fn msk1(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if MSK1 != 0"]
#[inline] pub fn test_msk1(&self) -> bool {
self.msk1() != 0
}
#[doc="Sets the MSK1 field."]
#[inline] pub fn set_msk1<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
#[doc="Second tens in BCD format"]
#[inline] pub fn st(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x7) as u8) } // [6:4]
}
#[doc="Returns true if ST != 0"]
#[inline] pub fn test_st(&self) -> bool {
self.st() != 0
}
#[doc="Sets the ST field."]
#[inline] pub fn set_st<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 4);
self.0 |= value << 4;
self
}
#[doc="Second units in BCD format"]
#[inline] pub fn su(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if SU != 0"]
#[inline] pub fn test_su(&self) -> bool {
self.su() != 0
}
#[doc="Sets the SU field."]
#[inline] pub fn set_su<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Alrmar {
#[inline]
fn from(other: u32) -> Self {
Alrmar(other)
}
}
impl ::core::fmt::Display for Alrmar {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Alrmar {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.msk4() != 0 { try!(write!(f, " msk4"))}
if self.wdsel() != 0 { try!(write!(f, " wdsel"))}
if self.dt() != 0 { try!(write!(f, " dt=0x{:x}", self.dt()))}
if self.du() != 0 { try!(write!(f, " du=0x{:x}", self.du()))}
if self.msk3() != 0 { try!(write!(f, " msk3"))}
if self.pm() != 0 { try!(write!(f, " pm"))}
if self.ht() != 0 { try!(write!(f, " ht=0x{:x}", self.ht()))}
if self.hu() != 0 { try!(write!(f, " hu=0x{:x}", self.hu()))}
if self.msk2() != 0 { try!(write!(f, " msk2"))}
if self.mnt() != 0 { try!(write!(f, " mnt=0x{:x}", self.mnt()))}
if self.mnu() != 0 { try!(write!(f, " mnu=0x{:x}", self.mnu()))}
if self.msk1() != 0 { try!(write!(f, " msk1"))}
if self.st() != 0 { try!(write!(f, " st=0x{:x}", self.st()))}
if self.su() != 0 { try!(write!(f, " su=0x{:x}", self.su()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="alarm B register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Alrmbr(pub u32);
impl Alrmbr {
#[doc="Alarm B date mask"]
#[inline] pub fn msk4(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 31) & 0x1) as u8) } // [31]
}
#[doc="Returns true if MSK4 != 0"]
#[inline] pub fn test_msk4(&self) -> bool {
self.msk4() != 0
}
#[doc="Sets the MSK4 field."]
#[inline] pub fn set_msk4<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 31);
self.0 |= value << 31;
self
}
#[doc="Week day selection"]
#[inline] pub fn wdsel(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 30) & 0x1) as u8) } // [30]
}
#[doc="Returns true if WDSEL != 0"]
#[inline] pub fn test_wdsel(&self) -> bool {
self.wdsel() != 0
}
#[doc="Sets the WDSEL field."]
#[inline] pub fn set_wdsel<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 30);
self.0 |= value << 30;
self
}
#[doc="Date tens in BCD format"]
#[inline] pub fn dt(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 28) & 0x3) as u8) } // [29:28]
}
#[doc="Returns true if DT != 0"]
#[inline] pub fn test_dt(&self) -> bool {
self.dt() != 0
}
#[doc="Sets the DT field."]
#[inline] pub fn set_dt<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 28);
self.0 |= value << 28;
self
}
#[doc="Date units or day in BCD format"]
#[inline] pub fn du(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xf) as u8) } // [27:24]
}
#[doc="Returns true if DU != 0"]
#[inline] pub fn test_du(&self) -> bool {
self.du() != 0
}
#[doc="Sets the DU field."]
#[inline] pub fn set_du<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 24);
self.0 |= value << 24;
self
}
#[doc="Alarm B hours mask"]
#[inline] pub fn msk3(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 23) & 0x1) as u8) } // [23]
}
#[doc="Returns true if MSK3 != 0"]
#[inline] pub fn test_msk3(&self) -> bool {
self.msk3() != 0
}
#[doc="Sets the MSK3 field."]
#[inline] pub fn set_msk3<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 23);
self.0 |= value << 23;
self
}
#[doc="AM/PM notation"]
#[inline] pub fn pm(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 22) & 0x1) as u8) } // [22]
}
#[doc="Returns true if PM != 0"]
#[inline] pub fn test_pm(&self) -> bool {
self.pm() != 0
}
#[doc="Sets the PM field."]
#[inline] pub fn set_pm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 22);
self.0 |= value << 22;
self
}
#[doc="Hour tens in BCD format"]
#[inline] pub fn ht(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x3) as u8) } // [21:20]
}
#[doc="Returns true if HT != 0"]
#[inline] pub fn test_ht(&self) -> bool {
self.ht() != 0
}
#[doc="Sets the HT field."]
#[inline] pub fn set_ht<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 20);
self.0 |= value << 20;
self
}
#[doc="Hour units in BCD format"]
#[inline] pub fn hu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xf) as u8) } // [19:16]
}
#[doc="Returns true if HU != 0"]
#[inline] pub fn test_hu(&self) -> bool {
self.hu() != 0
}
#[doc="Sets the HU field."]
#[inline] pub fn set_hu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 16);
self.0 |= value << 16;
self
}
#[doc="Alarm B minutes mask"]
#[inline] pub fn msk2(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if MSK2 != 0"]
#[inline] pub fn test_msk2(&self) -> bool {
self.msk2() != 0
}
#[doc="Sets the MSK2 field."]
#[inline] pub fn set_msk2<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Minute tens in BCD format"]
#[inline] pub fn mnt(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x7) as u8) } // [14:12]
}
#[doc="Returns true if MNT != 0"]
#[inline] pub fn test_mnt(&self) -> bool {
self.mnt() != 0
}
#[doc="Sets the MNT field."]
#[inline] pub fn set_mnt<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 12);
self.0 |= value << 12;
self
}
#[doc="Minute units in BCD format"]
#[inline] pub fn mnu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MNU != 0"]
#[inline] pub fn test_mnu(&self) -> bool {
self.mnu() != 0
}
#[doc="Sets the MNU field."]
#[inline] pub fn set_mnu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Alarm B seconds mask"]
#[inline] pub fn msk1(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if MSK1 != 0"]
#[inline] pub fn test_msk1(&self) -> bool {
self.msk1() != 0
}
#[doc="Sets the MSK1 field."]
#[inline] pub fn set_msk1<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
#[doc="Second tens in BCD format"]
#[inline] pub fn st(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x7) as u8) } // [6:4]
}
#[doc="Returns true if ST != 0"]
#[inline] pub fn test_st(&self) -> bool {
self.st() != 0
}
#[doc="Sets the ST field."]
#[inline] pub fn set_st<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 4);
self.0 |= value << 4;
self
}
#[doc="Second units in BCD format"]
#[inline] pub fn su(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if SU != 0"]
#[inline] pub fn test_su(&self) -> bool {
self.su() != 0
}
#[doc="Sets the SU field."]
#[inline] pub fn set_su<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Alrmbr {
#[inline]
fn from(other: u32) -> Self {
Alrmbr(other)
}
}
impl ::core::fmt::Display for Alrmbr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Alrmbr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.msk4() != 0 { try!(write!(f, " msk4"))}
if self.wdsel() != 0 { try!(write!(f, " wdsel"))}
if self.dt() != 0 { try!(write!(f, " dt=0x{:x}", self.dt()))}
if self.du() != 0 { try!(write!(f, " du=0x{:x}", self.du()))}
if self.msk3() != 0 { try!(write!(f, " msk3"))}
if self.pm() != 0 { try!(write!(f, " pm"))}
if self.ht() != 0 { try!(write!(f, " ht=0x{:x}", self.ht()))}
if self.hu() != 0 { try!(write!(f, " hu=0x{:x}", self.hu()))}
if self.msk2() != 0 { try!(write!(f, " msk2"))}
if self.mnt() != 0 { try!(write!(f, " mnt=0x{:x}", self.mnt()))}
if self.mnu() != 0 { try!(write!(f, " mnu=0x{:x}", self.mnu()))}
if self.msk1() != 0 { try!(write!(f, " msk1"))}
if self.st() != 0 { try!(write!(f, " st=0x{:x}", self.st()))}
if self.su() != 0 { try!(write!(f, " su=0x{:x}", self.su()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="write protection register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Wpr(pub u32);
impl Wpr {
#[doc="Write protection key"]
#[inline] pub fn key(&self) -> ::bobbin_bits::U8 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xff) as u8) } // [7:0]
}
#[doc="Returns true if KEY != 0"]
#[inline] pub fn test_key(&self) -> bool {
self.key() != 0
}
#[doc="Sets the KEY field."]
#[inline] pub fn set_key<V: Into<::bobbin_bits::U8>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U8 = value.into();
let value: u32 = value.into();
self.0 &= !(0xff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Wpr {
#[inline]
fn from(other: u32) -> Self {
Wpr(other)
}
}
impl ::core::fmt::Display for Wpr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Wpr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.key() != 0 { try!(write!(f, " key=0x{:x}", self.key()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="sub second register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Ssr(pub u32);
impl Ssr {
#[doc="Sub second value"]
#[inline] pub fn ss(&self) -> ::bobbin_bits::U16 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffff) as u16) } // [15:0]
}
#[doc="Returns true if SS != 0"]
#[inline] pub fn test_ss(&self) -> bool {
self.ss() != 0
}
#[doc="Sets the SS field."]
#[inline] pub fn set_ss<V: Into<::bobbin_bits::U16>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U16 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Ssr {
#[inline]
fn from(other: u32) -> Self {
Ssr(other)
}
}
impl ::core::fmt::Display for Ssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Ssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.ss() != 0 { try!(write!(f, " ss=0x{:x}", self.ss()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="shift control register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Shiftr(pub u32);
impl Shiftr {
#[doc="Add one second"]
#[inline] pub fn add1s(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 31) & 0x1) as u8) } // [31]
}
#[doc="Returns true if ADD1S != 0"]
#[inline] pub fn test_add1s(&self) -> bool {
self.add1s() != 0
}
#[doc="Sets the ADD1S field."]
#[inline] pub fn set_add1s<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 31);
self.0 |= value << 31;
self
}
#[doc="Subtract a fraction of a second"]
#[inline] pub fn subfs(&self) -> ::bobbin_bits::U15 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7fff) as u16) } // [14:0]
}
#[doc="Returns true if SUBFS != 0"]
#[inline] pub fn test_subfs(&self) -> bool {
self.subfs() != 0
}
#[doc="Sets the SUBFS field."]
#[inline] pub fn set_subfs<V: Into<::bobbin_bits::U15>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U15 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7fff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Shiftr {
#[inline]
fn from(other: u32) -> Self {
Shiftr(other)
}
}
impl ::core::fmt::Display for Shiftr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Shiftr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.add1s() != 0 { try!(write!(f, " add1s"))}
if self.subfs() != 0 { try!(write!(f, " subfs=0x{:x}", self.subfs()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="time stamp time register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Tstr(pub u32);
impl Tstr {
#[doc="Second units in BCD format"]
#[inline] pub fn su(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if SU != 0"]
#[inline] pub fn test_su(&self) -> bool {
self.su() != 0
}
#[doc="Sets the SU field."]
#[inline] pub fn set_su<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
#[doc="Second tens in BCD format"]
#[inline] pub fn st(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x7) as u8) } // [6:4]
}
#[doc="Returns true if ST != 0"]
#[inline] pub fn test_st(&self) -> bool {
self.st() != 0
}
#[doc="Sets the ST field."]
#[inline] pub fn set_st<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 4);
self.0 |= value << 4;
self
}
#[doc="Minute units in BCD format"]
#[inline] pub fn mnu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MNU != 0"]
#[inline] pub fn test_mnu(&self) -> bool {
self.mnu() != 0
}
#[doc="Sets the MNU field."]
#[inline] pub fn set_mnu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Minute tens in BCD format"]
#[inline] pub fn mnt(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x7) as u8) } // [14:12]
}
#[doc="Returns true if MNT != 0"]
#[inline] pub fn test_mnt(&self) -> bool {
self.mnt() != 0
}
#[doc="Sets the MNT field."]
#[inline] pub fn set_mnt<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 12);
self.0 |= value << 12;
self
}
#[doc="Hour units in BCD format"]
#[inline] pub fn hu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0xf) as u8) } // [19:16]
}
#[doc="Returns true if HU != 0"]
#[inline] pub fn test_hu(&self) -> bool {
self.hu() != 0
}
#[doc="Sets the HU field."]
#[inline] pub fn set_hu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 16);
self.0 |= value << 16;
self
}
#[doc="Hour tens in BCD format"]
#[inline] pub fn ht(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x3) as u8) } // [21:20]
}
#[doc="Returns true if HT != 0"]
#[inline] pub fn test_ht(&self) -> bool {
self.ht() != 0
}
#[doc="Sets the HT field."]
#[inline] pub fn set_ht<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 20);
self.0 |= value << 20;
self
}
#[doc="AM/PM notation"]
#[inline] pub fn pm(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 22) & 0x1) as u8) } // [22]
}
#[doc="Returns true if PM != 0"]
#[inline] pub fn test_pm(&self) -> bool {
self.pm() != 0
}
#[doc="Sets the PM field."]
#[inline] pub fn set_pm<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 22);
self.0 |= value << 22;
self
}
}
impl From<u32> for Tstr {
#[inline]
fn from(other: u32) -> Self {
Tstr(other)
}
}
impl ::core::fmt::Display for Tstr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Tstr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.su() != 0 { try!(write!(f, " su=0x{:x}", self.su()))}
if self.st() != 0 { try!(write!(f, " st=0x{:x}", self.st()))}
if self.mnu() != 0 { try!(write!(f, " mnu=0x{:x}", self.mnu()))}
if self.mnt() != 0 { try!(write!(f, " mnt=0x{:x}", self.mnt()))}
if self.hu() != 0 { try!(write!(f, " hu=0x{:x}", self.hu()))}
if self.ht() != 0 { try!(write!(f, " ht=0x{:x}", self.ht()))}
if self.pm() != 0 { try!(write!(f, " pm"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="time stamp date register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Tsdr(pub u32);
impl Tsdr {
#[doc="Week day units"]
#[inline] pub fn wdu(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x7) as u8) } // [15:13]
}
#[doc="Returns true if WDU != 0"]
#[inline] pub fn test_wdu(&self) -> bool {
self.wdu() != 0
}
#[doc="Sets the WDU field."]
#[inline] pub fn set_wdu<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 13);
self.0 |= value << 13;
self
}
#[doc="Month tens in BCD format"]
#[inline] pub fn mt(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 12) & 0x1) as u8) } // [12]
}
#[doc="Returns true if MT != 0"]
#[inline] pub fn test_mt(&self) -> bool {
self.mt() != 0
}
#[doc="Sets the MT field."]
#[inline] pub fn set_mt<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 12);
self.0 |= value << 12;
self
}
#[doc="Month units in BCD format"]
#[inline] pub fn mu(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0xf) as u8) } // [11:8]
}
#[doc="Returns true if MU != 0"]
#[inline] pub fn test_mu(&self) -> bool {
self.mu() != 0
}
#[doc="Sets the MU field."]
#[inline] pub fn set_mu<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 8);
self.0 |= value << 8;
self
}
#[doc="Date tens in BCD format"]
#[inline] pub fn dt(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x3) as u8) } // [5:4]
}
#[doc="Returns true if DT != 0"]
#[inline] pub fn test_dt(&self) -> bool {
self.dt() != 0
}
#[doc="Sets the DT field."]
#[inline] pub fn set_dt<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 4);
self.0 |= value << 4;
self
}
#[doc="Date units in BCD format"]
#[inline] pub fn du(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xf) as u8) } // [3:0]
}
#[doc="Returns true if DU != 0"]
#[inline] pub fn test_du(&self) -> bool {
self.du() != 0
}
#[doc="Sets the DU field."]
#[inline] pub fn set_du<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Tsdr {
#[inline]
fn from(other: u32) -> Self {
Tsdr(other)
}
}
impl ::core::fmt::Display for Tsdr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Tsdr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.wdu() != 0 { try!(write!(f, " wdu=0x{:x}", self.wdu()))}
if self.mt() != 0 { try!(write!(f, " mt"))}
if self.mu() != 0 { try!(write!(f, " mu=0x{:x}", self.mu()))}
if self.dt() != 0 { try!(write!(f, " dt=0x{:x}", self.dt()))}
if self.du() != 0 { try!(write!(f, " du=0x{:x}", self.du()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="timestamp sub second register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Tsssr(pub u32);
impl Tsssr {
#[doc="Sub second value"]
#[inline] pub fn ss(&self) -> ::bobbin_bits::U16 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffff) as u16) } // [15:0]
}
#[doc="Returns true if SS != 0"]
#[inline] pub fn test_ss(&self) -> bool {
self.ss() != 0
}
#[doc="Sets the SS field."]
#[inline] pub fn set_ss<V: Into<::bobbin_bits::U16>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U16 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Tsssr {
#[inline]
fn from(other: u32) -> Self {
Tsssr(other)
}
}
impl ::core::fmt::Display for Tsssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Tsssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.ss() != 0 { try!(write!(f, " ss=0x{:x}", self.ss()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="calibration register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Calr(pub u32);
impl Calr {
#[doc="Increase frequency of RTC by 488.5 ppm"]
#[inline] pub fn calp(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if CALP != 0"]
#[inline] pub fn test_calp(&self) -> bool {
self.calp() != 0
}
#[doc="Sets the CALP field."]
#[inline] pub fn set_calp<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Use an 8-second calibration cycle period"]
#[inline] pub fn calw8(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 14) & 0x1) as u8) } // [14]
}
#[doc="Returns true if CALW8 != 0"]
#[inline] pub fn test_calw8(&self) -> bool {
self.calw8() != 0
}
#[doc="Sets the CALW8 field."]
#[inline] pub fn set_calw8<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 14);
self.0 |= value << 14;
self
}
#[doc="Use a 16-second calibration cycle period"]
#[inline] pub fn calw16(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x1) as u8) } // [13]
}
#[doc="Returns true if CALW16 != 0"]
#[inline] pub fn test_calw16(&self) -> bool {
self.calw16() != 0
}
#[doc="Sets the CALW16 field."]
#[inline] pub fn set_calw16<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 13);
self.0 |= value << 13;
self
}
#[doc="Calibration minus"]
#[inline] pub fn calm(&self) -> ::bobbin_bits::U9 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1ff) as u16) } // [8:0]
}
#[doc="Returns true if CALM != 0"]
#[inline] pub fn test_calm(&self) -> bool {
self.calm() != 0
}
#[doc="Sets the CALM field."]
#[inline] pub fn set_calm<V: Into<::bobbin_bits::U9>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U9 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1ff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Calr {
#[inline]
fn from(other: u32) -> Self {
Calr(other)
}
}
impl ::core::fmt::Display for Calr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Calr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.calp() != 0 { try!(write!(f, " calp"))}
if self.calw8() != 0 { try!(write!(f, " calw8"))}
if self.calw16() != 0 { try!(write!(f, " calw16"))}
if self.calm() != 0 { try!(write!(f, " calm=0x{:x}", self.calm()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="tamper configuration register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Tampcr(pub u32);
impl Tampcr {
#[doc="Tamper 1 detection enable"]
#[inline] pub fn tamp1e(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0]
}
#[doc="Returns true if TAMP1E != 0"]
#[inline] pub fn test_tamp1e(&self) -> bool {
self.tamp1e() != 0
}
#[doc="Sets the TAMP1E field."]
#[inline] pub fn set_tamp1e<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 0);
self.0 |= value << 0;
self
}
#[doc="Active level for tamper 1"]
#[inline] pub fn tamp1trg(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1]
}
#[doc="Returns true if TAMP1TRG != 0"]
#[inline] pub fn test_tamp1trg(&self) -> bool {
self.tamp1trg() != 0
}
#[doc="Sets the TAMP1TRG field."]
#[inline] pub fn set_tamp1trg<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 1);
self.0 |= value << 1;
self
}
#[doc="Tamper interrupt enable"]
#[inline] pub fn tampie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 2) & 0x1) as u8) } // [2]
}
#[doc="Returns true if TAMPIE != 0"]
#[inline] pub fn test_tampie(&self) -> bool {
self.tampie() != 0
}
#[doc="Sets the TAMPIE field."]
#[inline] pub fn set_tampie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 2);
self.0 |= value << 2;
self
}
#[doc="Tamper 2 detection enable"]
#[inline] pub fn tamp2e(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 3) & 0x1) as u8) } // [3]
}
#[doc="Returns true if TAMP2E != 0"]
#[inline] pub fn test_tamp2e(&self) -> bool {
self.tamp2e() != 0
}
#[doc="Sets the TAMP2E field."]
#[inline] pub fn set_tamp2e<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 3);
self.0 |= value << 3;
self
}
#[doc="Active level for tamper 2"]
#[inline] pub fn tamp2trg(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 4) & 0x1) as u8) } // [4]
}
#[doc="Returns true if TAMP2TRG != 0"]
#[inline] pub fn test_tamp2trg(&self) -> bool {
self.tamp2trg() != 0
}
#[doc="Sets the TAMP2TRG field."]
#[inline] pub fn set_tamp2trg<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 4);
self.0 |= value << 4;
self
}
#[doc="Tamper 3 detection enable"]
#[inline] pub fn tamp3e(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 5) & 0x1) as u8) } // [5]
}
#[doc="Returns true if TAMP3E != 0"]
#[inline] pub fn test_tamp3e(&self) -> bool {
self.tamp3e() != 0
}
#[doc="Sets the TAMP3E field."]
#[inline] pub fn set_tamp3e<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 5);
self.0 |= value << 5;
self
}
#[doc="Active level for tamper 3"]
#[inline] pub fn tamp3trg(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 6) & 0x1) as u8) } // [6]
}
#[doc="Returns true if TAMP3TRG != 0"]
#[inline] pub fn test_tamp3trg(&self) -> bool {
self.tamp3trg() != 0
}
#[doc="Sets the TAMP3TRG field."]
#[inline] pub fn set_tamp3trg<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 6);
self.0 |= value << 6;
self
}
#[doc="Activate timestamp on tamper detection event"]
#[inline] pub fn tampts(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 7) & 0x1) as u8) } // [7]
}
#[doc="Returns true if TAMPTS != 0"]
#[inline] pub fn test_tampts(&self) -> bool {
self.tampts() != 0
}
#[doc="Sets the TAMPTS field."]
#[inline] pub fn | <V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 7);
self.0 |= value << 7;
self
}
#[doc="Tamper sampling frequency"]
#[inline] pub fn tampfreq(&self) -> ::bobbin_bits::U3 {
unsafe { ::core::mem::transmute(((self.0 >> 8) & 0x7) as u8) } // [10:8]
}
#[doc="Returns true if TAMPFREQ != 0"]
#[inline] pub fn test_tampfreq(&self) -> bool {
self.tampfreq() != 0
}
#[doc="Sets the TAMPFREQ field."]
#[inline] pub fn set_tampfreq<V: Into<::bobbin_bits::U3>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U3 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7 << 8);
self.0 |= value << 8;
self
}
#[doc="Tamper filter count"]
#[inline] pub fn tampflt(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 11) & 0x3) as u8) } // [12:11]
}
#[doc="Returns true if TAMPFLT != 0"]
#[inline] pub fn test_tampflt(&self) -> bool {
self.tampflt() != 0
}
#[doc="Sets the TAMPFLT field."]
#[inline] pub fn set_tampflt<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 11);
self.0 |= value << 11;
self
}
#[doc="Tamper precharge duration"]
#[inline] pub fn tampprch(&self) -> ::bobbin_bits::U2 {
unsafe { ::core::mem::transmute(((self.0 >> 13) & 0x3) as u8) } // [14:13]
}
#[doc="Returns true if TAMPPRCH != 0"]
#[inline] pub fn test_tampprch(&self) -> bool {
self.tampprch() != 0
}
#[doc="Sets the TAMPPRCH field."]
#[inline] pub fn set_tampprch<V: Into<::bobbin_bits::U2>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U2 = value.into();
let value: u32 = value.into();
self.0 &= !(0x3 << 13);
self.0 |= value << 13;
self
}
#[doc="TAMPER pull-up disable"]
#[inline] pub fn tamppudis(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 15) & 0x1) as u8) } // [15]
}
#[doc="Returns true if TAMPPUDIS != 0"]
#[inline] pub fn test_tamppudis(&self) -> bool {
self.tamppudis() != 0
}
#[doc="Sets the TAMPPUDIS field."]
#[inline] pub fn set_tamppudis<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 15);
self.0 |= value << 15;
self
}
#[doc="Tamper 1 interrupt enable"]
#[inline] pub fn tamp1ie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 16) & 0x1) as u8) } // [16]
}
#[doc="Returns true if TAMP1IE != 0"]
#[inline] pub fn test_tamp1ie(&self) -> bool {
self.tamp1ie() != 0
}
#[doc="Sets the TAMP1IE field."]
#[inline] pub fn set_tamp1ie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 16);
self.0 |= value << 16;
self
}
#[doc="Tamper 1 no erase"]
#[inline] pub fn tamp1noerase(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 17) & 0x1) as u8) } // [17]
}
#[doc="Returns true if TAMP1NOERASE != 0"]
#[inline] pub fn test_tamp1noerase(&self) -> bool {
self.tamp1noerase() != 0
}
#[doc="Sets the TAMP1NOERASE field."]
#[inline] pub fn set_tamp1noerase<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 17);
self.0 |= value << 17;
self
}
#[doc="Tamper 1 mask flag"]
#[inline] pub fn tamp1mf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 18) & 0x1) as u8) } // [18]
}
#[doc="Returns true if TAMP1MF != 0"]
#[inline] pub fn test_tamp1mf(&self) -> bool {
self.tamp1mf() != 0
}
#[doc="Sets the TAMP1MF field."]
#[inline] pub fn set_tamp1mf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 18);
self.0 |= value << 18;
self
}
#[doc="Tamper 2 interrupt enable"]
#[inline] pub fn tamp2ie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 19) & 0x1) as u8) } // [19]
}
#[doc="Returns true if TAMP2IE != 0"]
#[inline] pub fn test_tamp2ie(&self) -> bool {
self.tamp2ie() != 0
}
#[doc="Sets the TAMP2IE field."]
#[inline] pub fn set_tamp2ie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 19);
self.0 |= value << 19;
self
}
#[doc="Tamper 2 no erase"]
#[inline] pub fn tamp2noerase(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 20) & 0x1) as u8) } // [20]
}
#[doc="Returns true if TAMP2NOERASE != 0"]
#[inline] pub fn test_tamp2noerase(&self) -> bool {
self.tamp2noerase() != 0
}
#[doc="Sets the TAMP2NOERASE field."]
#[inline] pub fn set_tamp2noerase<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 20);
self.0 |= value << 20;
self
}
#[doc="Tamper 2 mask flag"]
#[inline] pub fn tamp2mf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 21) & 0x1) as u8) } // [21]
}
#[doc="Returns true if TAMP2MF != 0"]
#[inline] pub fn test_tamp2mf(&self) -> bool {
self.tamp2mf() != 0
}
#[doc="Sets the TAMP2MF field."]
#[inline] pub fn set_tamp2mf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 21);
self.0 |= value << 21;
self
}
#[doc="Tamper 3 interrupt enable"]
#[inline] pub fn tamp3ie(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 22) & 0x1) as u8) } // [22]
}
#[doc="Returns true if TAMP3IE != 0"]
#[inline] pub fn test_tamp3ie(&self) -> bool {
self.tamp3ie() != 0
}
#[doc="Sets the TAMP3IE field."]
#[inline] pub fn set_tamp3ie<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 22);
self.0 |= value << 22;
self
}
#[doc="Tamper 3 no erase"]
#[inline] pub fn tamp3noerase(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 23) & 0x1) as u8) } // [23]
}
#[doc="Returns true if TAMP3NOERASE != 0"]
#[inline] pub fn test_tamp3noerase(&self) -> bool {
self.tamp3noerase() != 0
}
#[doc="Sets the TAMP3NOERASE field."]
#[inline] pub fn set_tamp3noerase<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 23);
self.0 |= value << 23;
self
}
#[doc="Tamper 3 mask flag"]
#[inline] pub fn tamp3mf(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0x1) as u8) } // [24]
}
#[doc="Returns true if TAMP3MF != 0"]
#[inline] pub fn test_tamp3mf(&self) -> bool {
self.tamp3mf() != 0
}
#[doc="Sets the TAMP3MF field."]
#[inline] pub fn set_tamp3mf<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 24);
self.0 |= value << 24;
self
}
}
impl From<u32> for Tampcr {
#[inline]
fn from(other: u32) -> Self {
Tampcr(other)
}
}
impl ::core::fmt::Display for Tampcr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Tampcr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.tamp1e() != 0 { try!(write!(f, " tamp1e"))}
if self.tamp1trg() != 0 { try!(write!(f, " tamp1trg"))}
if self.tampie() != 0 { try!(write!(f, " tampie"))}
if self.tamp2e() != 0 { try!(write!(f, " tamp2e"))}
if self.tamp2trg() != 0 { try!(write!(f, " tamp2trg"))}
if self.tamp3e() != 0 { try!(write!(f, " tamp3e"))}
if self.tamp3trg() != 0 { try!(write!(f, " tamp3trg"))}
if self.tampts() != 0 { try!(write!(f, " tampts"))}
if self.tampfreq() != 0 { try!(write!(f, " tampfreq=0x{:x}", self.tampfreq()))}
if self.tampflt() != 0 { try!(write!(f, " tampflt=0x{:x}", self.tampflt()))}
if self.tampprch() != 0 { try!(write!(f, " tampprch=0x{:x}", self.tampprch()))}
if self.tamppudis() != 0 { try!(write!(f, " tamppudis"))}
if self.tamp1ie() != 0 { try!(write!(f, " tamp1ie"))}
if self.tamp1noerase() != 0 { try!(write!(f, " tamp1noerase"))}
if self.tamp1mf() != 0 { try!(write!(f, " tamp1mf"))}
if self.tamp2ie() != 0 { try!(write!(f, " tamp2ie"))}
if self.tamp2noerase() != 0 { try!(write!(f, " tamp2noerase"))}
if self.tamp2mf() != 0 { try!(write!(f, " tamp2mf"))}
if self.tamp3ie() != 0 { try!(write!(f, " tamp3ie"))}
if self.tamp3noerase() != 0 { try!(write!(f, " tamp3noerase"))}
if self.tamp3mf() != 0 { try!(write!(f, " tamp3mf"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="alarm A sub second register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Alrmassr(pub u32);
impl Alrmassr {
#[doc="Mask the most-significant bits starting at this bit"]
#[inline] pub fn maskss(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xf) as u8) } // [27:24]
}
#[doc="Returns true if MASKSS != 0"]
#[inline] pub fn test_maskss(&self) -> bool {
self.maskss() != 0
}
#[doc="Sets the MASKSS field."]
#[inline] pub fn set_maskss<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 24);
self.0 |= value << 24;
self
}
#[doc="Sub seconds value"]
#[inline] pub fn ss(&self) -> ::bobbin_bits::U15 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7fff) as u16) } // [14:0]
}
#[doc="Returns true if SS != 0"]
#[inline] pub fn test_ss(&self) -> bool {
self.ss() != 0
}
#[doc="Sets the SS field."]
#[inline] pub fn set_ss<V: Into<::bobbin_bits::U15>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U15 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7fff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Alrmassr {
#[inline]
fn from(other: u32) -> Self {
Alrmassr(other)
}
}
impl ::core::fmt::Display for Alrmassr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Alrmassr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.maskss() != 0 { try!(write!(f, " maskss=0x{:x}", self.maskss()))}
if self.ss() != 0 { try!(write!(f, " ss=0x{:x}", self.ss()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="alarm B sub second register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Alrmbssr(pub u32);
impl Alrmbssr {
#[doc="Mask the most-significant bits starting at this bit"]
#[inline] pub fn maskss(&self) -> ::bobbin_bits::U4 {
unsafe { ::core::mem::transmute(((self.0 >> 24) & 0xf) as u8) } // [27:24]
}
#[doc="Returns true if MASKSS != 0"]
#[inline] pub fn test_maskss(&self) -> bool {
self.maskss() != 0
}
#[doc="Sets the MASKSS field."]
#[inline] pub fn set_maskss<V: Into<::bobbin_bits::U4>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U4 = value.into();
let value: u32 = value.into();
self.0 &= !(0xf << 24);
self.0 |= value << 24;
self
}
#[doc="Sub seconds value"]
#[inline] pub fn ss(&self) -> ::bobbin_bits::U15 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x7fff) as u16) } // [14:0]
}
#[doc="Returns true if SS != 0"]
#[inline] pub fn test_ss(&self) -> bool {
self.ss() != 0
}
#[doc="Sets the SS field."]
#[inline] pub fn set_ss<V: Into<::bobbin_bits::U15>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U15 = value.into();
let value: u32 = value.into();
self.0 &= !(0x7fff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Alrmbssr {
#[inline]
fn from(other: u32) -> Self {
Alrmbssr(other)
}
}
impl ::core::fmt::Display for Alrmbssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Alrmbssr {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.maskss() != 0 { try!(write!(f, " maskss=0x{:x}", self.maskss()))}
if self.ss() != 0 { try!(write!(f, " ss=0x{:x}", self.ss()))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="option register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Or(pub u32);
impl Or {
#[doc="RTC_ALARM on PC13 output type"]
#[inline] pub fn rtc_alarm_type(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0x1) as u8) } // [0]
}
#[doc="Returns true if RTC_ALARM_TYPE != 0"]
#[inline] pub fn test_rtc_alarm_type(&self) -> bool {
self.rtc_alarm_type() != 0
}
#[doc="Sets the RTC_ALARM_TYPE field."]
#[inline] pub fn set_rtc_alarm_type<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 0);
self.0 |= value << 0;
self
}
#[doc="RTC_OUT remap"]
#[inline] pub fn rtc_out_rmp(&self) -> ::bobbin_bits::U1 {
unsafe { ::core::mem::transmute(((self.0 >> 1) & 0x1) as u8) } // [1]
}
#[doc="Returns true if RTC_OUT_RMP != 0"]
#[inline] pub fn test_rtc_out_rmp(&self) -> bool {
self.rtc_out_rmp() != 0
}
#[doc="Sets the RTC_OUT_RMP field."]
#[inline] pub fn set_rtc_out_rmp<V: Into<::bobbin_bits::U1>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U1 = value.into();
let value: u32 = value.into();
self.0 &= !(0x1 << 1);
self.0 |= value << 1;
self
}
}
impl From<u32> for Or {
#[inline]
fn from(other: u32) -> Self {
Or(other)
}
}
impl ::core::fmt::Display for Or {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Or {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
if self.rtc_alarm_type() != 0 { try!(write!(f, " rtc_alarm_type"))}
if self.rtc_out_rmp() != 0 { try!(write!(f, " rtc_out_rmp"))}
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp0r(pub u32);
impl Bkp0r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp0r {
#[inline]
fn from(other: u32) -> Self {
Bkp0r(other)
}
}
impl ::core::fmt::Display for Bkp0r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp0r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp1r(pub u32);
impl Bkp1r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp1r {
#[inline]
fn from(other: u32) -> Self {
Bkp1r(other)
}
}
impl ::core::fmt::Display for Bkp1r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp1r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp2r(pub u32);
impl Bkp2r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp2r {
#[inline]
fn from(other: u32) -> Self {
Bkp2r(other)
}
}
impl ::core::fmt::Display for Bkp2r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp2r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp3r(pub u32);
impl Bkp3r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp3r {
#[inline]
fn from(other: u32) -> Self {
Bkp3r(other)
}
}
impl ::core::fmt::Display for Bkp3r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp3r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp4r(pub u32);
impl Bkp4r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp4r {
#[inline]
fn from(other: u32) -> Self {
Bkp4r(other)
}
}
impl ::core::fmt::Display for Bkp4r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp4r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp5r(pub u32);
impl Bkp5r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp5r {
#[inline]
fn from(other: u32) -> Self {
Bkp5r(other)
}
}
impl ::core::fmt::Display for Bkp5r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp5r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp6r(pub u32);
impl Bkp6r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp6r {
#[inline]
fn from(other: u32) -> Self {
Bkp6r(other)
}
}
impl ::core::fmt::Display for Bkp6r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp6r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp7r(pub u32);
impl Bkp7r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp7r {
#[inline]
fn from(other: u32) -> Self {
Bkp7r(other)
}
}
impl ::core::fmt::Display for Bkp7r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp7r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp8r(pub u32);
impl Bkp8r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp8r {
#[inline]
fn from(other: u32) -> Self {
Bkp8r(other)
}
}
impl ::core::fmt::Display for Bkp8r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp8r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp9r(pub u32);
impl Bkp9r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp9r {
#[inline]
fn from(other: u32) -> Self {
Bkp9r(other)
}
}
impl ::core::fmt::Display for Bkp9r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp9r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp10r(pub u32);
impl Bkp10r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp10r {
#[inline]
fn from(other: u32) -> Self {
Bkp10r(other)
}
}
impl ::core::fmt::Display for Bkp10r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp10r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp11r(pub u32);
impl Bkp11r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp11r {
#[inline]
fn from(other: u32) -> Self {
Bkp11r(other)
}
}
impl ::core::fmt::Display for Bkp11r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp11r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp12r(pub u32);
impl Bkp12r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp12r {
#[inline]
fn from(other: u32) -> Self {
Bkp12r(other)
}
}
impl ::core::fmt::Display for Bkp12r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp12r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp13r(pub u32);
impl Bkp13r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp13r {
#[inline]
fn from(other: u32) -> Self {
Bkp13r(other)
}
}
impl ::core::fmt::Display for Bkp13r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp13r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp14r(pub u32);
impl Bkp14r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp14r {
#[inline]
fn from(other: u32) -> Self {
Bkp14r(other)
}
}
impl ::core::fmt::Display for Bkp14r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp14r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp15r(pub u32);
impl Bkp15r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp15r {
#[inline]
fn from(other: u32) -> Self {
Bkp15r(other)
}
}
impl ::core::fmt::Display for Bkp15r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp15r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp16r(pub u32);
impl Bkp16r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp16r {
#[inline]
fn from(other: u32) -> Self {
Bkp16r(other)
}
}
impl ::core::fmt::Display for Bkp16r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp16r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp17r(pub u32);
impl Bkp17r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp17r {
#[inline]
fn from(other: u32) -> Self {
Bkp17r(other)
}
}
impl ::core::fmt::Display for Bkp17r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp17r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp18r(pub u32);
impl Bkp18r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp18r {
#[inline]
fn from(other: u32) -> Self {
Bkp18r(other)
}
}
impl ::core::fmt::Display for Bkp18r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp18r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
#[doc="backup register"]
#[derive(Default, Clone, Copy, PartialEq, Eq)]
pub struct Bkp19r(pub u32);
impl Bkp19r {
#[doc="BKP"]
#[inline] pub fn bkp(&self) -> ::bobbin_bits::U32 {
unsafe { ::core::mem::transmute(((self.0 >> 0) & 0xffffffff) as u32) } // [31:0]
}
#[doc="Returns true if BKP != 0"]
#[inline] pub fn test_bkp(&self) -> bool {
self.bkp() != 0
}
#[doc="Sets the BKP field."]
#[inline] pub fn set_bkp<V: Into<::bobbin_bits::U32>>(mut self, value: V) -> Self {
let value: ::bobbin_bits::U32 = value.into();
let value: u32 = value.into();
self.0 &= !(0xffffffff << 0);
self.0 |= value << 0;
self
}
}
impl From<u32> for Bkp19r {
#[inline]
fn from(other: u32) -> Self {
Bkp19r(other)
}
}
impl ::core::fmt::Display for Bkp19r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
self.0.fmt(f)
}
}
impl ::core::fmt::Debug for Bkp19r {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
try!(write!(f, "[0x{:08x}", self.0));
try!(write!(f, "]"));
Ok(())
}
}
| set_tampts |
exti_h743_h743v_h753_h753v_h7b3.rs | #![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! External interrupt/event controller
//!
//! Used by: stm32h743, stm32h743v, stm32h753, stm32h753v, stm32h7b3
#[cfg(not(feature = "nosync"))]
pub use crate::stm32h7::peripherals::exti_v1::Instance;
pub use crate::stm32h7::peripherals::exti_v1::{RegisterBlock, ResetValues};
pub use crate::stm32h7::peripherals::exti_v1::{
CPUEMR1, CPUEMR2, CPUEMR3, CPUIMR1, CPUIMR2, CPUIMR3, CPUPR1, CPUPR2, CPUPR3, D3PCR1H, D3PCR1L,
D3PCR2H, D3PCR2L, D3PCR3H, D3PMR1, D3PMR2, D3PMR3, FTSR1, FTSR2, FTSR3, RTSR1, RTSR2, RTSR3,
SWIER1, SWIER2, SWIER3,
};
/// Access functions for the EXTI peripheral instance
pub mod EXTI {
use super::ResetValues;
#[cfg(not(feature = "nosync"))]
use super::Instance;
#[cfg(not(feature = "nosync"))]
const INSTANCE: Instance = Instance {
addr: 0x58000000,
_marker: ::core::marker::PhantomData,
};
/// Reset values for each field in EXTI
pub const reset: ResetValues = ResetValues {
RTSR1: 0x00000000,
FTSR1: 0x00000000,
SWIER1: 0x00000000,
D3PMR1: 0x00000000,
D3PCR1L: 0x00000000,
D3PCR1H: 0x00000000,
RTSR2: 0x00000000,
FTSR2: 0x00000000,
SWIER2: 0x00000000,
D3PMR2: 0x00000000,
D3PCR2L: 0x00000000,
D3PCR2H: 0x00000000,
RTSR3: 0x00000000,
FTSR3: 0x00000000,
SWIER3: 0x00000000,
D3PMR3: 0x00000000,
D3PCR3H: 0x00000000,
CPUIMR1: 0xFFC00000,
CPUEMR1: 0x00000000,
CPUPR1: 0x00000000,
CPUIMR2: 0x00000000,
CPUEMR2: 0x00000000,
CPUPR2: 0x00000000,
CPUIMR3: 0x00000000,
CPUEMR3: 0x00000000,
CPUPR3: 0x00000000,
};
#[cfg(not(feature = "nosync"))]
#[allow(renamed_and_removed_lints)]
#[allow(private_no_mangle_statics)]
#[no_mangle]
static mut EXTI_TAKEN: bool = false;
/// Safe access to EXTI
///
/// This function returns `Some(Instance)` if this instance is not
/// currently taken, and `None` if it is. This ensures that if you
/// do get `Some(Instance)`, you are ensured unique access to
/// the peripheral and there cannot be data races (unless other
/// code uses `unsafe`, of course). You can then pass the
/// `Instance` around to other functions as required. When you're
/// done with it, you can call `release(instance)` to return it.
///
/// `Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
external_cortex_m::interrupt::free(|_| unsafe {
if EXTI_TAKEN {
None
} else {
EXTI_TAKEN = true;
Some(INSTANCE)
}
})
}
/// Release exclusive access to EXTI
///
/// This function allows you to return an `Instance` so that it
/// is available to `take()` again. This function will panic if
/// you return a different `Instance` or if this instance is not
/// already taken.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn release(inst: Instance) {
external_cortex_m::interrupt::free(|_| unsafe {
if EXTI_TAKEN && inst.addr == INSTANCE.addr {
EXTI_TAKEN = false;
} else {
panic!("Released a peripheral which was not taken");
}
});
}
/// Unsafely steal EXTI
///
/// This function is similar to take() but forcibly takes the
/// Instance, marking it as taken irregardless of its previous
/// state.
#[cfg(not(feature = "nosync"))]
#[inline]
pub unsafe fn steal() -> Instance {
EXTI_TAKEN = true;
INSTANCE
}
}
/// Raw pointer to EXTI
///
/// Dereferencing this is unsafe because you are not ensured unique
/// access to the peripheral, so you may encounter data races with
/// other users of this peripheral. It is up to you to ensure you
/// will not cause data races. | pub const EXTI: *const RegisterBlock = 0x58000000 as *const _; | ///
/// This constant is provided for ease of use in unsafe code: you can
/// simply call for example `write_reg!(gpio, GPIOA, ODR, 1);`. |
node.go | package parser
import "reflect"
// MapNamePlaceholder is the placeholder for the map name.
const MapNamePlaceholder = "<name>"
// Node is a label node. | Name string `json:"name"`
Description string `json:"description,omitempty"`
FieldName string `json:"fieldName"`
Value string `json:"value,omitempty"`
Disabled bool `json:"disabled,omitempty"`
Kind reflect.Kind `json:"kind,omitempty"`
Tag reflect.StructTag `json:"tag,omitempty"`
Children []*Node `json:"children,omitempty"`
} | type Node struct { |
components__EnterOrderDetail__models__bkinfo.jsx.async.js | (window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[1],{"tH/P":function(e,a,n){"use strict";n.r(a);var t=n("MVZn"),c=n.n(t),s=n("o0o1"),r=n.n(s),o=n("dCQc");a["default"]={namespace:"bkinfo",state:{},effects:{fetch:r.a.mark(function e(a,n){var t,c,s,p,u,i,d;return r.a.wrap(function(e){while(1)switch(e.prev=e.next){case 0:return t=a.payload,c=a.callBack,s=n.call,p=n.put,e.next=4,s(o["h"],t);case 4:return u=e.sent,i=u.msg,d=u.data,e.next=8,p({type:"save",payload:d});case 8:c&&c(i,d);case 9:case"end":return e.stop()}},e,this)})},reducers:{save:function(e,a){var n=a.payload;return c()({},e,{},n)}}}}}]); |
||
setup.py | from setuptools import find_packages
from setuptools import setup
version = '0.0.0'
setup( | packages=find_packages(),
install_requires=open('requirements.txt').readlines(),
description='',
long_description=open('README.md').read(),
author='Shingo Kitagawa',
author_email='[email protected]',
url='https://github.com/knorth55/chainer-dense-fusion',
license='MIT',
keywords='machine-learning',
) | name='chainer_dense_fusion',
version=version, |
test_pitch.py | import unittest
from app.main.models import Pitches
from app import db
class PitchesModelTest(unittest.TestCase):
def setUp(self):
self.new_pitch=Pitches(pitch='new',comment='I love darkness', category='sports',user_id = 123)
def tearDown(self):
Pitches.query.delete()
def test __init__(self):
self.assertEquals(self.new_pitch.pitch,'new')
self.assertEquals(self.new_pitch.comment,'I love darkness')
self.assertEquals(self.new_pitch.category='sports')
self.assertEquals(self.new_pitch.user_id, 123)
def test_save_pitch(self):
self.new_pitch.save_pitch()
self.assertTrue(len(Pitches.query.all())>0) |
self.new_pitch.save_pitch
got_pitch = Pitches.get_pitch(12345)
self.assertTrue(len(got_pitch) == 1) |
def test_get_pitch_by_id(self): |
affinity.rs | // Generated from definition io.k8s.api.core.v1.Affinity
/// Affinity is a group of affinity scheduling rules.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Affinity {
/// Describes node affinity scheduling rules for the pod.
pub node_affinity: Option<crate::api::core::v1::NodeAffinity>,
/// Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s)).
pub pod_affinity: Option<crate::api::core::v1::PodAffinity>,
/// Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s)).
pub pod_anti_affinity: Option<crate::api::core::v1::PodAntiAffinity>,
}
impl<'de> crate::serde::Deserialize<'de> for Affinity {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_node_affinity,
Key_pod_affinity,
Key_pod_anti_affinity,
Other,
}
impl<'de> crate::serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: crate::serde::Deserializer<'de> {
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn | (&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: crate::serde::de::Error {
Ok(match v {
"nodeAffinity" => Field::Key_node_affinity,
"podAffinity" => Field::Key_pod_affinity,
"podAntiAffinity" => Field::Key_pod_anti_affinity,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> crate::serde::de::Visitor<'de> for Visitor {
type Value = Affinity;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Affinity")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: crate::serde::de::MapAccess<'de> {
let mut value_node_affinity: Option<crate::api::core::v1::NodeAffinity> = None;
let mut value_pod_affinity: Option<crate::api::core::v1::PodAffinity> = None;
let mut value_pod_anti_affinity: Option<crate::api::core::v1::PodAntiAffinity> = None;
while let Some(key) = crate::serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_node_affinity => value_node_affinity = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_pod_affinity => value_pod_affinity = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Key_pod_anti_affinity => value_pod_anti_affinity = crate::serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: crate::serde::de::IgnoredAny = crate::serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(Affinity {
node_affinity: value_node_affinity,
pod_affinity: value_pod_affinity,
pod_anti_affinity: value_pod_anti_affinity,
})
}
}
deserializer.deserialize_struct(
"Affinity",
&[
"nodeAffinity",
"podAffinity",
"podAntiAffinity",
],
Visitor,
)
}
}
impl crate::serde::Serialize for Affinity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: crate::serde::Serializer {
let mut state = serializer.serialize_struct(
"Affinity",
self.node_affinity.as_ref().map_or(0, |_| 1) +
self.pod_affinity.as_ref().map_or(0, |_| 1) +
self.pod_anti_affinity.as_ref().map_or(0, |_| 1),
)?;
if let Some(value) = &self.node_affinity {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "nodeAffinity", value)?;
}
if let Some(value) = &self.pod_affinity {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "podAffinity", value)?;
}
if let Some(value) = &self.pod_anti_affinity {
crate::serde::ser::SerializeStruct::serialize_field(&mut state, "podAntiAffinity", value)?;
}
crate::serde::ser::SerializeStruct::end(state)
}
}
#[cfg(feature = "schemars")]
impl crate::schemars::JsonSchema for Affinity {
fn schema_name() -> String {
"io.k8s.api.core.v1.Affinity".to_owned()
}
fn json_schema(__gen: &mut crate::schemars::gen::SchemaGenerator) -> crate::schemars::schema::Schema {
crate::schemars::schema::Schema::Object(crate::schemars::schema::SchemaObject {
metadata: Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Affinity is a group of affinity scheduling rules.".to_owned()),
..Default::default()
})),
instance_type: Some(crate::schemars::schema::SingleOrVec::Single(Box::new(crate::schemars::schema::InstanceType::Object))),
object: Some(Box::new(crate::schemars::schema::ObjectValidation {
properties: std::array::IntoIter::new([
(
"nodeAffinity".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::core::v1::NodeAffinity>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Describes node affinity scheduling rules for the pod.".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
(
"podAffinity".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::core::v1::PodAffinity>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Describes pod affinity scheduling rules (e.g. co-locate this pod in the same node, zone, etc. as some other pod(s)).".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
(
"podAntiAffinity".to_owned(),
{
let mut schema_obj = __gen.subschema_for::<crate::api::core::v1::PodAntiAffinity>().into_object();
schema_obj.metadata = Some(Box::new(crate::schemars::schema::Metadata {
description: Some("Describes pod anti-affinity scheduling rules (e.g. avoid putting this pod in the same node, zone, etc. as some other pod(s)).".to_owned()),
..Default::default()
}));
crate::schemars::schema::Schema::Object(schema_obj)
},
),
]).collect(),
..Default::default()
})),
..Default::default()
})
}
}
| expecting |
common.ts | export function sleep(ms : number) {
return new Promise(resolve => setTimeout(resolve, ms)); | } |
|
await_expr.rs | //! Await expression parsing.
//!
//! More information:
//! - [MDN documentation][mdn]
//! - [ECMAScript specification][spec]
//!
//! [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
//! [spec]: https://tc39.es/ecma262/#prod-AwaitExpression
use super::unary::UnaryExpression;
use crate::syntax::{
ast::{node::AwaitExpr, Keyword},
lexer::TokenKind,
parser::{AllowYield, Cursor, ParseError, TokenParser}, | /// Parses an await expression.
///
/// More information:
/// - [MDN documentation][mdn]
/// - [ECMAScript specification][spec]
///
/// [mdn]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
/// [spec]: https://tc39.es/ecma262/#prod-AwaitExpression
#[derive(Debug, Clone, Copy)]
pub(in crate::syntax::parser) struct AwaitExpression {
allow_yield: AllowYield,
}
impl AwaitExpression {
/// Creates a new `AwaitExpression` parser.
pub(in crate::syntax::parser) fn new<Y>(allow_yield: Y) -> Self
where
Y: Into<AllowYield>,
{
Self {
allow_yield: allow_yield.into(),
}
}
}
impl<R> TokenParser<R> for AwaitExpression
where
R: Read,
{
type Output = AwaitExpr;
fn parse(
self,
cursor: &mut Cursor<R>,
interner: &mut Interner,
) -> Result<Self::Output, ParseError> {
cursor.expect(
TokenKind::Keyword(Keyword::Await),
"Await expression parsing",
interner,
)?;
let expr = UnaryExpression::new(self.allow_yield, true).parse(cursor, interner)?;
Ok(expr.into())
}
} | };
use boa_interner::Interner;
use std::io::Read;
|
mod.rs | // Copyright 2020 Dmitry Tantsur <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Support for loading sessions from external input.
#[cfg(any(feature = "native-tls", feature = "rustls"))]
use std::fs;
#[cfg(any(feature = "native-tls", feature = "rustls"))]
use reqwest::Certificate;
use reqwest::Client;
use crate::{Error, ErrorKind};
/// Create an HTTP client with the provided CA certificate.
#[inline]
#[allow(unused_mut)] // mut builder unused with --no-default-features
fn | (cacert: Option<String>) -> Result<Client, Error> {
let mut builder = Client::builder();
#[cfg(any(feature = "native-tls", feature = "rustls"))]
if let Some(cert_path) = cacert {
let cert_content = fs::read(&cert_path).map_err(|e| {
Error::new(
ErrorKind::InvalidConfig,
format!("Cannot open cacert file {}: {}", cert_path, e),
)
})?;
let cert = Certificate::from_pem(&cert_content).map_err(|e| {
Error::new(
ErrorKind::InvalidConfig,
format!("Cannot parse {} as PEM: {}", cert_path, e),
)
})?;
builder = builder.add_root_certificate(cert);
}
#[cfg(not(any(feature = "native-tls", feature = "rustls")))]
if cacert.is_some() {
return Err(Error::new(
ErrorKind::InvalidConfig,
"TLS support is disabled",
));
}
Ok(builder.build().expect("Cannot initialize HTTP backend"))
}
mod cloud;
mod config;
mod env;
pub use cloud::CloudConfig;
| get_client |
delayModule.ts | import {ModuleBase} from "./moduleBase"
/**
* delay module.
* @author fukuroda
*/
class DelayModule extends ModuleBase {
/**
* constructor.
* @param x
* @param y
* @param removable
* @param canvas_context
* @param img
*/
public constructor(x:number, y:number, removable:boolean, img:HTMLImageElement){
super('delay_module', x, y, 1, 1, removable, img);
this.is_delay = true;
}
/**
* evaluate.
*/
public evaluate():void{
this.output_arr[0].value1 = this.input_arr[0].value1 + 1.0e-100; // Denomal cancel
this.output_arr[0].value2 = this.input_arr[0].value2 + 1.0e-100; // Denomal cancel
}
/**
* 定数判定.
* @return
*/
public is_constant():boolean{
// 強制的にstream update扱いとする
return false;
}
/**
* stream更新.
| * @return
*/
public stream_update():ModuleBase[] {
//------------------------
// nextには進まずに止める
//------------------------
return [];
}
/**
* Delayモジュール更新.
* @return
*/
public delay_update():ModuleBase[]{
// Output先のモジュールを更新する
var order:ModuleBase[] = [this];
for ( var output of this.output_arr ) {
// Output & QuickBus
let next_input_arr = output.next_input_arr.concat(output.quick_bus_next_input_arr);
for( var next_input of next_input_arr ){
next_input.stream_updated = true;
order = order.concat(next_input.module.stream_update());
}
}
return order;
}
}
export{DelayModule} | |
zipfile.py | """
Read and write ZIP files.
XXX references to utf-8 need further investigation.
"""
import binascii
import importlib.util
import io
import itertools
import os
import posixpath
import shutil
import stat
import struct
import sys
import threading
import time
import contextlib
try:
import zlib # We may need its compression method
crc32 = zlib.crc32
except ImportError:
zlib = None
crc32 = binascii.crc32
try:
import bz2 # We may need its compression method
except ImportError:
bz2 = None
try:
import lzma # We may need its compression method
except ImportError:
lzma = None
__all__ = ["BadZipFile", "BadZipfile", "error",
"ZIP_STORED", "ZIP_DEFLATED", "ZIP_BZIP2", "ZIP_LZMA",
"is_zipfile", "ZipInfo", "ZipFile", "PyZipFile", "LargeZipFile",
"Path"]
class BadZipFile(Exception):
pass
class LargeZipFile(Exception):
"""
Raised when writing a zipfile, the zipfile requires ZIP64 extensions
and those extensions are disabled.
"""
error = BadZipfile = BadZipFile # Pre-3.2 compatibility names
ZIP64_LIMIT = (1 << 31) - 1
ZIP_FILECOUNT_LIMIT = (1 << 16) - 1
ZIP_MAX_COMMENT = (1 << 16) - 1
# constants for Zip file compression methods
ZIP_STORED = 0
ZIP_DEFLATED = 8
ZIP_BZIP2 = 12
ZIP_LZMA = 14
# Other ZIP compression methods not supported
DEFAULT_VERSION = 20
ZIP64_VERSION = 45
BZIP2_VERSION = 46
LZMA_VERSION = 63
# we recognize (but not necessarily support) all features up to that version
MAX_EXTRACT_VERSION = 63
# Below are some formats and associated data for reading/writing headers using
# the struct module. The names and structures of headers/records are those used
# in the PKWARE description of the ZIP file format:
# http://www.pkware.com/documents/casestudies/APPNOTE.TXT
# (URL valid as of January 2008)
# The "end of central directory" structure, magic number, size, and indices
# (section V.I in the format document)
structEndArchive = b"<4s4H2LH"
stringEndArchive = b"PK\005\006"
sizeEndCentDir = struct.calcsize(structEndArchive)
_ECD_SIGNATURE = 0
_ECD_DISK_NUMBER = 1
_ECD_DISK_START = 2
_ECD_ENTRIES_THIS_DISK = 3
_ECD_ENTRIES_TOTAL = 4
_ECD_SIZE = 5
_ECD_OFFSET = 6
_ECD_COMMENT_SIZE = 7
# These last two indices are not part of the structure as defined in the
# spec, but they are used internally by this module as a convenience
_ECD_COMMENT = 8
_ECD_LOCATION = 9
# The "central directory" structure, magic number, size, and indices
# of entries in the structure (section V.F in the format document)
structCentralDir = "<4s4B4HL2L5H2L"
stringCentralDir = b"PK\001\002"
sizeCentralDir = struct.calcsize(structCentralDir)
# indexes of entries in the central directory structure
_CD_SIGNATURE = 0
_CD_CREATE_VERSION = 1
_CD_CREATE_SYSTEM = 2
_CD_EXTRACT_VERSION = 3
_CD_EXTRACT_SYSTEM = 4
_CD_FLAG_BITS = 5
_CD_COMPRESS_TYPE = 6
_CD_TIME = 7
_CD_DATE = 8
_CD_CRC = 9
_CD_COMPRESSED_SIZE = 10
_CD_UNCOMPRESSED_SIZE = 11
_CD_FILENAME_LENGTH = 12
_CD_EXTRA_FIELD_LENGTH = 13
_CD_COMMENT_LENGTH = 14
_CD_DISK_NUMBER_START = 15
_CD_INTERNAL_FILE_ATTRIBUTES = 16
_CD_EXTERNAL_FILE_ATTRIBUTES = 17
_CD_LOCAL_HEADER_OFFSET = 18
# The "local file header" structure, magic number, size, and indices
# (section V.A in the format document)
structFileHeader = "<4s2B4HL2L2H"
stringFileHeader = b"PK\003\004"
sizeFileHeader = struct.calcsize(structFileHeader)
_FH_SIGNATURE = 0
_FH_EXTRACT_VERSION = 1
_FH_EXTRACT_SYSTEM = 2
_FH_GENERAL_PURPOSE_FLAG_BITS = 3
_FH_COMPRESSION_METHOD = 4
_FH_LAST_MOD_TIME = 5
_FH_LAST_MOD_DATE = 6
_FH_CRC = 7
_FH_COMPRESSED_SIZE = 8
_FH_UNCOMPRESSED_SIZE = 9
_FH_FILENAME_LENGTH = 10
_FH_EXTRA_FIELD_LENGTH = 11
# The "Zip64 end of central directory locator" structure, magic number, and size
structEndArchive64Locator = "<4sLQL"
stringEndArchive64Locator = b"PK\x06\x07"
sizeEndCentDir64Locator = struct.calcsize(structEndArchive64Locator)
# The "Zip64 end of central directory" record, magic number, size, and indices
# (section V.G in the format document)
structEndArchive64 = "<4sQ2H2L4Q"
stringEndArchive64 = b"PK\x06\x06"
sizeEndCentDir64 = struct.calcsize(structEndArchive64)
_CD64_SIGNATURE = 0
_CD64_DIRECTORY_RECSIZE = 1
_CD64_CREATE_VERSION = 2
_CD64_EXTRACT_VERSION = 3
_CD64_DISK_NUMBER = 4
_CD64_DISK_NUMBER_START = 5
_CD64_NUMBER_ENTRIES_THIS_DISK = 6
_CD64_NUMBER_ENTRIES_TOTAL = 7
_CD64_DIRECTORY_SIZE = 8
_CD64_OFFSET_START_CENTDIR = 9
_DD_SIGNATURE = 0x08074b50
_EXTRA_FIELD_STRUCT = struct.Struct('<HH')
def _strip_extra(extra, xids):
# Remove Extra Fields with specified IDs.
unpack = _EXTRA_FIELD_STRUCT.unpack
modified = False
buffer = []
start = i = 0
while i + 4 <= len(extra):
xid, xlen = unpack(extra[i : i + 4])
j = i + 4 + xlen
if xid in xids:
if i != start:
buffer.append(extra[start : i])
start = j
modified = True
i = j
if not modified:
return extra
return b''.join(buffer)
def _check_zipfile(fp):
try:
if _EndRecData(fp):
return True # file has correct magic number
except OSError:
pass
return False
def is_zipfile(filename):
"""Quickly see if a file is a ZIP file by checking the magic number.
The filename argument may be a file or file-like object too.
"""
result = False
try:
if hasattr(filename, "read"):
result = _check_zipfile(fp=filename)
else:
with open(filename, "rb") as fp:
result = _check_zipfile(fp)
except OSError:
pass
return result
def _EndRecData64(fpin, offset, endrec):
"""
Read the ZIP64 end-of-archive records and use that to update endrec
"""
try:
fpin.seek(offset - sizeEndCentDir64Locator, 2)
except OSError:
# If the seek fails, the file is not large enough to contain a ZIP64
# end-of-archive record, so just return the end record we were given.
return endrec
data = fpin.read(sizeEndCentDir64Locator)
if len(data) != sizeEndCentDir64Locator:
return endrec
sig, diskno, reloff, disks = struct.unpack(structEndArchive64Locator, data)
if sig != stringEndArchive64Locator:
return endrec
if diskno != 0 or disks > 1:
raise BadZipFile("zipfiles that span multiple disks are not supported")
# Assume no 'zip64 extensible data'
fpin.seek(offset - sizeEndCentDir64Locator - sizeEndCentDir64, 2)
data = fpin.read(sizeEndCentDir64)
if len(data) != sizeEndCentDir64:
return endrec
sig, sz, create_version, read_version, disk_num, disk_dir, \
dircount, dircount2, dirsize, diroffset = \
struct.unpack(structEndArchive64, data)
if sig != stringEndArchive64:
return endrec
# Update the original endrec using data from the ZIP64 record
endrec[_ECD_SIGNATURE] = sig
endrec[_ECD_DISK_NUMBER] = disk_num
endrec[_ECD_DISK_START] = disk_dir
endrec[_ECD_ENTRIES_THIS_DISK] = dircount
endrec[_ECD_ENTRIES_TOTAL] = dircount2
endrec[_ECD_SIZE] = dirsize
endrec[_ECD_OFFSET] = diroffset
return endrec
def _EndRecData(fpin):
"""Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record."""
# Determine file size
fpin.seek(0, 2)
filesize = fpin.tell()
# Check to see if this is ZIP file with no archive comment (the
# "end of central directory" structure should be the last item in the
# file if this is the case).
try:
fpin.seek(-sizeEndCentDir, 2)
except OSError:
return None
data = fpin.read()
if (len(data) == sizeEndCentDir and
data[0:4] == stringEndArchive and
data[-2:] == b"\000\000"):
# the signature is correct and there's no comment, unpack structure
endrec = struct.unpack(structEndArchive, data)
endrec=list(endrec)
# Append a blank comment and record start offset
endrec.append(b"")
endrec.append(filesize - sizeEndCentDir)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
# Either this is not a ZIP file, or it is a ZIP file with an archive
# comment. Search the end of the file for the "end of central directory"
# record signature. The comment is the last item in the ZIP file and may be
# up to 64K long. It is assumed that the "end of central directory" magic
# number does not appear in the comment.
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
fpin.seek(maxCommentStart, 0)
data = fpin.read()
start = data.rfind(stringEndArchive)
if start >= 0:
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
if len(recData) != sizeEndCentDir:
# Zip file is corrupted.
return None
endrec = list(struct.unpack(structEndArchive, recData))
commentSize = endrec[_ECD_COMMENT_SIZE] #as claimed by the zip file
comment = data[start+sizeEndCentDir:start+sizeEndCentDir+commentSize]
endrec.append(comment)
endrec.append(maxCommentStart + start)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, maxCommentStart + start - filesize,
endrec)
# Unable to find a valid end of central directory structure
return None
class ZipInfo (object):
"""Class with attributes describing each file in the ZIP archive."""
__slots__ = (
'orig_filename',
'filename',
'date_time',
'compress_type',
'_compresslevel',
'comment',
'extra',
'create_system',
'create_version',
'extract_version',
'reserved',
'flag_bits',
'volume',
'internal_attr',
'external_attr',
'header_offset',
'CRC',
'compress_size',
'file_size',
'_raw_time',
)
def __init__(self, filename="NoName", date_time=(1980,1,1,0,0,0)):
self.orig_filename = filename # Original file name in archive
# Terminate the file name at the first null byte. Null bytes in file
# names are used as tricks by viruses in archives.
null_byte = filename.find(chr(0))
if null_byte >= 0:
filename = filename[0:null_byte]
# This is used to ensure paths in generated ZIP files always use
# forward slashes as the directory separator, as required by the
# ZIP format specification.
if os.sep != "/" and os.sep in filename:
filename = filename.replace(os.sep, "/")
self.filename = filename # Normalized file name
self.date_time = date_time # year, month, day, hour, min, sec
if date_time[0] < 1980:
raise ValueError('ZIP does not support timestamps before 1980')
# Standard values:
self.compress_type = ZIP_STORED # Type of compression for the file
self._compresslevel = None # Level for the compressor
self.comment = b"" # Comment for each file
self.extra = b"" # ZIP extra data
if sys.platform == 'win32':
self.create_system = 0 # System which created ZIP archive
else:
# Assume everything else is unix-y
self.create_system = 3 # System which created ZIP archive
self.create_version = DEFAULT_VERSION # Version which created ZIP archive
self.extract_version = DEFAULT_VERSION # Version needed to extract archive
self.reserved = 0 # Must be zero
self.flag_bits = 0 # ZIP flag bits
self.volume = 0 # Volume number of file header
self.internal_attr = 0 # Internal attributes
self.external_attr = 0 # External file attributes
self.compress_size = 0 # Size of the compressed file
self.file_size = 0 # Size of the uncompressed file
# Other attributes are set by class ZipFile:
# header_offset Byte offset to the file header
# CRC CRC-32 of the uncompressed file
def __repr__(self):
result = ['<%s filename=%r' % (self.__class__.__name__, self.filename)]
if self.compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self.compress_type,
self.compress_type))
hi = self.external_attr >> 16
lo = self.external_attr & 0xFFFF
if hi:
result.append(' filemode=%r' % stat.filemode(hi))
if lo:
result.append(' external_attr=%#x' % lo)
isdir = self.is_dir()
if not isdir or self.file_size:
result.append(' file_size=%r' % self.file_size)
if ((not isdir or self.compress_size) and
(self.compress_type != ZIP_STORED or
self.file_size != self.compress_size)):
result.append(' compress_size=%r' % self.compress_size)
result.append('>')
return ''.join(result)
def FileHeader(self, zip64=None):
"""Return the per-file header as a bytes object."""
dt = self.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
if self.flag_bits & 0x08:
# Set these to zero because we write them after the file data
CRC = compress_size = file_size = 0
else:
CRC = self.CRC
compress_size = self.compress_size
file_size = self.file_size
extra = self.extra
min_version = 0
if zip64 is None:
zip64 = file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT
if zip64:
fmt = '<HHQQ'
extra = extra + struct.pack(fmt,
1, struct.calcsize(fmt)-4, file_size, compress_size)
if file_size > ZIP64_LIMIT or compress_size > ZIP64_LIMIT:
if not zip64:
raise LargeZipFile("Filesize would require ZIP64 extensions")
# File is larger than what fits into a 4 byte integer,
# fall back to the ZIP64 extension
file_size = 0xffffffff
compress_size = 0xffffffff
min_version = ZIP64_VERSION
if self.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif self.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
self.extract_version = max(min_version, self.extract_version)
self.create_version = max(min_version, self.create_version)
filename, flag_bits = self._encodeFilenameFlags()
header = struct.pack(structFileHeader, stringFileHeader,
self.extract_version, self.reserved, flag_bits,
self.compress_type, dostime, dosdate, CRC,
compress_size, file_size,
len(filename), len(extra))
return header + filename + extra
def _encodeFilenameFlags(self):
try:
return self.filename.encode('ascii'), self.flag_bits
except UnicodeEncodeError:
return self.filename.encode('utf-8'), self.flag_bits | 0x800
def _decodeExtra(self):
# Try to decode the extra field.
extra = self.extra
unpack = struct.unpack
while len(extra) >= 4:
tp, ln = unpack('<HH', extra[:4])
if ln+4 > len(extra):
raise BadZipFile("Corrupt extra field %04x (size=%d)" % (tp, ln))
if tp == 0x0001:
data = extra[4:ln+4]
# ZIP64 extension (large files and/or large archives)
try:
if self.file_size in (0xFFFF_FFFF_FFFF_FFFF, 0xFFFF_FFFF):
field = "File size"
self.file_size, = unpack('<Q', data[:8])
data = data[8:]
if self.compress_size == 0xFFFF_FFFF:
field = "Compress size"
self.compress_size, = unpack('<Q', data[:8])
data = data[8:]
if self.header_offset == 0xFFFF_FFFF:
field = "Header offset"
self.header_offset, = unpack('<Q', data[:8])
except struct.error:
raise BadZipFile(f"Corrupt zip64 extra field. "
f"{field} not found.") from None
extra = extra[ln+4:]
@classmethod
def from_file(cls, filename, arcname=None, *, strict_timestamps=True):
"""Construct an appropriate ZipInfo for a file on the filesystem.
filename should be the path to a file or directory on the filesystem.
arcname is the name which it will have within the archive (by default,
this will be the same as filename, but without a drive letter and with
leading path separators removed).
"""
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
st = os.stat(filename)
isdir = stat.S_ISDIR(st.st_mode)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
if not strict_timestamps and date_time[0] < 1980:
date_time = (1980, 1, 1, 0, 0, 0)
elif not strict_timestamps and date_time[0] > 2107:
date_time = (2107, 12, 31, 23, 59, 59)
# Create ZipInfo instance to store file information
if arcname is None:
arcname = filename
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
if isdir:
arcname += '/'
zinfo = cls(arcname, date_time)
zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes
if isdir:
zinfo.file_size = 0
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.file_size = st.st_size
return zinfo
def is_dir(self):
"""Return True if this archive member is a directory."""
return self.filename[-1] == '/'
# ZIP encryption uses the CRC32 one-byte primitive for scrambling some
# internal keys. We noticed that a direct implementation is faster than
# relying on binascii.crc32().
_crctable = None
def _gen_crc(crc):
for j in range(8):
if crc & 1:
crc = (crc >> 1) ^ 0xEDB88320
else:
crc >>= 1
return crc
# ZIP supports a password-based form of encryption. Even though known
# plaintext attacks have been found against it, it is still useful
# to be able to get data out of such a file.
#
# Usage:
# zd = _ZipDecrypter(mypwd)
# plain_bytes = zd(cypher_bytes)
def _ZipDecrypter(pwd):
key0 = 305419896
key1 = 591751049
key2 = 878082192
global _crctable
if _crctable is None:
_crctable = list(map(_gen_crc, range(256)))
crctable = _crctable
def crc32(ch, crc):
"""Compute the CRC32 primitive on one byte."""
return (crc >> 8) ^ crctable[(crc ^ ch) & 0xFF]
def update_keys(c):
nonlocal key0, key1, key2
key0 = crc32(c, key0)
key1 = (key1 + (key0 & 0xFF)) & 0xFFFFFFFF
key1 = (key1 * 134775813 + 1) & 0xFFFFFFFF
key2 = crc32(key1 >> 24, key2)
for p in pwd:
update_keys(p)
def decrypter(data):
"""Decrypt a bytes object."""
result = bytearray()
append = result.append
for c in data:
k = key2 | 2
c ^= ((k * (k^1)) >> 8) & 0xFF
update_keys(c)
append(c)
return bytes(result)
return decrypter
class LZMACompressor:
def __init__(self):
self._comp = None
def _init(self):
props = lzma._encode_filter_properties({'id': lzma.FILTER_LZMA1})
self._comp = lzma.LZMACompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1, props)
])
return struct.pack('<BBH', 9, 4, len(props)) + props
def compress(self, data):
if self._comp is None:
return self._init() + self._comp.compress(data)
return self._comp.compress(data)
def flush(self):
if self._comp is None:
return self._init() + self._comp.flush()
return self._comp.flush()
class LZMADecompressor:
def __init__(self):
self._decomp = None
self._unconsumed = b''
self.eof = False
def decompress(self, data):
if self._decomp is None:
self._unconsumed += data
if len(self._unconsumed) <= 4:
return b''
psize, = struct.unpack('<H', self._unconsumed[2:4])
if len(self._unconsumed) <= 4 + psize:
return b''
self._decomp = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[
lzma._decode_filter_properties(lzma.FILTER_LZMA1,
self._unconsumed[4:4 + psize])
])
data = self._unconsumed[4 + psize:]
del self._unconsumed
result = self._decomp.decompress(data)
self.eof = self._decomp.eof
return result
compressor_names = {
0: 'store',
1: 'shrink',
2: 'reduce',
3: 'reduce',
4: 'reduce',
5: 'reduce',
6: 'implode',
7: 'tokenize',
8: 'deflate',
9: 'deflate64',
10: 'implode',
12: 'bzip2',
14: 'lzma',
18: 'terse',
19: 'lz77',
97: 'wavpack',
98: 'ppmd',
}
def _check_compression(compression):
if compression == ZIP_STORED:
pass
elif compression == ZIP_DEFLATED:
if not zlib:
raise RuntimeError(
"Compression requires the (missing) zlib module")
elif compression == ZIP_BZIP2:
if not bz2:
raise RuntimeError(
"Compression requires the (missing) bz2 module")
elif compression == ZIP_LZMA:
if not lzma:
raise RuntimeError(
"Compression requires the (missing) lzma module")
else:
raise NotImplementedError("That compression method is not supported")
def _get_compressor(compress_type, compresslevel=None):
if compress_type == ZIP_DEFLATED:
if compresslevel is not None:
return zlib.compressobj(compresslevel, zlib.DEFLATED, -15)
return zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
elif compress_type == ZIP_BZIP2:
if compresslevel is not None:
return bz2.BZ2Compressor(compresslevel)
return bz2.BZ2Compressor()
# compresslevel is ignored for ZIP_LZMA
elif compress_type == ZIP_LZMA:
return LZMACompressor()
else:
return None
def _get_decompressor(compress_type):
_check_compression(compress_type)
if compress_type == ZIP_STORED:
return None
elif compress_type == ZIP_DEFLATED:
return zlib.decompressobj(-15)
elif compress_type == ZIP_BZIP2:
return bz2.BZ2Decompressor()
elif compress_type == ZIP_LZMA:
return LZMADecompressor()
else:
descr = compressor_names.get(compress_type)
if descr:
raise NotImplementedError("compression type %d (%s)" % (compress_type, descr))
else:
raise NotImplementedError("compression type %d" % (compress_type,))
class _SharedFile:
def __init__(self, file, pos, close, lock, writing):
self._file = file
self._pos = pos
self._close = close
self._lock = lock
self._writing = writing
self.seekable = file.seekable
self.tell = file.tell
def seek(self, offset, whence=0):
with self._lock:
if self._writing():
raise ValueError("Can't reposition in the ZIP file while "
"there is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(offset, whence)
self._pos = self._file.tell()
return self._pos
def read(self, n=-1):
with self._lock:
if self._writing():
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
self._file.seek(self._pos)
data = self._file.read(n)
self._pos = self._file.tell()
return data
def close(self):
if self._file is not None:
fileobj = self._file
self._file = None
self._close(fileobj)
# Provide the tell method for unseekable stream
class _Tellable:
def __init__(self, fp):
self.fp = fp
self.offset = 0
def write(self, data):
n = self.fp.write(data)
self.offset += n
return n
def tell(self):
return self.offset
def flush(self):
self.fp.flush()
def close(self):
self.fp.close()
class ZipExtFile(io.BufferedIOBase):
"""File-like object for reading an archive member.
Is returned by ZipFile.open().
"""
# Max size supported by decompressor.
MAX_N = 1 << 31 - 1
# Read from compressed files in 4k blocks.
MIN_READ_SIZE = 4096
# Chunk size to read during seek
MAX_SEEK_READ = 1 << 24
def __init__(self, fileobj, mode, zipinfo, pwd=None,
close_fileobj=False):
self._fileobj = fileobj
self._pwd = pwd
self._close_fileobj = close_fileobj
self._compress_type = zipinfo.compress_type
self._compress_left = zipinfo.compress_size
self._left = zipinfo.file_size
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
self._readbuffer = b''
self._offset = 0
self.newlines = None
self.mode = mode
self.name = zipinfo.filename
if hasattr(zipinfo, 'CRC'):
self._expected_crc = zipinfo.CRC
self._running_crc = crc32(b'')
else:
self._expected_crc = None
self._seekable = False
try:
if fileobj.seekable():
self._orig_compress_start = fileobj.tell()
self._orig_compress_size = zipinfo.compress_size
self._orig_file_size = zipinfo.file_size
self._orig_start_crc = self._running_crc
self._seekable = True
except AttributeError:
pass
self._decrypter = None
if pwd:
if zipinfo.flag_bits & 0x8:
# compare against the file type from extended local headers
check_byte = (zipinfo._raw_time >> 8) & 0xff
else:
# compare against the CRC otherwise
check_byte = (zipinfo.CRC >> 24) & 0xff
h = self._init_decrypter()
if h != check_byte:
raise RuntimeError("Bad password for file %r" % zipinfo.orig_filename)
def _init_decrypter(self):
self._decrypter = _ZipDecrypter(self._pwd)
# The first 12 bytes in the cypher stream is an encryption header
# used to strengthen the algorithm. The first 11 bytes are
# completely random, while the 12th contains the MSB of the CRC,
# or the MSB of the file time depending on the header type
# and is used to check the correctness of the password.
header = self._fileobj.read(12)
self._compress_left -= 12
return self._decrypter(header)[11]
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if not self.closed:
result.append(' name=%r mode=%r' % (self.name, self.mode))
if self._compress_type != ZIP_STORED:
result.append(' compress_type=%s' %
compressor_names.get(self._compress_type,
self._compress_type))
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def readline(self, limit=-1):
"""Read and return a line from the stream.
If limit is specified, at most limit bytes will be read.
"""
if limit < 0:
# Shortcut common case - newline found in buffer.
i = self._readbuffer.find(b'\n', self._offset) + 1
if i > 0:
line = self._readbuffer[self._offset: i]
self._offset = i
return line
return io.BufferedIOBase.readline(self, limit)
def peek(self, n=1):
"""Returns buffered bytes without advancing the position."""
if n > len(self._readbuffer) - self._offset:
chunk = self.read(n)
if len(chunk) > self._offset:
self._readbuffer = chunk + self._readbuffer[self._offset:]
self._offset = 0
else:
self._offset -= len(chunk)
# Return up to 512 bytes to reduce allocation overhead for tight loops.
return self._readbuffer[self._offset: self._offset + 512]
def readable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return True
def read(self, n=-1):
"""Read and return up to n bytes.
If the argument is omitted, None, or negative, data is read and returned until EOF is reached.
"""
if self.closed:
raise ValueError("read from closed file.")
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
buf += self._read1(self.MAX_N)
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while n > 0 and not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
buf += data
n -= len(data)
return buf
def _update_crc(self, newdata):
# Update the CRC using the given data.
if self._expected_crc is None:
# No need to compute the CRC if we don't have a reference value
return
self._running_crc = crc32(newdata, self._running_crc)
# Check the CRC if we're at the end of the file
if self._eof and self._running_crc != self._expected_crc:
raise BadZipFile("Bad CRC-32 for file %r" % self.name)
def read1(self, n):
"""Read up to n bytes with at most one read() system call."""
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while not self._eof:
data = self._read1(self.MAX_N)
if data:
buf += data
break
return buf
end = n + self._offset
if end < len(self._readbuffer):
buf = self._readbuffer[self._offset:end]
self._offset = end
return buf
n = end - len(self._readbuffer)
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
if n > 0:
while not self._eof:
data = self._read1(n)
if n < len(data):
self._readbuffer = data
self._offset = n
buf += data[:n]
break
if data:
buf += data
break
return buf
def _read1(self, n):
# Read up to n compressed bytes with at most one read() system call,
# decrypt and decompress them.
if self._eof or n <= 0:
return b''
# Read from file.
if self._compress_type == ZIP_DEFLATED:
## Handle unconsumed data.
data = self._decompressor.unconsumed_tail
if n > len(data):
data += self._read2(n - len(data))
else:
data = self._read2(n)
if self._compress_type == ZIP_STORED:
self._eof = self._compress_left <= 0
elif self._compress_type == ZIP_DEFLATED:
n = max(n, self.MIN_READ_SIZE)
data = self._decompressor.decompress(data, n)
self._eof = (self._decompressor.eof or
self._compress_left <= 0 and
not self._decompressor.unconsumed_tail)
if self._eof:
data += self._decompressor.flush()
else:
data = self._decompressor.decompress(data)
self._eof = self._decompressor.eof or self._compress_left <= 0
data = data[:self._left]
self._left -= len(data)
if self._left <= 0:
self._eof = True
self._update_crc(data)
return data
def _read2(self, n):
if self._compress_left <= 0:
return b''
n = max(n, self.MIN_READ_SIZE)
n = min(n, self._compress_left)
data = self._fileobj.read(n)
self._compress_left -= len(data)
if not data:
raise EOFError
if self._decrypter is not None:
data = self._decrypter(data)
return data
def close(self):
try:
if self._close_fileobj:
self._fileobj.close()
finally: | super().close()
def seekable(self):
if self.closed:
raise ValueError("I/O operation on closed file.")
return self._seekable
def seek(self, offset, whence=0):
if self.closed:
raise ValueError("seek on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
curr_pos = self.tell()
if whence == 0: # Seek from start of file
new_pos = offset
elif whence == 1: # Seek from current position
new_pos = curr_pos + offset
elif whence == 2: # Seek from EOF
new_pos = self._orig_file_size + offset
else:
raise ValueError("whence must be os.SEEK_SET (0), "
"os.SEEK_CUR (1), or os.SEEK_END (2)")
if new_pos > self._orig_file_size:
new_pos = self._orig_file_size
if new_pos < 0:
new_pos = 0
read_offset = new_pos - curr_pos
buff_offset = read_offset + self._offset
if buff_offset >= 0 and buff_offset < len(self._readbuffer):
# Just move the _offset index if the new position is in the _readbuffer
self._offset = buff_offset
read_offset = 0
elif read_offset < 0:
# Position is before the current position. Reset the ZipExtFile
self._fileobj.seek(self._orig_compress_start)
self._running_crc = self._orig_start_crc
self._compress_left = self._orig_compress_size
self._left = self._orig_file_size
self._readbuffer = b''
self._offset = 0
self._decompressor = _get_decompressor(self._compress_type)
self._eof = False
read_offset = new_pos
if self._decrypter is not None:
self._init_decrypter()
while read_offset > 0:
read_len = min(self.MAX_SEEK_READ, read_offset)
self.read(read_len)
read_offset -= read_len
return self.tell()
def tell(self):
if self.closed:
raise ValueError("tell on closed file.")
if not self._seekable:
raise io.UnsupportedOperation("underlying stream is not seekable")
filepos = self._orig_file_size - self._left - len(self._readbuffer) + self._offset
return filepos
class _ZipWriteFile(io.BufferedIOBase):
def __init__(self, zf, zinfo, zip64):
self._zinfo = zinfo
self._zip64 = zip64
self._zipfile = zf
self._compressor = _get_compressor(zinfo.compress_type,
zinfo._compresslevel)
self._file_size = 0
self._compress_size = 0
self._crc = 0
@property
def _fileobj(self):
return self._zipfile.fp
def writable(self):
return True
def write(self, data):
if self.closed:
raise ValueError('I/O operation on closed file.')
# Accept any data that supports the buffer protocol
if isinstance(data, (bytes, bytearray)):
nbytes = len(data)
else:
data = memoryview(data)
nbytes = data.nbytes
self._file_size += nbytes
self._crc = crc32(data, self._crc)
if self._compressor:
data = self._compressor.compress(data)
self._compress_size += len(data)
self._fileobj.write(data)
return nbytes
def close(self):
if self.closed:
return
try:
super().close()
# Flush any data from the compressor, and update header info
if self._compressor:
buf = self._compressor.flush()
self._compress_size += len(buf)
self._fileobj.write(buf)
self._zinfo.compress_size = self._compress_size
else:
self._zinfo.compress_size = self._file_size
self._zinfo.CRC = self._crc
self._zinfo.file_size = self._file_size
# Write updated header info
if self._zinfo.flag_bits & 0x08:
# Write CRC and file sizes after the file data
fmt = '<LLQQ' if self._zip64 else '<LLLL'
self._fileobj.write(struct.pack(fmt, _DD_SIGNATURE, self._zinfo.CRC,
self._zinfo.compress_size, self._zinfo.file_size))
self._zipfile.start_dir = self._fileobj.tell()
else:
if not self._zip64:
if self._file_size > ZIP64_LIMIT:
raise RuntimeError(
'File size unexpectedly exceeded ZIP64 limit')
if self._compress_size > ZIP64_LIMIT:
raise RuntimeError(
'Compressed size unexpectedly exceeded ZIP64 limit')
# Seek backwards and write file header (which will now include
# correct CRC and file sizes)
# Preserve current position in file
self._zipfile.start_dir = self._fileobj.tell()
self._fileobj.seek(self._zinfo.header_offset)
self._fileobj.write(self._zinfo.FileHeader(self._zip64))
self._fileobj.seek(self._zipfile.start_dir)
# Successfully written: Add file to our caches
self._zipfile.filelist.append(self._zinfo)
self._zipfile.NameToInfo[self._zinfo.filename] = self._zinfo
finally:
self._zipfile._writing = False
class ZipFile:
""" Class with methods to open, read, write, close, list zip files.
z = ZipFile(file, mode="r", compression=ZIP_STORED, allowZip64=True,
compresslevel=None)
file: Either the path to the file, or a file-like object.
If it is a path, the file will be opened and closed by ZipFile.
mode: The mode can be either read 'r', write 'w', exclusive create 'x',
or append 'a'.
compression: ZIP_STORED (no compression), ZIP_DEFLATED (requires zlib),
ZIP_BZIP2 (requires bz2) or ZIP_LZMA (requires lzma).
allowZip64: if True ZipFile will create files with ZIP64 extensions when
needed, otherwise it will raise an exception when this would
be necessary.
compresslevel: None (default for the given compression type) or an integer
specifying the level to pass to the compressor.
When using ZIP_STORED or ZIP_LZMA this keyword has no effect.
When using ZIP_DEFLATED integers 0 through 9 are accepted.
When using ZIP_BZIP2 integers 1 through 9 are accepted.
"""
fp = None # Set here since __del__ checks it
_windows_illegal_name_trans_table = None
def __init__(self, file, mode="r", compression=ZIP_STORED, allowZip64=True,
compresslevel=None, *, strict_timestamps=True):
"""Open the ZIP file with mode read 'r', write 'w', exclusive create 'x',
or append 'a'."""
if mode not in ('r', 'w', 'x', 'a'):
raise ValueError("ZipFile requires mode 'r', 'w', 'x', or 'a'")
_check_compression(compression)
self._allowZip64 = allowZip64
self._didModify = False
self.debug = 0 # Level of printing: 0 through 3
self.NameToInfo = {} # Find file info given name
self.filelist = [] # List of ZipInfo instances for archive
self.compression = compression # Method of compression
self.compresslevel = compresslevel
self.mode = mode
self.pwd = None
self._comment = b''
self._strict_timestamps = strict_timestamps
# Check if we were passed a file-like object
if isinstance(file, os.PathLike):
file = os.fspath(file)
if isinstance(file, str):
# No, it's a filename
self._filePassed = 0
self.filename = file
modeDict = {'r' : 'rb', 'w': 'w+b', 'x': 'x+b', 'a' : 'r+b',
'r+b': 'w+b', 'w+b': 'wb', 'x+b': 'xb'}
filemode = modeDict[mode]
while True:
try:
self.fp = io.open(file, filemode)
except OSError:
if filemode in modeDict:
filemode = modeDict[filemode]
continue
raise
break
else:
self._filePassed = 1
self.fp = file
self.filename = getattr(file, 'name', None)
self._fileRefCnt = 1
self._lock = threading.RLock()
self._seekable = True
self._writing = False
try:
if mode == 'r':
self._RealGetContents()
elif mode in ('w', 'x'):
# set the modified flag so central directory gets written
# even if no files are added to the archive
self._didModify = True
try:
self.start_dir = self.fp.tell()
except (AttributeError, OSError):
self.fp = _Tellable(self.fp)
self.start_dir = 0
self._seekable = False
else:
# Some file-like objects can provide tell() but not seek()
try:
self.fp.seek(self.start_dir)
except (AttributeError, OSError):
self._seekable = False
elif mode == 'a':
try:
# See if file is a zip file
self._RealGetContents()
# seek to start of directory and overwrite
self.fp.seek(self.start_dir)
except BadZipFile:
# file is not a zip file, just append
self.fp.seek(0, 2)
# set the modified flag so central directory gets written
# even if no files are added to the archive
self._didModify = True
self.start_dir = self.fp.tell()
else:
raise ValueError("Mode must be 'r', 'w', 'x', or 'a'")
except:
fp = self.fp
self.fp = None
self._fpclose(fp)
raise
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __repr__(self):
result = ['<%s.%s' % (self.__class__.__module__,
self.__class__.__qualname__)]
if self.fp is not None:
if self._filePassed:
result.append(' file=%r' % self.fp)
elif self.filename is not None:
result.append(' filename=%r' % self.filename)
result.append(' mode=%r' % self.mode)
else:
result.append(' [closed]')
result.append('>')
return ''.join(result)
def _RealGetContents(self):
"""Read in the table of contents for the ZIP file."""
fp = self.fp
try:
endrec = _EndRecData(fp)
except OSError:
raise BadZipFile("File is not a zip file")
if not endrec:
raise BadZipFile("File is not a zip file")
if self.debug > 1:
print(endrec)
size_cd = endrec[_ECD_SIZE] # bytes in central directory
offset_cd = endrec[_ECD_OFFSET] # offset of central directory
self._comment = endrec[_ECD_COMMENT] # archive comment
# "concat" is zero, unless zip was concatenated to another file
concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
if endrec[_ECD_SIGNATURE] == stringEndArchive64:
# If Zip64 extension structures are present, account for them
concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
if self.debug > 2:
inferred = concat + offset_cd
print("given, inferred, offset", offset_cd, inferred, concat)
# self.start_dir: Position of start of central directory
self.start_dir = offset_cd + concat
fp.seek(self.start_dir, 0)
data = fp.read(size_cd)
fp = io.BytesIO(data)
total = 0
while total < size_cd:
centdir = fp.read(sizeCentralDir)
if len(centdir) != sizeCentralDir:
raise BadZipFile("Truncated central directory")
centdir = struct.unpack(structCentralDir, centdir)
if centdir[_CD_SIGNATURE] != stringCentralDir:
raise BadZipFile("Bad magic number for central directory")
if self.debug > 2:
print(centdir)
filename = fp.read(centdir[_CD_FILENAME_LENGTH])
flags = centdir[5]
if flags & 0x800:
# UTF-8 file names extension
filename = filename.decode('utf-8')
else:
# Historical ZIP filename encoding
filename = filename.decode('cp437')
# Create ZipInfo instance to store file information
x = ZipInfo(filename)
x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
(x.create_version, x.create_system, x.extract_version, x.reserved,
x.flag_bits, x.compress_type, t, d,
x.CRC, x.compress_size, x.file_size) = centdir[1:12]
if x.extract_version > MAX_EXTRACT_VERSION:
raise NotImplementedError("zip file version %.1f" %
(x.extract_version / 10))
x.volume, x.internal_attr, x.external_attr = centdir[15:18]
# Convert date/time code to (year, month, day, hour, min, sec)
x._raw_time = t
x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F,
t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
x._decodeExtra()
x.header_offset = x.header_offset + concat
self.filelist.append(x)
self.NameToInfo[x.filename] = x
# update total bytes read from central directory
total = (total + sizeCentralDir + centdir[_CD_FILENAME_LENGTH]
+ centdir[_CD_EXTRA_FIELD_LENGTH]
+ centdir[_CD_COMMENT_LENGTH])
if self.debug > 2:
print("total", total)
def namelist(self):
"""Return a list of file names in the archive."""
return [data.filename for data in self.filelist]
def infolist(self):
"""Return a list of class ZipInfo instances for files in the
archive."""
return self.filelist
def printdir(self, file=None):
"""Print a table of contents for the zip file."""
print("%-46s %19s %12s" % ("File Name", "Modified ", "Size"),
file=file)
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print("%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size),
file=file)
def testzip(self):
"""Read all the files and check the CRC."""
chunk_size = 2 ** 20
for zinfo in self.filelist:
try:
# Read by chunks, to avoid an OverflowError or a
# MemoryError with very large embedded files.
with self.open(zinfo.filename, "r") as f:
while f.read(chunk_size): # Check CRC-32
pass
except BadZipFile:
return zinfo.filename
def getinfo(self, name):
"""Return the instance of ZipInfo given 'name'."""
info = self.NameToInfo.get(name)
if info is None:
raise KeyError(
'There is no item named %r in the archive' % name)
return info
def setpassword(self, pwd):
"""Set default password for encrypted files."""
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd:
self.pwd = pwd
else:
self.pwd = None
@property
def comment(self):
"""The comment text associated with the ZIP file."""
return self._comment
@comment.setter
def comment(self, comment):
if not isinstance(comment, bytes):
raise TypeError("comment: expected bytes, got %s" % type(comment).__name__)
# check for valid comment length
if len(comment) > ZIP_MAX_COMMENT:
import warnings
warnings.warn('Archive comment is too long; truncating to %d bytes'
% ZIP_MAX_COMMENT, stacklevel=2)
comment = comment[:ZIP_MAX_COMMENT]
self._comment = comment
self._didModify = True
def read(self, name, pwd=None):
"""Return file bytes for name."""
with self.open(name, "r", pwd) as fp:
return fp.read()
def open(self, name, mode="r", pwd=None, *, force_zip64=False):
"""Return file-like object for 'name'.
name is a string for the file name within the ZIP file, or a ZipInfo
object.
mode should be 'r' to read a file already in the ZIP file, or 'w' to
write to a file newly added to the archive.
pwd is the password to decrypt files (only used for reading).
When writing, if the file size is not known in advance but may exceed
2 GiB, pass force_zip64 to use the ZIP64 format, which can handle large
files. If the size is known in advance, it is best to pass a ZipInfo
instance for name, with zinfo.file_size set.
"""
if mode not in {"r", "w"}:
raise ValueError('open() requires mode "r" or "w"')
if pwd and not isinstance(pwd, bytes):
raise TypeError("pwd: expected bytes, got %s" % type(pwd).__name__)
if pwd and (mode == "w"):
raise ValueError("pwd is only supported for reading files")
if not self.fp:
raise ValueError(
"Attempt to use ZIP archive that was already closed")
# Make sure we have an info object
if isinstance(name, ZipInfo):
# 'name' is already an info object
zinfo = name
elif mode == 'w':
zinfo = ZipInfo(name)
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
else:
# Get info object for name
zinfo = self.getinfo(name)
if mode == 'w':
return self._open_to_write(zinfo, force_zip64=force_zip64)
if self._writing:
raise ValueError("Can't read from the ZIP file while there "
"is an open writing handle on it. "
"Close the writing handle before trying to read.")
# Open for reading:
self._fileRefCnt += 1
zef_file = _SharedFile(self.fp, zinfo.header_offset,
self._fpclose, self._lock, lambda: self._writing)
try:
# Skip the file header:
fheader = zef_file.read(sizeFileHeader)
if len(fheader) != sizeFileHeader:
raise BadZipFile("Truncated file header")
fheader = struct.unpack(structFileHeader, fheader)
if fheader[_FH_SIGNATURE] != stringFileHeader:
raise BadZipFile("Bad magic number for file header")
fname = zef_file.read(fheader[_FH_FILENAME_LENGTH])
if fheader[_FH_EXTRA_FIELD_LENGTH]:
zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
if zinfo.flag_bits & 0x20:
# Zip 2.7: compressed patched data
raise NotImplementedError("compressed patched data (flag bit 5)")
if zinfo.flag_bits & 0x40:
# strong encryption
raise NotImplementedError("strong encryption (flag bit 6)")
if fheader[_FH_GENERAL_PURPOSE_FLAG_BITS] & 0x800:
# UTF-8 filename
fname_str = fname.decode("utf-8")
else:
fname_str = fname.decode("cp437")
if fname_str != zinfo.orig_filename:
raise BadZipFile(
'File name in directory %r and header %r differ.'
% (zinfo.orig_filename, fname))
# check for encrypted flag & handle password
is_encrypted = zinfo.flag_bits & 0x1
if is_encrypted:
if not pwd:
pwd = self.pwd
if not pwd:
raise RuntimeError("File %r is encrypted, password "
"required for extraction" % name)
else:
pwd = None
return ZipExtFile(zef_file, mode, zinfo, pwd, True)
except:
zef_file.close()
raise
def _open_to_write(self, zinfo, force_zip64=False):
if force_zip64 and not self._allowZip64:
raise ValueError(
"force_zip64 is True, but allowZip64 was False when opening "
"the ZIP file."
)
if self._writing:
raise ValueError("Can't write to the ZIP file while there is "
"another write handle open on it. "
"Close the first handle before opening another.")
# Size and CRC are overwritten with correct data after processing the file
zinfo.compress_size = 0
zinfo.CRC = 0
zinfo.flag_bits = 0x00
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
if not self._seekable:
zinfo.flag_bits |= 0x08
if not zinfo.external_attr:
zinfo.external_attr = 0o600 << 16 # permissions: ?rw-------
# Compressed size can be larger than uncompressed size
zip64 = self._allowZip64 and \
(force_zip64 or zinfo.file_size * 1.05 > ZIP64_LIMIT)
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell()
self._writecheck(zinfo)
self._didModify = True
self.fp.write(zinfo.FileHeader(zip64))
self._writing = True
return _ZipWriteFile(self, zinfo, zip64)
def extract(self, member, path=None, pwd=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a ZipInfo object. You can
specify a different directory using `path'.
"""
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
return self._extract_member(member, path, pwd)
def extractall(self, path=None, members=None, pwd=None):
"""Extract all members from the archive to the current working
directory. `path' specifies a different directory to extract to.
`members' is optional and must be a subset of the list returned
by namelist().
"""
if members is None:
members = self.namelist()
if path is None:
path = os.getcwd()
else:
path = os.fspath(path)
for zipinfo in members:
self._extract_member(zipinfo, path, pwd)
@classmethod
def _sanitize_windows_name(cls, arcname, pathsep):
"""Replace bad characters and remove trailing dots from parts."""
table = cls._windows_illegal_name_trans_table
if not table:
illegal = ':<>|"?*'
table = str.maketrans(illegal, '_' * len(illegal))
cls._windows_illegal_name_trans_table = table
arcname = arcname.translate(table)
# remove trailing dots
arcname = (x.rstrip('.') for x in arcname.split(pathsep))
# rejoin, removing empty parts.
arcname = pathsep.join(x for x in arcname if x)
return arcname
def _extract_member(self, member, targetpath, pwd):
"""Extract the ZipInfo object 'member' to a physical
file on the path targetpath.
"""
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
# build the destination pathname, replacing
# forward slashes to platform specific separators.
arcname = member.filename.replace('/', os.path.sep)
if os.path.altsep:
arcname = arcname.replace(os.path.altsep, os.path.sep)
# interpret absolute pathname as relative, remove drive letter or
# UNC path, redundant separators, "." and ".." components.
arcname = os.path.splitdrive(arcname)[1]
invalid_path_parts = ('', os.path.curdir, os.path.pardir)
arcname = os.path.sep.join(x for x in arcname.split(os.path.sep)
if x not in invalid_path_parts)
if os.path.sep == '\\':
# filter illegal characters on Windows
arcname = self._sanitize_windows_name(arcname, os.path.sep)
targetpath = os.path.join(targetpath, arcname)
targetpath = os.path.normpath(targetpath)
# Create all upper directories if necessary.
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.is_dir():
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
with self.open(member, pwd=pwd) as source, \
open(targetpath, "wb") as target:
shutil.copyfileobj(source, target)
return targetpath
def _writecheck(self, zinfo):
"""Check for errors before writing a file to the archive."""
if zinfo.filename in self.NameToInfo:
import warnings
warnings.warn('Duplicate name: %r' % zinfo.filename, stacklevel=3)
if self.mode not in ('w', 'x', 'a'):
raise ValueError("write() requires mode 'w', 'x', or 'a'")
if not self.fp:
raise ValueError(
"Attempt to write ZIP archive that was already closed")
_check_compression(zinfo.compress_type)
if not self._allowZip64:
requires_zip64 = None
if len(self.filelist) >= ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif zinfo.file_size > ZIP64_LIMIT:
requires_zip64 = "Filesize"
elif zinfo.header_offset > ZIP64_LIMIT:
requires_zip64 = "Zipfile size"
if requires_zip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
def write(self, filename, arcname=None,
compress_type=None, compresslevel=None):
"""Put the bytes from filename into the archive under the name
arcname."""
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists"
)
zinfo = ZipInfo.from_file(filename, arcname,
strict_timestamps=self._strict_timestamps)
if zinfo.is_dir():
zinfo.compress_size = 0
zinfo.CRC = 0
else:
if compress_type is not None:
zinfo.compress_type = compress_type
else:
zinfo.compress_type = self.compression
if compresslevel is not None:
zinfo._compresslevel = compresslevel
else:
zinfo._compresslevel = self.compresslevel
if zinfo.is_dir():
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
zinfo.header_offset = self.fp.tell() # Start of header bytes
if zinfo.compress_type == ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
self._writecheck(zinfo)
self._didModify = True
self.filelist.append(zinfo)
self.NameToInfo[zinfo.filename] = zinfo
self.fp.write(zinfo.FileHeader(False))
self.start_dir = self.fp.tell()
else:
with open(filename, "rb") as src, self.open(zinfo, 'w') as dest:
shutil.copyfileobj(src, dest, 1024*8)
def writestr(self, zinfo_or_arcname, data,
compress_type=None, compresslevel=None):
"""Write a file into the archive. The contents is 'data', which
may be either a 'str' or a 'bytes' instance; if it is a 'str',
it is encoded as UTF-8 first.
'zinfo_or_arcname' is either a ZipInfo instance or
the name of the file in the archive."""
if isinstance(data, str):
data = data.encode("utf-8")
if not isinstance(zinfo_or_arcname, ZipInfo):
zinfo = ZipInfo(filename=zinfo_or_arcname,
date_time=time.localtime(time.time())[:6])
zinfo.compress_type = self.compression
zinfo._compresslevel = self.compresslevel
if zinfo.filename[-1] == '/':
zinfo.external_attr = 0o40775 << 16 # drwxrwxr-x
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.external_attr = 0o600 << 16 # ?rw-------
else:
zinfo = zinfo_or_arcname
if not self.fp:
raise ValueError(
"Attempt to write to ZIP archive that was already closed")
if self._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists."
)
if compress_type is not None:
zinfo.compress_type = compress_type
if compresslevel is not None:
zinfo._compresslevel = compresslevel
zinfo.file_size = len(data) # Uncompressed size
with self._lock:
with self.open(zinfo, mode='w') as dest:
dest.write(data)
def __del__(self):
"""Call the "close()" method in case the user forgot."""
self.close()
def close(self):
"""Close the file, and for mode 'w', 'x' and 'a' write the ending
records."""
if self.fp is None:
return
if self._writing:
raise ValueError("Can't close the ZIP file while there is "
"an open writing handle on it. "
"Close the writing handle before closing the zip.")
try:
if self.mode in ('w', 'x', 'a') and self._didModify: # write ending records
with self._lock:
if self._seekable:
self.fp.seek(self.start_dir)
self._write_end_record()
finally:
fp = self.fp
self.fp = None
self._fpclose(fp)
def _write_end_record(self):
for zinfo in self.filelist: # write central directory
dt = zinfo.date_time
dosdate = (dt[0] - 1980) << 9 | dt[1] << 5 | dt[2]
dostime = dt[3] << 11 | dt[4] << 5 | (dt[5] // 2)
extra = []
if zinfo.file_size > ZIP64_LIMIT \
or zinfo.compress_size > ZIP64_LIMIT:
extra.append(zinfo.file_size)
extra.append(zinfo.compress_size)
file_size = 0xffffffff
compress_size = 0xffffffff
else:
file_size = zinfo.file_size
compress_size = zinfo.compress_size
if zinfo.header_offset > ZIP64_LIMIT:
extra.append(zinfo.header_offset)
header_offset = 0xffffffff
else:
header_offset = zinfo.header_offset
extra_data = zinfo.extra
min_version = 0
if extra:
# Append a ZIP64 field to the extra's
extra_data = _strip_extra(extra_data, (1,))
extra_data = struct.pack(
'<HH' + 'Q'*len(extra),
1, 8*len(extra), *extra) + extra_data
min_version = ZIP64_VERSION
if zinfo.compress_type == ZIP_BZIP2:
min_version = max(BZIP2_VERSION, min_version)
elif zinfo.compress_type == ZIP_LZMA:
min_version = max(LZMA_VERSION, min_version)
extract_version = max(min_version, zinfo.extract_version)
create_version = max(min_version, zinfo.create_version)
filename, flag_bits = zinfo._encodeFilenameFlags()
centdir = struct.pack(structCentralDir,
stringCentralDir, create_version,
zinfo.create_system, extract_version, zinfo.reserved,
flag_bits, zinfo.compress_type, dostime, dosdate,
zinfo.CRC, compress_size, file_size,
len(filename), len(extra_data), len(zinfo.comment),
0, zinfo.internal_attr, zinfo.external_attr,
header_offset)
self.fp.write(centdir)
self.fp.write(filename)
self.fp.write(extra_data)
self.fp.write(zinfo.comment)
pos2 = self.fp.tell()
# Write end-of-zip-archive record
centDirCount = len(self.filelist)
centDirSize = pos2 - self.start_dir
centDirOffset = self.start_dir
requires_zip64 = None
if centDirCount > ZIP_FILECOUNT_LIMIT:
requires_zip64 = "Files count"
elif centDirOffset > ZIP64_LIMIT:
requires_zip64 = "Central directory offset"
elif centDirSize > ZIP64_LIMIT:
requires_zip64 = "Central directory size"
if requires_zip64:
# Need to write the ZIP64 end-of-archive records
if not self._allowZip64:
raise LargeZipFile(requires_zip64 +
" would require ZIP64 extensions")
zip64endrec = struct.pack(
structEndArchive64, stringEndArchive64,
44, 45, 45, 0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset)
self.fp.write(zip64endrec)
zip64locrec = struct.pack(
structEndArchive64Locator,
stringEndArchive64Locator, 0, pos2, 1)
self.fp.write(zip64locrec)
centDirCount = min(centDirCount, 0xFFFF)
centDirSize = min(centDirSize, 0xFFFFFFFF)
centDirOffset = min(centDirOffset, 0xFFFFFFFF)
endrec = struct.pack(structEndArchive, stringEndArchive,
0, 0, centDirCount, centDirCount,
centDirSize, centDirOffset, len(self._comment))
self.fp.write(endrec)
self.fp.write(self._comment)
if self.mode == "a":
self.fp.truncate()
self.fp.flush()
def _fpclose(self, fp):
assert self._fileRefCnt > 0
self._fileRefCnt -= 1
if not self._fileRefCnt and not self._filePassed:
fp.close()
class PyZipFile(ZipFile):
"""Class to create ZIP archives with Python library files and packages."""
def __init__(self, file, mode="r", compression=ZIP_STORED,
allowZip64=True, optimize=-1):
ZipFile.__init__(self, file, mode=mode, compression=compression,
allowZip64=allowZip64)
self._optimize = optimize
def writepy(self, pathname, basename="", filterfunc=None):
"""Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive. If pathname is a plain
directory, listdir *.py and enter all modules. Else, pathname
must be a Python *.py file and the module will be put into the
archive. Added modules are always module.pyc.
This method will compile the module.py into module.pyc if
necessary.
If filterfunc(pathname) is given, it is called with every argument.
When it is False, the file or directory is skipped.
"""
pathname = os.fspath(pathname)
if filterfunc and not filterfunc(pathname):
if self.debug:
label = 'path' if os.path.isdir(pathname) else 'file'
print('%s %r skipped by filterfunc' % (label, pathname))
return
dir, name = os.path.split(pathname)
if os.path.isdir(pathname):
initname = os.path.join(pathname, "__init__.py")
if os.path.isfile(initname):
# This is a package directory, add it
if basename:
basename = "%s/%s" % (basename, name)
else:
basename = name
if self.debug:
print("Adding package in", pathname, "as", basename)
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
dirlist = sorted(os.listdir(pathname))
dirlist.remove("__init__.py")
# Add all *.py files and package subdirectories
for filename in dirlist:
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, "__init__.py")):
# This is a package directory, add it
self.writepy(path, basename,
filterfunc=filterfunc) # Recursive call
elif ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
print("Adding files from directory", pathname)
for filename in sorted(os.listdir(pathname)):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if ext == ".py":
if filterfunc and not filterfunc(path):
if self.debug:
print('file %r skipped by filterfunc' % path)
continue
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print("Adding", arcname)
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError(
'Files added with writepy() must end with ".py"')
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print("Adding file", arcname)
self.write(fname, arcname)
def _get_codename(self, pathname, basename):
"""Return (filename, archivename) for the path.
Given a module name path, return the correct file path and
archive name, compiling if necessary. For example, given
/python/lib/string, return (/python/lib/string.pyc, string).
"""
def _compile(file, optimize=-1):
import py_compile
if self.debug:
print("Compiling", file)
try:
py_compile.compile(file, doraise=True, optimize=optimize)
except py_compile.PyCompileError as err:
print(err.msg)
return False
return True
file_py = pathname + ".py"
file_pyc = pathname + ".pyc"
pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='')
pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1)
pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2)
if self._optimize == -1:
# legacy mode: use whatever file is present
if (os.path.isfile(file_pyc) and
os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
# Use .pyc file.
arcname = fname = file_pyc
elif (os.path.isfile(pycache_opt0) and
os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt0
arcname = file_pyc
elif (os.path.isfile(pycache_opt1) and
os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt1
arcname = file_pyc
elif (os.path.isfile(pycache_opt2) and
os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime):
# Use the __pycache__/*.pyc file, but write it to the legacy pyc
# file name in the archive.
fname = pycache_opt2
arcname = file_pyc
else:
# Compile py into PEP 3147 pyc file.
if _compile(file_py):
if sys.flags.optimize == 0:
fname = pycache_opt0
elif sys.flags.optimize == 1:
fname = pycache_opt1
else:
fname = pycache_opt2
arcname = file_pyc
else:
fname = arcname = file_py
else:
# new mode: use given optimization level
if self._optimize == 0:
fname = pycache_opt0
arcname = file_pyc
else:
arcname = file_pyc
if self._optimize == 1:
fname = pycache_opt1
elif self._optimize == 2:
fname = pycache_opt2
else:
msg = "invalid value for 'optimize': {!r}".format(self._optimize)
raise ValueError(msg)
if not (os.path.isfile(fname) and
os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
if not _compile(file_py, optimize=self._optimize):
fname = arcname = file_py
archivename = os.path.split(arcname)[1]
if basename:
archivename = "%s/%s" % (basename, archivename)
return (fname, archivename)
def _parents(path):
"""
Given a path with elements separated by
posixpath.sep, generate all parents of that path.
>>> list(_parents('b/d'))
['b']
>>> list(_parents('/b/d/'))
['/b']
>>> list(_parents('b/d/f/'))
['b/d', 'b']
>>> list(_parents('b'))
[]
>>> list(_parents(''))
[]
"""
return itertools.islice(_ancestry(path), 1, None)
def _ancestry(path):
"""
Given a path with elements separated by
posixpath.sep, generate all elements of that path
>>> list(_ancestry('b/d'))
['b/d', 'b']
>>> list(_ancestry('/b/d/'))
['/b/d', '/b']
>>> list(_ancestry('b/d/f/'))
['b/d/f', 'b/d', 'b']
>>> list(_ancestry('b'))
['b']
>>> list(_ancestry(''))
[]
"""
path = path.rstrip(posixpath.sep)
while path and path != posixpath.sep:
yield path
path, tail = posixpath.split(path)
_dedupe = dict.fromkeys
"""Deduplicate an iterable in original order"""
def _difference(minuend, subtrahend):
"""
Return items in minuend not in subtrahend, retaining order
with O(1) lookup.
"""
return itertools.filterfalse(set(subtrahend).__contains__, minuend)
class CompleteDirs(ZipFile):
"""
A ZipFile subclass that ensures that implied directories
are always included in the namelist.
"""
@staticmethod
def _implied_dirs(names):
parents = itertools.chain.from_iterable(map(_parents, names))
as_dirs = (p + posixpath.sep for p in parents)
return _dedupe(_difference(as_dirs, names))
def namelist(self):
names = super(CompleteDirs, self).namelist()
return names + list(self._implied_dirs(names))
def _name_set(self):
return set(self.namelist())
def resolve_dir(self, name):
"""
If the name represents a directory, return that name
as a directory (with the trailing slash).
"""
names = self._name_set()
dirname = name + '/'
dir_match = name not in names and dirname in names
return dirname if dir_match else name
@classmethod
def make(cls, source):
"""
Given a source (filename or zipfile), return an
appropriate CompleteDirs subclass.
"""
if isinstance(source, CompleteDirs):
return source
if not isinstance(source, ZipFile):
return cls(source)
# Only allow for FastPath when supplied zipfile is read-only
if 'r' not in source.mode:
cls = CompleteDirs
res = cls.__new__(cls)
vars(res).update(vars(source))
return res
class FastLookup(CompleteDirs):
"""
ZipFile subclass to ensure implicit
dirs exist and are resolved rapidly.
"""
def namelist(self):
with contextlib.suppress(AttributeError):
return self.__names
self.__names = super(FastLookup, self).namelist()
return self.__names
def _name_set(self):
with contextlib.suppress(AttributeError):
return self.__lookup
self.__lookup = super(FastLookup, self)._name_set()
return self.__lookup
class Path:
"""
A pathlib-compatible interface for zip files.
Consider a zip file with this structure::
.
├── a.txt
└── b
├── c.txt
└── d
└── e.txt
>>> data = io.BytesIO()
>>> zf = ZipFile(data, 'w')
>>> zf.writestr('a.txt', 'content of a')
>>> zf.writestr('b/c.txt', 'content of c')
>>> zf.writestr('b/d/e.txt', 'content of e')
>>> zf.filename = 'abcde.zip'
Path accepts the zipfile object itself or a filename
>>> root = Path(zf)
From there, several path operations are available.
Directory iteration (including the zip file itself):
>>> a, b = root.iterdir()
>>> a
Path('abcde.zip', 'a.txt')
>>> b
Path('abcde.zip', 'b/')
name property:
>>> b.name
'b'
join with divide operator:
>>> c = b / 'c.txt'
>>> c
Path('abcde.zip', 'b/c.txt')
>>> c.name
'c.txt'
Read text:
>>> c.read_text()
'content of c'
existence:
>>> c.exists()
True
>>> (b / 'missing.txt').exists()
False
Coercion to string:
>>> str(c)
'abcde.zip/b/c.txt'
"""
__repr = "{self.__class__.__name__}({self.root.filename!r}, {self.at!r})"
def __init__(self, root, at=""):
self.root = FastLookup.make(root)
self.at = at
def open(self, mode='r', *args, **kwargs):
"""
Open this entry as text or binary following the semantics
of ``pathlib.Path.open()`` by passing arguments through
to io.TextIOWrapper().
"""
pwd = kwargs.pop('pwd', None)
zip_mode = mode[0]
stream = self.root.open(self.at, zip_mode, pwd=pwd)
if 'b' in mode:
if args or kwargs:
raise ValueError("encoding args invalid for binary operation")
return stream
return io.TextIOWrapper(stream, *args, **kwargs)
@property
def name(self):
return posixpath.basename(self.at.rstrip("/"))
def read_text(self, *args, **kwargs):
with self.open('r', *args, **kwargs) as strm:
return strm.read()
def read_bytes(self):
with self.open('rb') as strm:
return strm.read()
def _is_child(self, path):
return posixpath.dirname(path.at.rstrip("/")) == self.at.rstrip("/")
def _next(self, at):
return Path(self.root, at)
def is_dir(self):
return not self.at or self.at.endswith("/")
def is_file(self):
return not self.is_dir()
def exists(self):
return self.at in self.root._name_set()
def iterdir(self):
if not self.is_dir():
raise ValueError("Can't listdir a file")
subs = map(self._next, self.root.namelist())
return filter(self._is_child, subs)
def __str__(self):
return posixpath.join(self.root.filename, self.at)
def __repr__(self):
return self.__repr.format(self=self)
def joinpath(self, add):
next = posixpath.join(self.at, add)
return self._next(self.root.resolve_dir(next))
__truediv__ = joinpath
@property
def parent(self):
parent_at = posixpath.dirname(self.at.rstrip('/'))
if parent_at:
parent_at += '/'
return self._next(parent_at)
def main(args=None):
import argparse
description = 'A simple command-line interface for zipfile module.'
parser = argparse.ArgumentParser(description=description)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-l', '--list', metavar='<zipfile>',
help='Show listing of a zipfile')
group.add_argument('-e', '--extract', nargs=2,
metavar=('<zipfile>', '<output_dir>'),
help='Extract zipfile into target dir')
group.add_argument('-c', '--create', nargs='+',
metavar=('<name>', '<file>'),
help='Create zipfile from sources')
group.add_argument('-t', '--test', metavar='<zipfile>',
help='Test if a zipfile is valid')
args = parser.parse_args(args)
if args.test is not None:
src = args.test
with ZipFile(src, 'r') as zf:
badfile = zf.testzip()
if badfile:
print("The following enclosed file is corrupted: {!r}".format(badfile))
print("Done testing")
elif args.list is not None:
src = args.list
with ZipFile(src, 'r') as zf:
zf.printdir()
elif args.extract is not None:
src, curdir = args.extract
with ZipFile(src, 'r') as zf:
zf.extractall(curdir)
elif args.create is not None:
zip_name = args.create.pop(0)
files = args.create
def addToZip(zf, path, zippath):
if os.path.isfile(path):
zf.write(path, zippath, ZIP_DEFLATED)
elif os.path.isdir(path):
if zippath:
zf.write(path, zippath)
for nm in sorted(os.listdir(path)):
addToZip(zf,
os.path.join(path, nm), os.path.join(zippath, nm))
# else: ignore
with ZipFile(zip_name, 'w') as zf:
for path in files:
zippath = os.path.basename(path)
if not zippath:
zippath = os.path.basename(os.path.dirname(path))
if zippath in ('', os.curdir, os.pardir):
zippath = ''
addToZip(zf, path, zippath)
if __name__ == "__main__":
main() | |
main.go | package main
import (
"fmt"
"strings"
) | s = s[slash+1:]
if dot := strings.LastIndex(s, "."); dot >= 1 {
s = s[:dot]
}
return s
}
func main() {
fmt.Println(basename("a/b/c.go")) // "c"
fmt.Println(basename("c.d.go")) // "c.d"
fmt.Println(basename("abc")) // "abc"
} |
func basename(s string) string {
slash := strings.LastIndex(s, "/") |
_tickfont.py | import _plotly_utils.basevalidators
class | (_plotly_utils.basevalidators.CompoundValidator):
def __init__(
self, plotly_name='tickfont', parent_name='contour.colorbar', **kwargs
):
super(TickfontValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class_str='Tickfont',
data_docs="""
color
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The plotly service (at https://plot.ly
or on-premise) generates images on a server,
where only a select number of fonts are
installed and supported. These include *Arial*,
*Balto*, *Courier New*, *Droid Sans*,, *Droid
Serif*, *Droid Sans Mono*, *Gravitas One*, *Old
Standard TT*, *Open Sans*, *Overpass*, *PT Sans
Narrow*, *Raleway*, *Times New Roman*.
size
""",
**kwargs
)
| TickfontValidator |
zim.min.js | // ZIM js Interactive Media framework http://zimjs.com by Dan Zen http://danzen.com (c) 2018
// Also see http://zimjs.com/distill to minify only the functions in your app
// free to use - donations welcome of course! http://zimjs.com/donate
var zimDefaultFrame;if(void 0===zon)var zon=!0;if(void 0===zns)var zns=!1;var zog=zon?console.log.bind(console):function(){};function zid(e){return z_d("1"),document.getElementById(e)}function zss(e){if(z_d("2"),document.getElementById(e))return document.getElementById(e).style;zon&&zog("zim wrap - zss(): id not found")}function zgo(e,t,o,n,r,i){if(z_d("3"),!(zot(t)&&""!=t||"_self"==t)){var a="";return o&&(a+="width="+o+","),n&&(a+="height="+n+","),r&&(a+="fullscreen=yes,"),i&&(a+="modal=yes,alwaysRaised=yes"),window.open(e,t,a)}window.location.href=e}function zum(e){if(z_d("4"),!zot(e))return Number(String(e).replace(/[^\d\.\-]/g,""))}function zot(e){return null==e}function zop(e){z_d("5"),zot(e)||(e.stopImmediatePropagation&&e.stopImmediatePropagation(),window.event&&(window.event.cancelBubble=!0))}function zil(){z_d("6");var e=function(e){e||(e=event),e.keyCode&&32<=e.keyCode&&e.keyCode<=40&&e.preventDefault()},t=function(e){e||(e=event),e.preventDefault()},o=t;return window.addEventListener("keydown",e,{passive:!1}),window.addEventListener("wheel",t,{passive:!1}),window.addEventListener("DOMMouseScroll",o,{passive:!1}),[e,t,o]}function zet(r){return z_d("6.1"),new function(){var a=this;this.on=function(e,t){if(!(zot(r)||zot(e)||zot(t)))for(var o=a.tags,n=0;n<o.length;n++)o[n].addEventListener(e,t)},this.off=function(e,t){if(!(zot(r)||zot(e)||zot(t)))for(var o=a.tags,n=0;n<o.length;n++)o[n].removeEventListener(e,t)},Object.defineProperty(a,"tags",{get:function(){return zot(r)?[]:"string"==typeof r||r instanceof String?document.querySelectorAll(r):"string"==typeof r.innerHTML?[r]:[]},set:function(e){}}),this.css=function(e,t){for(var o=a.tags,n=0;n<o.length;n++)if(1==arguments.length&&e.constructor==={}.constructor)for(var r in e)o[n].style[r]=e[r];else{if(1==arguments.length)return a.tags[0].style[e];o[n].style[e]=t}},this.prop=function(e,t){if(!zot(e)){for(var o=a.tags,n=[],r=0;r<o.length;r++)if(zot(t))if(e.constructor==={}.constructor)for(var i in e)o[r][i]=e[i];else n.push(o[r][e]);else o[r][e]=t;return zot(t)?n:void 0}}}}function isDUO(e){return 1==e.length&&null!=e[0]&&e[0].constructor==={}.constructor}function zob(e,t,o,n){if(isDUO(t)){z_d("7");var r,i,a,l=t[0],s=zot(o)?e.toString().split(/\n/,1)[0].match(/\((.*)\)/)[1].replace(/\s+/g,"").split(","):o.replace(/\s+/g,"").split(","),c=[];for(r=0;r<s.length;r++)i=s[r].split("=")[0],s[r]=i,c.push(l[i]);for(r in l)s.indexOf(r)<0&&zon&&zog(e,"bad argument "+r);return!(a=e.prototype.isPrototypeOf(n)?new(e.bind.apply(e,[null].concat(c))):e.apply(null,c))||a}}function zik(e){if(z_d("7.5"),z_d("17.6"),!zot(e))return zim.Pick.choose(e)}var ignore,zta=zon?console.table.bind(console):function(){};function z_d(e){zim&&(zim.DISTILL||window.DISTILL)&&zim.distillery.push(e)}function zimify(e,t){z_d("83.3");var o={drag:function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f){return isDUO(arguments)?(e.obj=this,zim.drag(e)):zim.drag(this,e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f)},noDrag:function(){return zim.noDrag(this)},dragBoundary:function(e){return zim.dragBoundary(this,e)},dragRect:function(e){return zim.dragBoundary(this,e)},transform:function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A){return isDUO(arguments)?(e.obj=this,zim.transform(e)):zim.transform(this,e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A)},setSwipe:function(e){return zim.setSwipe(this,e)},gesture:function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p){return isDUO(arguments)?(e.obj=this,zim.gesture(e)):zim.gesture(this,e,t,o,n,r,i,a,l,s,c,u,d,h,g,p)},noGesture:function(e,t,o){if(isDUO(arguments))return e.obj=this,zim.noGesture(e);zim.noGesture(this,e,t,o)},gestureBoundary:function(e,t){return zim.gestureBoundary(this,e,t)},gestureRect:function(e,t){return zim.gestureBoundary(this,e,t)},addPhysics:function(e,t,o,n,r,i,a,l,s,c,u){return isDUO(arguments)?(e.obj=this,zim.addPhysics(e)):zim.addPhysics(this,e,t,o,n,r,i,a,l,s,c,u)},removePhysics:function(){return zim.removePhysics(this)},hitTestPoint:function(e,t,o){return zim.hitTestPoint(this,e,t,o)},hitTestReg:function(e,t){return zim.hitTestReg(this,e,t)},hitTestRect:function(e,t,o){return zim.hitTestRect(this,e,t,o)},hitTestCircle:function(e,t,o){return zim.hitTestCircle(this,e,t,o)},hitTestCircles:function(e,t){return zim.hitTestCircles(this,e,t)},hitTestBounds:function(e,t,o){return zim.hitTestBounds(this,e,t,o)},boundsToGlobal:function(e,t,o){return zim.boundsToGlobal(this,e,t,o)},resetBounds:function(e,t,o,n){return zim.resetBounds(this,e,t,o,n)},hitTestGrid:function(e,t,o,n,r,i,a,l,s,c,u,d){return zim.hitTestGrid(this,e,t,o,n,r,i,a,l,s,c,u,d)},animate:function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R){return isDUO(arguments)?(e.target=this,zim.animate(e)):zim.animate(this,e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R)},pauseAnimate:function(){return this},stopAnimate:function(){return this},wiggle:function(e,t,o,n,r,i,a,l,s,c,u,d,h){return isDUO(arguments)?(e.target=this,zim.wiggle(e)):zim.wiggle(this,e,t,o,n,r,i,a,l,s,c,u,d,h)},loop:function(e,t,o,n,r){return zim.loop(this,e,t,o,n,r)},copyMatrix:function(e){return zim.copyMatrix(this,e)},cur:function(e){return zim.cur(this,e)},sha:function(e,t,o,n){return zim.sha(this,e,t,o,n)},pos:function(e,t,o,n,r,i,a,l,s,c){return isDUO(arguments)?(e.obj=this,zim.pos(e)):zim.pos(this,e,t,o,n,r,i,a,l,s,c)},loc:function(e,t,o,n,r,i,a){return isDUO(arguments)?(e.obj=this,zim.loc(e)):zim.loc(this,e,t,o,n,r,i,a)},mov:function(e,t){return isDUO(arguments)?(e.obj=this,zim.mov(e)):zim.mov(this,e,t)},top:function(){return zim.top(this)},bot:function(){return zim.bot(this)},ord:function(e){return zim.ord(this,e)},dep:function(e){return zim.dep(this,e)},alp:function(e){return zim.alp(this,e)},hov:function(e,t){return zim.hov(this,e,t)},rot:function(e,t,o){return zim.rot(this,e,t,o)},siz:function(e,t,o){return zim.siz(this,e,t,o)},ske:function(e,t){return zim.ske(this,e,t)},reg:function(e,t){return zim.reg(this,e,t)},sca:function(e,t){return zim.sca(this,e,t)},scaleTo:function(e,t,o,n,r){return isDUO(arguments)?(e.obj=this,zim.scaleTo(e)):zim.scaleTo(this,e,t,o,n,r)},fit:function(e,t,o,n,r){return isDUO(arguments)?(e.obj=this,zim.fit(e)):zim.fit(this,e,t,o,n,r)},outline:function(e,t){return isDUO(arguments)?(e.obj=this,zim.outline(e)):zim.outline(this,e,t)},addTo:function(e,t,o){return isDUO(arguments)?(e.obj=this,zim.addTo(e)):zim.addTo(this,e,t,o)},removeFrom:function(e){return zim.removeFrom(this,e)},added:function(e,t,o){return zim.added(this,e,t,o)},tap:function(e,t,o,n){return zim.tap(this,e,t,o,n)},noTap:function(){return zim.noTap(this)},change:function(e,t){return zim.change(this,e,t)},noChange:function(){return zim.noChange(this)},centerReg:function(e,t,o){return isDUO(arguments)?(e.obj=this,zim.centerReg(e)):zim.centerReg(this,e,t,o)},center:function(e,t,o){return isDUO(arguments)?(e.obj=this,zim.center(e)):zim.center(this,e,t,o)},place:function(e){return zim.place(this,e)},placeReg:function(e){return zim.placeReg(this,e)},expand:function(e,t){return zim.expand(this,e,t)},setMask:function(e,t){return zim.setMask(this,e,t)},cloneProps:function(e){return e.type=this.type,e.group=this.group,e.style=this.style,e.alpha=this.alpha,e.rotation=this.rotation,e.mouseEnabled=this.mouseEnabled,e.tickEnabled=this.tickEnabled,e.x=this.x,e.y=this.y,e.scaleX=this.scaleX,e.scaleY=this.scaleY,e.skewX=this.skewX,e.skewY=this.skewY,e.name=this.name,e.regX=this.regX*e.width/this.width,e.regY=this.regY*e.height/this.height,e.visible=this.visible,e.shadow=this.shadow,this.type&&"Shape"!=this.type||zim.copyMatrix(e,this),e.compositeOperation=this.compositeOperation,e.snapToPixel=this.snapToPixel,e.filters=null==this.filters?null:this.filters.slice(0),e.mask=this.mask,e.hitArea=this.hitArea,this.type&&"Shape"!=this.type||!this._bounds||e.setBounds(this._bounds.x,this._bounds.y,this._bounds.width,this._bounds.height),e},cloneChildren:function(e){e.children.length&&e.removeAllChildren();for(var t=e.children,o=0,n=this.children.length;o<n;o++){var r=this.children[o].clone();r.parent=e,t.push(r)}return e}};if(!zot(t)){t=[];for(var n in o)t.push(n);return t}for(var r in o)o.hasOwnProperty(r)&&(e[r]=o[r]);return Object.defineProperty(e,"width",{enumerable:!0,get:function(){var e=this.getBounds();return zot(e)?null:e.width*this.scaleX},set:function(e){var t=this.getBounds();if(zot(t)||0==t.width)zog("width needs bounds set with setBounds()");else{var o=e/t.width;this.scaleX=this.scaleY=o}}}),Object.defineProperty(e,"height",{enumerable:!0,get:function(){var e=this.getBounds();return zot(e)?null:e.height*this.scaleY},set:function(e){var t=this.getBounds();if(zot(t)||0==t.height)zog("height needs bounds set with setBounds()");else{var o=e/t.height;this.scaleX=this.scaleY=o}}}),Object.defineProperty(e,"widthOnly",{enumerable:!0,get:function(){var e=this.getBounds();return zot(e)?null:e.width*this.scaleX},set:function(e){var t=this.getBounds();if(zot(t)||0==t.width)zog("widthOnly needs bounds set with setBounds()");else{var o=e/t.width;this.scaleX=o}}}),Object.defineProperty(e,"heightOnly",{enumerable:!0,get:function(){var e=this.getBounds();return zot(e)?null:e.height*this.scaleY},set:function(e){var t=this.getBounds();if(zot(t)||0==t.height)zog("heightOnly needs bounds set with setBounds()");else{var o=e/t.height;this.scaleY=o}}}),Object.defineProperty(e,"depth",{enumerable:!0,get:function(){return this._depth},set:function(e){if(this._depth=e,!zot(this.vrChannel)){var t=this.vrParallaxDistance?e*this.vrParallax*this.vrParallaxDistance:0;"left"==this.vrChannel?this.x=this.vrStartX+e+t:"right"==this.vrChannel&&(this.x=this.vrStartX-e+t)}}}),Object.defineProperty(e,"blendMode",{enumerable:!0,get:function(){return this.compositeOperation},set:function(e){this.compositeOperation=e}}),e}function zimplify(e){z_d("83.35"),document.Window=Window,document.Blob=Blob,ignore="ignore",zot(e)&&(e=[]),Array.isArray(e)||(e=[e]);var t=zimify(null,!0),o=["loop","stopAnimate","pauseAnimate","animate","wiggle"];for(var n in zim)(-1==t.indexOf(n)||0<=o.indexOf(n))&&-1==e.indexOf(n)&&(window[n]=zim[n]);window.KEYFOCUS=zim.KEYFOCUS,window.OPTIMIZE=zim.OPTIMIZE,window.ACTIONEVENT=zim.ACTIONEVENT,window.STYLE=zim.STYLE}var zim=function(m){return m.Wonder=function(n,r,i,a,e){var t;if(t=zob(m.Wonder,arguments,"wid, client, app, notes, server",this))return t;if(z_d("82"),zot(n))zog("zim.Wonder() - please provide Wonder ID (see https://zimjs.com/wonder/)");else{zot(e)&&(e="http://54.237.229.197:3001/wonder");var o=this;zot(m.wonderSession)&&(m.wonderSession="W"+m.rand(1e5,999999));var l,s=[],c=setInterval(p,1e3),u=0,d=setInterval(function(){28<u&&(s.push({id:n,c:r,a:i,n:a,k:l,t:"e",v:"frequency max - terminated",s:m.wonderSession}),zog("zim.Wonder() - frequency max - terminated"),o.dispose()),u=0},3e4);this.countsOff={},this.timesOff={},this.ordersOff={},this.count=function(e){f(e,"count")&&(l=e,s.push({id:n,c:r,a:i,n:a,k:e,t:"c",v:1,s:m.wonderSession}))};var h={};this.timeStart=function(e){f(e,"time")&&(o.timeEnd(e),h[l=e]=(new Date).getTime())};var g={};this.timePause=function(e){f(e,"time")&&(g[e]||(g[e]=(new Date).getTime()))},this.timeUnpause=function(e){if(f(e,"time")&&g[e]){var t=(new Date).getTime()-g[e];h[e]&&(h[e]+=t),delete g[e]}},this.timeEnd=function(e){if(f(e,"time")&&h[e]){var t=g[e]?g[e]:(new Date).getTime(),o=Math.round((t-h[e])/1e3);delete g[e],delete h[e],s.push({id:n,c:r,a:i,n:a,k:e,t:"t",v:o,s:m.wonderSession})}},this.order=function(e,t){f(e,"order")&&(l=e,zot(t)?zog("zim.Wonder order() - please provide an item"):s.push({id:n,c:r,a:i,n:a,k:e,t:"o",v:t,s:m.wonderSession}))},this.countOff=function(e){o.countsOff[e]=1},this.countOn=function(e){delete o.countOff[e]},this.timeOff=function(e){o.timesOff[e]=1},this.timeOn=function(e){delete o.timesOff[e]},this.orderOff=function(e){o.ordersOff[e]=1},this.orderOn=function(e){delete o.ordersOff[e]},this.dispose=function(){return p(),clearInterval(c),clearInterval(d),!0}}function p(){0<s.length&&(m.async(e+"?wonder="+JSON.stringify(s)),s=[],u++)}function | (e,t){return zot(e)?(zog("zim.Wonder "+t+" - please provide a keyword"),!1):!o[t+"sOff"][e]}},m}((zim=function(kt){function u(e,t,o,n,r){var i=e*e;return t+(3*-t+e*(3*t-t*e))*e+(3*o+e*(-6*o+3*o*e))*e+(3*n-3*n*e)*i+r*(i*e)}if(kt.orange="#f58e25",kt.green="#acd241",kt.pink="#e472c4",kt.blue="#50c4b7",kt.brown="#d1a170",kt.yellow="#ebcb35",kt.purple="#993399",kt.red="#fb4758",kt.silver="#999999",kt.tin="#777777",kt.grey="#555555",kt.gray="#555555",kt.lighter="#eeeeee",kt.moon="#dddddd",kt.light="#cccccc",kt.dark="#333333",kt.darker="#111111",kt.black="#000000",kt.white="#ffffff",kt.clear="rgba(0,0,0,0)",kt.faint="rgba(0,0,0,.01)",kt.shuffle=function(e){if(z_d("8"),!zot(e)){var t,o,n=e.length;if(0==n)return e;for(;--n;)t=Math.floor(Math.random()*(n+1)),o=e[n],e[n]=e[t],e[t]=o;return e}},kt.rand=function(e,t,o,n){return z_d("9"),zot(e)&&zot(t)?Math.random():((zot(e)||isNaN(e))&&(e=0),(zot(t)||isNaN(t))&&(t=0),e%1==0&&t%1==0||(o=!1),zot(o)&&(o=!0),n&&.5<Math.random()&&(e*=-1,t*=-1),o&&(t<e?e++:e<t&&t++),0==e&&0==t?0:(r=0==t?Math.random()*e:Math.min(e,t)+Math.random()*(Math.max(e,t)-Math.min(e,t)),o?Math.floor(r):r));var r},kt.series=function(){var e;if(z_d("13.61"),0==arguments.length)return function(){};e=1==arguments.length&&Array.isArray(arguments[0])?arguments[0]:arguments;var t=0,o=function(){return e[t++%e.length]};return o.array=e,o},kt.makeSeries=function(e){if(z_d("13.6"),zot(e))return function(){};var t=0,o=function(){return e[t++%e.length]};return o.array=e,o},kt.loop=function(e,t,o,n,r,i){var a;if(a=zob(kt.loop,arguments,"obj, call, reverse, step, start, end"))return a;if(z_d("9.5"),!zot(e)&&!zot(t)){zot(o)&&(o=!1),(zot(n)||n<=0)&&(n=1);var l="number"==typeof e?"number":e.constructor===Array?"array":e.constructor==={}.constructor?"object":e instanceof NodeList?"nodelist":e instanceof HTMLCollection?"htmlcollection":"invalid";if("invalid"!=l)if("number"==l||"array"==l||"nodelist"==l||"htmlcollection"==l){if(0==(u=g((d="number"==l?e:e.length)-1)))return;if(o)for(var s=r;i<=s;s-=n){if("number"==l)var c=t(s,u,r,i,e);else if("array"==l)c=t(e[s],s,u,r,i,e);else c=t(e.item(s),s,u,r,i,e);if(void 0!==c)return c}else for(s=r;s<=i;s+=n){if("number"==l)c=t(s,u,r,i,e);else if("array"==l)c=t(e[s],s,u,r,i,e);else c=t(e.item(s),s,u,r,i,e);if(void 0!==c)return c}}else if("object"==l){var u,d=0,h=[];for(var s in e)d++,h.push(s);if(0==(u=g(d-1)))return;if(o)for(s=r;i<=s;s-=n){if(void 0!==(c=t(h[s],e[h[s]],s,u,r,i,e)))return c}else for(s=r;s<=i;s+=n){if(void 0!==(c=t(h[s],e[h[s]],s,u,r,i,e)))return c}}}function g(e){return zot(r)&&(r=o?e:0),zot(i)&&(i=o?0:e),o&&r<i||!o&&i<r?0:(r<0&&i)<0||e<r&&e<i?0:(r=Math.max(0,Math.min(r,e)),i=Math.max(0,Math.min(i,e)),Math.floor((o?r-i:i-r)/n)+1)}},kt.timeout=function(t,o){if(z_d("9.7"),!zot(o)&&"function"==typeof o){zot(t)&&(t=1e3),t=kt.Pick.choose(t);var n={startTime:Date.now(),time:0,paused:!1,done:!1},r=n.startTime;return n.pause=function(e){zot(e)&&(e=!0),e?cancelAnimationFrame(n.rid):(r=Date.now(),i()),n.paused=e},n.clear=function(){for(var e in n&&cancelAnimationFrame(n.rid),n)delete n[e];n.pause=function(){},n.clear=function(){}},i(),n}function i(){var e=Date.now();if(n.time+=e-r,r=e,n.time>=t)return n.done=!0,o(n),void n.clear();n.rid=requestAnimationFrame(i)}},kt.interval=function(e,o,t,n){if(z_d("9.8"),!zot(o)&&"function"==typeof o&&(zot(e)&&(e=1e3),zot(n)&&(n=!1),zot(t)||!(isNaN(t)||t<=0))){zot(t)&&(t=-1);var r,i={count:0,total:t,paused:!1,time:e,active:!0};return n&&setTimeout(function(){o(i),l()},10),i.pause=function(e,t){zot(e)&&(e=!0),i.pauseTimeLeft=e?(clearTimeout(r),clearTimeout(i.id),cancelAnimationFrame(i.rid),i.interval-(Date.now()-i.startTime)):(r=setTimeout(function(){i.count++,o(i),a(),l()},t?0:i.pauseTimeLeft),null),i.paused=e},i.clear=function(){i.active=!1,clearTimeout(r),cancelAnimationFrame(i.rid),clearTimeout(i.id);var e=i.count;for(var t in i)delete i[t];i.active=!1,i.count=e,i.pause=function(){},i.clear=function(){}},a(),i}function a(){i.startTime=Date.now(),i.interval=kt.Pick.choose(i.time),i.id=setTimeout(function(){i.paused||i.active&&(i.rid=requestAnimationFrame(a),i.count++,o(i),l())},i.interval)}function l(){-1!=t&&i.count>=(n?i.total-1:i.total)&&i.clear()}},kt.async=function(e,t){if(z_d("29"),!zot(e)){var o,n=document.createElement("script");if(t){var r=t.toString().split(/\n/,1)[0].match(/^function\s?([^\s(]*)/)[1];kt.async[r]=(o=n,function(e){o&&o.parentNode.removeChild(o),o=null,t(e)})}else kt.async.z_s&&kt.async.z_s.parentNode&&kt.async.z_s.parentNode.removeChild(kt.async.z_s),kt.async.z_s=n;e.match(/\?/)||(e+="?"),n.setAttribute("src",e+"&r="+Math.random()),document.getElementsByTagName("head")[0].appendChild(n)}},kt.convertColorCheck=!1,kt.convertColor=function(e,o,n){if(kt.convertColorCheck||(z_d("27.5"),kt.convertColorCheck=!0),zot(o)&&(o="hex"),zot(n),!zot(e)){var t;if(e.match(/rgba\(/))return(t=e.split(","))[3]=n+")",t.join(",");if(e.match(/rgb\(/))return"rgba"!=o?e:(t=e.split(")"))[0]+","+n+t[1];if("rgb"==o||"rgba"==o){function r(e){var t;return/^#([A-Fa-f0-9]{3}){1,2}$/.test(e)?(3==(t=e.substring(1).split("")).length&&(t=[t[0],t[0],t[1],t[1],t[2],t[2]]),t="0x"+t.join(""),"rgb"==o?"rgb("+[t>>16&255,t>>8&255,255&t]+")":"rgba("+[t>>16&255,t>>8&255,255&t].join(",")+","+n+")"):"rgb"==o?"rgb(0,0,0)":"rgba(0,0,0,1)"}return"#"==e.charAt(0)?r(e):r(kt.convertColor(e))}if("hex"==o){if("#"==e.charAt(0))return e}else"#"==e.charAt(0)&&3==(e=e.replace("#","")).length&&(e=e.charAt(0)+e.charAt(0)+e.charAt(1)+e.charAt(1)+e.charAt(2)+e.charAt(2));var i=["black","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgrey","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgrey","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],a=["000000","f0f8ff","faebd7","00ffff","7fffd4","f0ffff","f5f5dc","ffe4c4","ffebcd","0000ff","8a2be2","a52a2a","deb887","5f9ea0","7fff00","d2691e","ff7f50","6495ed","fff8dc","dc143c","00ffff","00008b","008b8b","b8860b","a9a9a9","a9a9a9","006400","bdb76b","8b008b","556b2f","ff8c00","9932cc","8b0000","e9967a","8fbc8f","483d8b","2f4f4f","2f4f4f","00ced1","9400d3","ff1493","00bfff","696969","696969","1e90ff","b22222","fffaf0","228b22","ff00ff","dcdcdc","f8f8ff","ffd700","daa520","808080","808080","008000","adff2f","f0fff0","ff69b4","cd5c5c","4b0082","fffff0","f0e68c","e6e6fa","fff0f5","7cfc00","fffacd","add8e6","f08080","e0ffff","fafad2","d3d3d3","d3d3d3","90ee90","ffb6c1","ffa07a","20b2aa","87cefa","778899","778899","b0c4de","ffffe0","00ff00","32cd32","faf0e6","ff00ff","800000","66cdaa","0000cd","ba55d3","9370db","3cb371","7b68ee","00fa9a","48d1cc","c71585","191970","f5fffa","ffe4e1","ffe4b5","ffdead","000080","fdf5e6","808000","6b8e23","ffa500","ff4500","da70d6","eee8aa","98fb98","afeeee","db7093","ffefd5","ffdab9","cd853f","ffc0cb","dda0dd","b0e0e6","800080","663399","ff0000","bc8f8f","4169e1","8b4513","fa8072","f4a460","2e8b57","fff5ee","a0522d","c0c0c0","87ceeb","6a5acd","708090","708090","fffafa","00ff7f","4682b4","d2b48c","008080","d8bfd8","ff6347","40e0d0","ee82ee","f5deb3","ffffff","f5f5f5","ffff00","9acd32"];return"string"==o?i[-1!=a.indexOf(e.toLowerCase())?a.indexOf(e):0]:"#"+a[-1!=i.indexOf(e.toLowerCase())?i.indexOf(e):0]}},kt.colorRangeCheck=!1,kt.colorRange=function(e,t,o){o=Math.max(0,Math.min(1,o)),kt.colorRangeCheck||(z_d("27.6"),kt.colorRangeCheck=!0),zot(e)&&(e="white"),zot(t)&&(t="black");for(var n,r,i=kt.convertColor(e,"rgb"),a=kt.convertColor(t,"rgb"),l=(e=i.substring(4,i.length-1).split(","),t=a.substring(4,a.length-1).split(","),"#"),s=0;s<e.length;s++)n=t[s]-e[s],(r=Math.floor(parseInt(e[s],10)+n*o).toString(16)).length<2&&(r="0"+r),l+=r;return l},kt.pointAlongCurve=function(e,t,o){if(z_d("27.7"),e&&e[0]&&e[1]&&e[2]&&e[3]){var n=u(t,e[0].x,e[1].x,e[2].x,e[3].x),r=u(t,e[0].y,e[1].y,e[2].y,e[3].y);if(o){var i=t+.05;if(1<i){i-=.05;var a=u(t-=.05,e[0].x,e[1].x,e[2].x,e[3].x),l=u(t,e[0].y,e[1].y,e[2].y,e[3].y)}else a=n,l=r;var s=u(i,e[0].x,e[1].x,e[2].x,e[3].x),c=u(i,e[0].y,e[1].y,e[2].y,e[3].y);return{x:n,y:r,angle:kt.angle(a,l,s,c)}}return{x:n,y:r}}},kt.distanceAlongCurve=function(e){return z_d("27.8"),(kt.dist(e[0],e[3])+(kt.dist(e[0],e[1])+kt.dist(e[1],e[2])+kt.dist(e[2],e[3])))/2},kt.closestPointAlongCurve=function(a,e,t,o,n){z_d("27.9");var l,s=1e7,c=0,u=0;return zot(t)&&(t=10),kt.loop(e,function(r,i,e){kt.loop(t,function(e,t){var o=kt.pointAlongCurve(r,e/t),n=kt.dist(a,o);n<s&&(s=n,l=o,c=i,u=e)})}),n?(c*t+u)/(e.length*t)*100:o?l:c},kt.transformPoints=function(e,t,o,n,r){if(z_d("27.95"),!zot(e)&&Array.isArray(e)){zot(n)&&(n=0),zot(r)&&(r=0);e=kt.copy(e);var i,a=n,l=r;"rotation"==t&&(0!=n&&(e=kt.transformPoints(e,"x",-a)),0!=r&&(e=kt.transformPoints(e,"y",-l)));for(var s=0;s<e.length;s++)if(i=e[s],Array.isArray(i))if("x"==t)i[0]+=o;else if("y"==t)i[1]+=o;else if("scaleX"==t)i[0]=(i[0]-n)*o+n,i[4]=i[4]*o,i[6]=i[6]*o;else if("scaleY"==t)i[1]=(i[1]-r)*o+r,i[5]=i[5]*o,i[7]=i[7]*o;else if("scale"==t)i[0]=(i[0]-n)*o+n,i[4]=i[4]*o,i[6]=i[6]*o,i[1]=(i[1]-r)*o+r,i[5]=i[5]*o,i[7]=i[7]*o;else if("rotation"==t){var c=o*Math.PI/180,u=i[0],d=i[1];i[0]=u*Math.cos(c)-d*Math.sin(c),i[1]=d*Math.cos(c)+u*Math.sin(c),u=i[4],d=i[5],i[4]=u*Math.cos(c)-d*Math.sin(c),i[5]=d*Math.cos(c)+u*Math.sin(c),u=i[6],d=i[7],i[6]=u*Math.cos(c)-d*Math.sin(c),i[7]=d*Math.cos(c)+u*Math.sin(c)}return"rotation"==t&&(0!=n&&(e=kt.transformPoints(e,"x",a)),0!=r&&(e=kt.transformPoints(e,"y",l))),e}},kt.makeID=function(e,t,o){var n;z_d("13.5"),zot(e)&&(e="mixed"),zot(t)&&(t=5),zot(o)&&(o="uppercase");var r=[2,3,4,5,6,7,8,9],i="abcdefghjkmnpqrstuvwxyz".split("");n=e.constructor===Array?e:"numbers"==e?r:"letters"==e?i:r.concat(i);for(var a,l,s="",c=0;c<t;c++)a=n[Math.floor(Math.random()*n.length)],l=Math.random(),"uppercase"==o||"mixed"==o&&.5<l?a.toUpperCase&&(a=a.toUpperCase()):a.toLowerCase&&(a=a.toLowerCase()),s+=String(a);return s},kt.swapProperties=function(e,t,o){if(z_d("17.1"),zot(t)||zot(o)||zot(t[e])||zot(o[e]))return!1;var n=o[e];return o[e]=t[e],t[e]=n,!0},kt.mobile=function(e){return z_d("28"),zot(e)&&(e=!0),/ip(hone|od|ad)/i.test(navigator.userAgent)?"ios":/android|nexus/i.test(navigator.userAgent)?"android":/blackberry/i.test(navigator.userAgent)?"blackberry":/nokia|phone|mobile/i.test(navigator.userAgent)?"windows":/opera mini|webos/i.test(navigator.userAgent)?"other":!(!e||void 0===window.orientation)},kt.vee=function(e){return z_d("28.5"),!zot(e)&&("Pick"==e.type||Array.isArray(e)||e.constructor=={}.constructor&&(!zot(e.max)||!zot(e.noPick))||"function"==typeof e)},kt.extend=function(e,t,o,n,r){var i;if(i=zob(kt.extend,arguments,"subclass, superclass, override, prefix, prototype"))return i;if(!zot(e)&&!zot(t)||!zon){zot(n)&&(n="super"),zot(o)&&(o=[]),Array.isArray(o)||(o=[o]),zot(r)&&(r=!0);var a={};for(var l in e.prototype)Object.defineProperty(a,l,Object.getOwnPropertyDescriptor(e.prototype,l));for(l in h.prototype=t.prototype,e.prototype=new h,a)Object.defineProperty(e.prototype,l,Object.getOwnPropertyDescriptor(a,l));var s=e.prototype,c=Object.getPrototypeOf&&Object.getPrototypeOf(s)||s.__proto__;if(c){var u;s[(n+="_")+"constructor"]=c.constructor;for(var d=0;d<o.length;d++)"function"==typeof c[u=o[d]]&&(s[n+u]=c[u]);if(r)for(u in c)s.hasOwnProperty(u)&&"function"==typeof c[u]&&(s[n+u]=c[u])}return e}function h(){this.constructor=e}zog("zim.extend() - please supply a class and its superclass")},kt.copyCheck=!1,kt.copy=function(e,t,o){if(kt.copyCheck||(z_d("10"),kt.copyCheck=!0),zot(t)&&(t=!1),zot(o)&&(o=!0),null==e||!(e instanceof Array||e.constructor=={}.constructor))return t&&null!=e&&e.clone&&e.type&&("Container"!=e.type&&"Stage"!=e.type&&"StageGL"!=e.type||o)?e.clone():e;if(e instanceof Array){for(var n=[],r=0;r<e.length;r++)n[r]=kt.copy(e[r],t,o);return n}if(e.constructor=={}.constructor){var i={};for(var a in e){var l=kt.copy(e[a],t,o);e.hasOwnProperty(a)&&(i[a]=l)}return i}},kt.mergeCheck=!1,kt.merge=function(){kt.mergeCheck||(z_d("12"),kt.mergeCheck=!0);var e,t,o={};for(e=0;e<arguments.length;e++)for(t in arguments[e])arguments[e].hasOwnProperty(t)&&(o[t]=arguments[e][t]);return o},kt.arraysEqual=function(e,t,o){if(z_d("11"),zot(e)||zot(t))return!1;if(zot(o)&&(o=!0),e.length!=t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]instanceof Array&&t[n]instanceof Array){if(!kt.arraysEqual(e[n],t[n],o))return!1}else{if(o&&e[n]!=t[n])return!1;if(!o)return kt.arraysEqual(e.sort(),t.sort(),!0)}return!0},kt.isEmpty=function(e){if(z_d("11.5"),!zot(e)){var t=0;for(var o in e){t++;break}return 0==t}},kt.isJSON=function(e){z_d("11.6");try{return JSON.parse(e).constructor=={}.constructor}catch(e){return!1}},kt.zut=function(e){if(zot(e)||"object"==typeof e)return!0},kt.zimDecimalCheck=!1,kt.decimals=function(e,t,o,n,r,i,a){if(kt.zimDecimalCheck||z_d("13"),kt.zimDecimalCheck=!0,zot(e))return 0;zot(t)&&(t=1),zot(o)&&(o=0),zot(n)&&(n=0),zot(n)&&(n=0),zot(r)&&(r=!0),zot(i)&&(i=!1);var l=Math.round(e*Math.pow(10,t))/Math.pow(10,t);if(i){var s=l-Math.floor(l);l=kt.decimals(Math.floor(l)+60*s/100,2)}var c=kt.sign(l);if(0<o){var u=String(l).indexOf("."),d=String(l).length;u<0&&(u=d++,l+=".");for(var h=0;h<o-(d-u-1);h++)l+="0"}if(0<n){-1==c&&(l=l.substr(1,l.length-1));u=String(l).indexOf("."),d=String(l).length;var g=u<0?d:u;for(h=0;h<n-g;h++)l="0"+l;-1==c&&(l="-"+l)}return 0<o+n&&!r&&0==Number(l)&&(l=0),i&&(l=String(l).replace(".",":")),kt.zut(a)?l:null},kt.zimSignCheck=!1,kt.sign=function(e){return kt.zimSignCheck||z_d("13.1"),kt.zimSignCheck=!0,e?e<0?-1:1:0},kt.constrain=function(e,t,o,n){if(z_d("13.2"),!zot(e))return zot(t)&&(t=0),zot(o)&&(o=Number.MAX_VALUE),o<t&&(o=max2=t,t=max2),zot(n)&&(n=!1),n&&e<0?Math.max(-o,Math.min(e,-t)):Math.max(t,Math.min(e,o))},kt.zimDistCheck=!1,kt.dist=function(e,t,o,n){if(kt.zimDistCheck||z_d("13.3"),kt.zimDistCheck=!0,!zot(e)&&!zot(t))return zot(e.x)||zot(t.x)?(zot(o)&&(o=0),zot(n)&&(n=0)):(n=t.y,o=t.x,t=e.y,e=e.x),Math.sqrt(Math.pow(o-e,2)+Math.pow(n-t,2))},kt.angle=function(e,t,o,n){if(z_d("13.4"),!zot(e)&&!zot(t))return zot(o)&&(o=e,e=0),zot(n)&&(n=t,t=0),(180*Math.atan2(n-t,o-e)/Math.PI+360)%360},kt.smoothStep=function(e,t,o){z_d("13.7");var n=kt.constrain((e-t)/(o-t),0,1);return n*n*n*(n*(6*n-15)+10)},kt.Noise=function(e){"use strict";z_d("13.9"),zot(e)&&(e=1e6*Math.random());var t=e;this.seed=e;var F=this,H={};function o(e){var t=new Uint32Array(1);return t[0]=1664525*e[0]+1013904223,t}function n(e,t,o){this.dx=-t-e*H.SQUISH_2D,this.dy=-o-e*H.SQUISH_2D,this.xsb=t,this.ysb=o}function r(e,t,o,n){this.dx=-t-e*H.SQUISH_3D,this.dy=-o-e*H.SQUISH_3D,this.dz=-n-e*H.SQUISH_3D,this.xsb=t,this.ysb=o,this.zsb=n}function i(e,t,o,n,r){this.dx=-t-e*H.SQUISH_4D,this.dy=-o-e*H.SQUISH_4D,this.dz=-n-e*H.SQUISH_4D,this.dw=-r-e*H.SQUISH_4D,this.xsb=t,this.ysb=o,this.zsb=n,this.wsb=r}H.NORM_2D=1/47,H.NORM_3D=1/103,H.NORM_4D=1/30,H.SQUISH_2D=(Math.sqrt(3)-1)/2,H.SQUISH_3D=(Math.sqrt(4)-1)/3,H.SQUISH_4D=(Math.sqrt(5)-1)/4,H.STRETCH_2D=(1/Math.sqrt(3)-1)/2,H.STRETCH_3D=(1/Math.sqrt(4)-1)/3,H.STRETCH_4D=(1/Math.sqrt(5)-1)/4,H.base2D=[[1,1,0,1,0,1,0,0,0],[1,1,0,1,0,1,2,1,1]],H.base3D=[[0,0,0,0,1,1,0,0,1,0,1,0,1,0,0,1],[2,1,1,0,2,1,0,1,2,0,1,1,3,1,1,1],[1,1,0,0,1,0,1,0,1,0,0,1,2,1,1,0,2,1,0,1,2,0,1,1]],H.base4D=[[0,0,0,0,0,1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,4,1,1,1,1],[1,1,0,0,0,1,0,1,0,0,1,0,0,1,0,1,0,0,0,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1],[3,1,1,1,0,3,1,1,0,1,3,1,0,1,1,3,0,1,1,1,2,1,1,0,0,2,1,0,1,0,2,1,0,0,1,2,0,1,1,0,2,0,1,0,1,2,0,0,1,1]],H.gradients2D=[5,2,2,5,-5,2,-2,5,5,-2,2,-5,-5,-2,-2,-5],H.gradients3D=[-11,4,4,-4,11,4,-4,4,11,11,4,4,4,11,4,4,4,11,-11,-4,4,-4,-11,4,-4,-4,11,11,-4,4,4,-11,4,4,-4,11,-11,4,-4,-4,11,-4,-4,4,-11,11,4,-4,4,11,-4,4,4,-11,-11,-4,-4,-4,-11,-4,-4,-4,-11,11,-4,-4,4,-11,-4,4,-4,-11],H.gradients4D=[3,1,1,1,1,3,1,1,1,1,3,1,1,1,1,3,-3,1,1,1,-1,3,1,1,-1,1,3,1,-1,1,1,3,3,-1,1,1,1,-3,1,1,1,-1,3,1,1,-1,1,3,-3,-1,1,1,-1,-3,1,1,-1,-1,3,1,-1,-1,1,3,3,1,-1,1,1,3,-1,1,1,1,-3,1,1,1,-1,3,-3,1,-1,1,-1,3,-1,1,-1,1,-3,1,-1,1,-1,3,3,-1,-1,1,1,-3,-1,1,1,-1,-3,1,1,-1,-1,3,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,3,1,1,-1,1,3,1,-1,1,1,3,-1,1,1,1,-3,-3,1,1,-1,-1,3,1,-1,-1,1,3,-1,-1,1,1,-3,3,-1,1,-1,1,-3,1,-1,1,-1,3,-1,1,-1,1,-3,-3,-1,1,-1,-1,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,3,1,-1,-1,1,3,-1,-1,1,1,-3,-1,1,1,-1,-3,-3,1,-1,-1,-1,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,3,-1,-1,-1,1,-3,-1,-1,1,-1,-3,-1,1,-1,-1,-3,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3,-1,-1,-1,-1,-3],H.lookupPairs2D=[0,1,1,0,4,1,17,0,20,2,21,2,22,5,23,5,26,4,39,3,42,4,43,3],H.lookupPairs3D=[0,2,1,1,2,2,5,1,6,0,7,0,32,2,34,2,129,1,133,1,160,5,161,5,518,0,519,0,546,4,550,4,645,3,647,3,672,5,673,5,674,4,677,3,678,4,679,3,680,13,681,13,682,12,685,14,686,12,687,14,712,20,714,18,809,21,813,23,840,20,841,21,1198,19,1199,22,1226,18,1230,19,1325,23,1327,22,1352,15,1353,17,1354,15,1357,17,1358,16,1359,16,1360,11,1361,10,1362,11,1365,10,1366,9,1367,9,1392,11,1394,11,1489,10,1493,10,1520,8,1521,8,1878,9,1879,9,1906,7,1910,7,2005,6,2007,6,2032,8,2033,8,2034,7,2037,6,2038,7,2039,6],H.lookupPairs4D=[0,3,1,2,2,3,5,2,6,1,7,1,8,3,9,2,10,3,13,2,16,3,18,3,22,1,23,1,24,3,26,3,33,2,37,2,38,1,39,1,41,2,45,2,54,1,55,1,56,0,57,0,58,0,59,0,60,0,61,0,62,0,63,0,256,3,258,3,264,3,266,3,272,3,274,3,280,3,282,3,2049,2,2053,2,2057,2,2061,2,2081,2,2085,2,2089,2,2093,2,2304,9,2305,9,2312,9,2313,9,16390,1,16391,1,16406,1,16407,1,16422,1,16423,1,16438,1,16439,1,16642,8,16646,8,16658,8,16662,8,18437,6,18439,6,18469,6,18471,6,18688,9,18689,9,18690,8,18693,6,18694,8,18695,6,18696,9,18697,9,18706,8,18710,8,18725,6,18727,6,131128,0,131129,0,131130,0,131131,0,131132,0,131133,0,131134,0,131135,0,131352,7,131354,7,131384,7,131386,7,133161,5,133165,5,133177,5,133181,5,133376,9,133377,9,133384,9,133385,9,133400,7,133402,7,133417,5,133421,5,133432,7,133433,5,133434,7,133437,5,147510,4,147511,4,147518,4,147519,4,147714,8,147718,8,147730,8,147734,8,147736,7,147738,7,147766,4,147767,4,147768,7,147770,7,147774,4,147775,4,149509,6,149511,6,149541,6,149543,6,149545,5,149549,5,149558,4,149559,4,149561,5,149565,5,149566,4,149567,4,149760,9,149761,9,149762,8,149765,6,149766,8,149767,6,149768,9,149769,9,149778,8,149782,8,149784,7,149786,7,149797,6,149799,6,149801,5,149805,5,149814,4,149815,4,149816,7,149817,5,149818,7,149821,5,149822,4,149823,4,149824,37,149825,37,149826,36,149829,34,149830,36,149831,34,149832,37,149833,37,149842,36,149846,36,149848,35,149850,35,149861,34,149863,34,149865,33,149869,33,149878,32,149879,32,149880,35,149881,33,149882,35,149885,33,149886,32,149887,32,150080,49,150082,48,150088,49,150098,48,150104,47,150106,47,151873,46,151877,45,151881,46,151909,45,151913,44,151917,44,152128,49,152129,46,152136,49,152137,46,166214,43,166215,42,166230,43,166247,42,166262,41,166263,41,166466,48,166470,43,166482,48,166486,43,168261,45,168263,42,168293,45,168295,42,168512,31,168513,28,168514,31,168517,28,168518,25,168519,25,280952,40,280953,39,280954,40,280957,39,280958,38,280959,38,281176,47,281178,47,281208,40,281210,40,282985,44,282989,44,283001,39,283005,39,283208,30,283209,27,283224,30,283241,27,283256,22,283257,22,297334,41,297335,41,297342,38,297343,38,297554,29,297558,24,297562,29,297590,24,297594,21,297598,21,299365,26,299367,23,299373,26,299383,23,299389,20,299391,20,299584,31,299585,28,299586,31,299589,28,299590,25,299591,25,299592,30,299593,27,299602,29,299606,24,299608,30,299610,29,299621,26,299623,23,299625,27,299629,26,299638,24,299639,23,299640,22,299641,22,299642,21,299645,20,299646,21,299647,20,299648,61,299649,60,299650,61,299653,60,299654,59,299655,59,299656,58,299657,57,299666,55,299670,54,299672,58,299674,55,299685,52,299687,51,299689,57,299693,52,299702,54,299703,51,299704,56,299705,56,299706,53,299709,50,299710,53,299711,50,299904,61,299906,61,299912,58,299922,55,299928,58,299930,55,301697,60,301701,60,301705,57,301733,52,301737,57,301741,52,301952,79,301953,79,301960,76,301961,76,316038,59,316039,59,316054,54,316071,51,316086,54,316087,51,316290,78,316294,78,316306,73,316310,73,318085,77,318087,77,318117,70,318119,70,318336,79,318337,79,318338,78,318341,77,318342,78,318343,77,430776,56,430777,56,430778,53,430781,50,430782,53,430783,50,431e3,75,431002,72,431032,75,431034,72,432809,74,432813,69,432825,74,432829,69,433032,76,433033,76,433048,75,433065,74,433080,75,433081,74,447158,71,447159,68,447166,71,447167,68,447378,73,447382,73,447386,72,447414,71,447418,72,447422,71,449189,70,449191,70,449197,69,449207,68,449213,69,449215,68,449408,67,449409,67,449410,66,449413,64,449414,66,449415,64,449416,67,449417,67,449426,66,449430,66,449432,65,449434,65,449445,64,449447,64,449449,63,449453,63,449462,62,449463,62,449464,65,449465,63,449466,65,449469,63,449470,62,449471,62,449472,19,449473,19,449474,18,449477,16,449478,18,449479,16,449480,19,449481,19,449490,18,449494,18,449496,17,449498,17,449509,16,449511,16,449513,15,449517,15,449526,14,449527,14,449528,17,449529,15,449530,17,449533,15,449534,14,449535,14,449728,19,449729,19,449730,18,449734,18,449736,19,449737,19,449746,18,449750,18,449752,17,449754,17,449784,17,449786,17,451520,19,451521,19,451525,16,451527,16,451528,19,451529,19,451557,16,451559,16,451561,15,451565,15,451577,15,451581,15,451776,19,451777,19,451784,19,451785,19,465858,18,465861,16,465862,18,465863,16,465874,18,465878,18,465893,16,465895,16,465910,14,465911,14,465918,14,465919,14,466114,18,466118,18,466130,18,466134,18,467909,16,467911,16,467941,16,467943,16,468160,13,468161,13,468162,13,468163,13,468164,13,468165,13,468166,13,468167,13,580568,17,580570,17,580585,15,580589,15,580598,14,580599,14,580600,17,580601,15,580602,17,580605,15,580606,14,580607,14,580824,17,580826,17,580856,17,580858,17,582633,15,582637,15,582649,15,582653,15,582856,12,582857,12,582872,12,582873,12,582888,12,582889,12,582904,12,582905,12,596982,14,596983,14,596990,14,596991,14,597202,11,597206,11,597210,11,597214,11,597234,11,597238,11,597242,11,597246,11,599013,10,599015,10,599021,10,599023,10,599029,10,599031,10,599037,10,599039,10,599232,13,599233,13,599234,13,599235,13,599236,13,599237,13,599238,13,599239,13,599240,12,599241,12,599250,11,599254,11,599256,12,599257,12,599258,11,599262,11,599269,10,599271,10,599272,12,599273,12,599277,10,599279,10,599282,11,599285,10,599286,11,599287,10,599288,12,599289,12,599290,11,599293,10,599294,11,599295,10],H.p2D=[0,0,1,-1,0,0,-1,1,0,2,1,1,1,2,2,0,1,2,0,2,1,0,0,0],H.p3D=[0,0,1,-1,0,0,1,0,-1,0,0,-1,1,0,0,0,1,-1,0,0,-1,0,1,0,0,-1,1,0,2,1,1,0,1,1,1,-1,0,2,1,0,1,1,1,-1,1,0,2,0,1,1,1,-1,1,1,1,3,2,1,0,3,1,2,0,1,3,2,0,1,3,1,0,2,1,3,0,2,1,3,0,1,2,1,1,1,0,0,2,2,0,0,1,1,0,1,0,2,0,2,0,1,1,0,0,1,2,0,0,2,2,0,0,0,0,1,1,-1,1,2,0,0,0,0,1,-1,1,1,2,0,0,0,0,1,1,1,-1,2,3,1,1,1,2,0,0,2,2,3,1,1,1,2,2,0,0,2,3,1,1,1,2,0,2,0,2,1,1,-1,1,2,0,0,2,2,1,1,-1,1,2,2,0,0,2,1,-1,1,1,2,0,0,2,2,1,-1,1,1,2,0,2,0,2,1,1,1,-1,2,2,0,0,2,1,1,1,-1,2,0,2,0],H.p4D=[0,0,1,-1,0,0,0,1,0,-1,0,0,1,0,0,-1,0,0,-1,1,0,0,0,0,1,-1,0,0,0,1,0,-1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,-1,0,0,-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,2,1,1,0,0,1,1,1,-1,0,1,1,1,0,-1,0,2,1,0,1,0,1,1,-1,1,0,1,1,0,1,-1,0,2,0,1,1,0,1,-1,1,1,0,1,0,1,1,-1,0,2,1,0,0,1,1,1,-1,0,1,1,1,0,-1,1,0,2,0,1,0,1,1,-1,1,0,1,1,0,1,-1,1,0,2,0,0,1,1,1,-1,0,1,1,1,0,-1,1,1,1,4,2,1,1,0,4,1,2,1,0,4,1,1,2,0,1,4,2,1,0,1,4,1,2,0,1,4,1,1,0,2,1,4,2,0,1,1,4,1,0,2,1,4,1,0,1,2,1,4,0,2,1,1,4,0,1,2,1,4,0,1,1,2,1,2,1,1,0,0,3,2,1,0,0,3,1,2,0,0,1,2,1,0,1,0,3,2,0,1,0,3,1,0,2,0,1,2,0,1,1,0,3,0,2,1,0,3,0,1,2,0,1,2,1,0,0,1,3,2,0,0,1,3,1,0,0,2,1,2,0,1,0,1,3,0,2,0,1,3,0,1,0,2,1,2,0,0,1,1,3,0,0,2,1,3,0,0,1,2,2,3,1,1,1,0,2,1,1,1,-1,2,2,0,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,2,0,0,0,2,3,1,0,1,1,2,1,-1,1,1,2,2,0,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,2,0,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,2,0,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,2,0,0,2,3,1,1,1,0,2,1,1,1,-1,2,0,0,2,0,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,2,0,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,2,0,2,3,1,1,0,1,2,1,1,-1,1,2,0,0,0,2,2,3,1,0,1,1,2,1,-1,1,1,2,0,0,0,2,2,3,0,1,1,1,2,-1,1,1,1,2,0,0,0,2,2,1,1,1,-1,0,1,1,1,0,-1,0,0,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,0,0,0,0,0,2,1,-1,1,1,0,1,0,1,1,-1,0,0,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,0,0,0,0,0,2,1,-1,1,0,1,1,0,1,-1,1,0,0,0,0,0,2,1,-1,0,1,1,1,0,-1,1,1,0,0,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,2,0,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,2,0,0,0,2,1,1,-1,0,1,1,1,0,-1,1,2,2,0,0,0,2,1,1,1,-1,0,1,1,1,0,-1,2,0,2,0,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,2,0,0,2,1,-1,1,0,1,1,0,1,-1,1,2,0,2,0,0,2,1,1,-1,1,0,1,1,0,1,-1,2,0,0,2,0,2,1,-1,1,1,0,1,0,1,1,-1,2,0,0,2,0,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,2,0,2,1,1,-1,0,1,1,1,0,-1,1,2,0,0,0,2,2,1,-1,1,0,1,1,0,1,-1,1,2,0,0,0,2,2,1,-1,0,1,1,1,0,-1,1,1,2,0,0,0,2,3,1,1,0,0,0,2,2,0,0,0,2,1,1,1,-1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,1,-1,3,1,0,0,1,0,2,0,0,2,0,2,1,1,1,-1,3,1,1,0,0,0,2,2,0,0,0,2,1,1,-1,1,3,1,0,1,0,0,2,0,2,0,0,2,1,1,-1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,1,-1,1,3,1,1,0,0,0,2,2,0,0,0,2,1,-1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,1,-1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,1,-1,1,1,3,1,0,1,0,0,2,0,2,0,0,2,-1,1,1,1,3,1,0,0,1,0,2,0,0,2,0,2,-1,1,1,1,3,1,0,0,0,1,2,0,0,0,2,2,-1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,4,1,1,1,1,3,3,2,0,1,0,3,1,0,2,0,4,1,1,1,1,3,3,0,2,1,0,3,0,1,2,0,4,1,1,1,1,3,3,2,0,0,1,3,1,0,0,2,4,1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,4,1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,4,1,1,1,1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,1,-1,3,3,2,0,1,0,3,1,0,2,0,2,1,1,1,-1,3,3,0,2,1,0,3,0,1,2,0,2,1,1,1,-1,3,3,2,1,0,0,3,1,2,0,0,2,1,1,-1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,1,-1,1,3,3,0,2,0,1,3,0,1,0,2,2,1,1,-1,1,3,3,2,0,1,0,3,1,0,2,0,2,1,-1,1,1,3,3,2,0,0,1,3,1,0,0,2,2,1,-1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,1,-1,1,1,3,3,0,2,1,0,3,0,1,2,0,2,-1,1,1,1,3,3,0,2,0,1,3,0,1,0,2,2,-1,1,1,1,3,3,0,0,2,1,3,0,0,1,2,2,-1,1,1,1];for(var a=[],l=0;l<H.p2D.length;l+=4){for(var s=H.base2D[H.p2D[l]],c=null,u=null,d=0;d<s.length;d+=3)u=new n(s[d],s[d+1],s[d+2]),null===c?a[l/4]=u:c.next=u,c=u;u.next=new n(H.p2D[l+1],H.p2D[l+2],H.p2D[l+3])}this.lookup2D=[];for(l=0;l<H.lookupPairs2D.length;l+=2)this.lookup2D[H.lookupPairs2D[l]]=a[H.lookupPairs2D[l+1]];var h=[];for(l=0;l<H.p3D.length;l+=9){for(s=H.base3D[H.p3D[l]],c=null,u=null,d=0;d<s.length;d+=4)u=new r(s[d],s[d+1],s[d+2],s[d+3]),null===c?h[l/9]=u:c.next=u,c=u;u.next=new r(H.p3D[l+1],H.p3D[l+2],H.p3D[l+3],H.p3D[l+4]),u.next.next=new r(H.p3D[l+5],H.p3D[l+6],H.p3D[l+7],H.p3D[l+8])}this.lookup3D=[];for(l=0;l<H.lookupPairs3D.length;l+=2)this.lookup3D[H.lookupPairs3D[l]]=h[H.lookupPairs3D[l+1]];var g=[];for(l=0;l<H.p4D.length;l+=16){for(s=H.base4D[H.p4D[l]],c=null,u=null,d=0;d<s.length;d+=5)u=new i(s[d],s[d+1],s[d+2],s[d+3],s[d+4]),null===c?g[l/16]=u:c.next=u,c=u;u.next=new i(H.p4D[l+1],H.p4D[l+2],H.p4D[l+3],H.p4D[l+4],H.p4D[l+5]),u.next.next=new i(H.p4D[l+6],H.p4D[l+7],H.p4D[l+8],H.p4D[l+9],H.p4D[l+10]),u.next.next.next=new i(H.p4D[l+11],H.p4D[l+12],H.p4D[l+13],H.p4D[l+14],H.p4D[l+15])}this.lookup4D=[];for(l=0;l<H.lookupPairs4D.length;l+=2)this.lookup4D[H.lookupPairs4D[l]]=g[H.lookupPairs4D[l+1]];this.perm=new Uint8Array(256),this.perm2D=new Uint8Array(256),this.perm3D=new Uint8Array(256),this.perm4D=new Uint8Array(256);var p=new Uint8Array(256);for(l=0;l<256;l++)p[l]=l;(e=new Uint32Array(1))[0]=t,e=o(o(o(e)));for(l=255;0<=l;l--){e=o(e);var f=new Uint32Array(1);f[0]=(e[0]+31)%(l+1),f[0]<0&&(f[0]+=l+1),this.perm[l]=p[f[0]],this.perm2D[l]=14&this.perm[l],this.perm3D[l]=this.perm[l]%24*3,this.perm4D[l]=252&this.perm[l],p[f[0]]=p[l]}this.simplex1D=function(e){return F.simplex2D(e,1)},this.simplex2D=function(e,t){var o=(e+t)*H.STRETCH_2D,n=[e+o,t+o],r=n[0],i=n[1],a=[Math.floor(r),Math.floor(i)],l=a[0],s=a[1],c=(l+s)*H.SQUISH_2D,u=[e-(l+c),t-(s+c)],d=u[0],h=u[1],g=[r-l,i-s],p=g[0],f=g[1],m=p+f,z=new Uint32Array(4);z[0]=p-f+1,z[1]=m,z[2]=m+f,z[3]=m+p;for(var v=z[0]|z[1]<<1|z[2]<<2|z[3]<<4,y=F.lookup2D[v],b=0;void 0!==y;){var w=[d+y.dx,h+y.dy],x=w[0],C=w[1],k=2-x*x-C*C;if(0<k){var T=[l+y.xsb,s+y.ysb],A=T[0],P=T[1],B=F.perm2D[F.perm[255&A]+P&255];b+=(k*=k)*k*(H.gradients2D[B]*x+H.gradients2D[B+1]*C)}y=y.next}return b*H.NORM_2D},this.simplex3D=function(e,t,o){var n=(e+t+o)*H.STRETCH_3D,r=[e+n,t+n,o+n],i=r[0],a=r[1],l=r[2],s=[Math.floor(i),Math.floor(a),Math.floor(l)],c=s[0],u=s[1],d=s[2],h=(c+u+d)*H.SQUISH_3D,g=[e-(c+h),t-(u+h),o-(d+h)],p=g[0],f=g[1],m=g[2],z=[i-c,a-u,l-d],v=z[0],y=z[1],b=z[2],w=v+y+b,x=new Uint32Array(7);x[0]=y-b+1,x[1]=v-y+1,x[2]=v-b+1,x[3]=w,x[4]=w+b,x[5]=w+y,x[6]=w+v;for(var C=x[0]|x[1]<<1|x[2]<<2|x[3]<<3|x[4]<<5|x[5]<<7|x[6]<<9,k=F.lookup3D[C],T=0;void 0!==k;){var A=[p+k.dx,f+k.dy,m+k.dz],P=A[0],B=A[1],I=A[2],S=2-P*P-B*B-I*I;if(0<S){var E=[c+k.xsb,u+k.ysb,d+k.zsb],M=E[0],O=E[1],j=E[2],D=F.perm3D[F.perm[F.perm[255&M]+O&255]+j&255];T+=(S*=S)*S*(H.gradients3D[D]*P+H.gradients3D[D+1]*B+H.gradients3D[D+2]*I)}k=k.next}return T*H.NORM_3D},this.simplex4D=function(e,t,o,n){var r=(e+t+o+n)*H.STRETCH_4D,i=[e+r,t+r,o+r,n+r],a=i[0],l=i[1],s=i[2],c=i[3],u=[Math.floor(a),Math.floor(l),Math.floor(s),Math.floor(c)],d=u[0],h=u[1],g=u[2],p=u[3],f=(d+h+g+p)*H.SQUISH_4D,m=e-(d+f),z=t-(h+f),v=o-(g+f),y=n-(p+f),b=[a-d,l-h,s-g,c-p],w=b[0],x=b[1],C=b[2],k=b[3],T=w+x+C+k,A=new Uint32Array(11);A[0]=C-k+1,A[1]=x-C+1,A[2]=x-k+1,A[3]=w-x+1,A[4]=w-C+1,A[5]=w-k+1,A[6]=T<<6,A[7]=T+k,A[8]=T+C,A[9]=T+x,A[10]=T+w;for(var P=A[0]|A[1]<<1|A[2]<<2|A[3]<<3|A[4]<<4|A[5]<<5|A[6]<<6|A[7]<<8|A[8]<<11|A[9]<<14|A[10]<<17,B=F.lookup4D[P],I=0;void 0!==B;){var S=[m+B.dx,z+B.dy,v+B.dz,y+B.dw],E=S[0],M=S[1],O=S[2],j=S[3],D=2-E*E-M*M-O*O-j*j;if(0<D){var L=[d+B.xsb,h+B.ysb,g+B.zsb,p+B.wsb],Y=L[0],X=L[1],R=L[2],_=L[3],W=F.perm4D[F.perm[F.perm[F.perm[255&Y]+X&255]+R&255]+_&255];I+=(D*=D)*D*(H.gradients4D[W]*E+H.gradients4D[W+1]*M+H.gradients4D[W+2]*O+H.gradients4D[W+3]*j)}B=B.next}return I*H.NORM_4D}},kt.Point=function(e,t,o,n,r,i,a,l,s,c){z_d("13.45"),zot(e)&&(e=0),zot(t)&&(t=0),zot(o)&&(o=0),zot(n)&&(n=0),zot(r)&&(r=0),zot(i)&&(i=0),zot(a)&&(a=0),zot(l)&&(l=0),zot(s)&&(s=0),zot(c)&&(c=0),this.x=e,this.y=t,this.z=o,this.q=n,this.r=r,this.s=i,this.t=a,this.u=l,this.v=s,this.w=c},kt.Boundary=function(e,t,o,n){z_d("13.46"),zot(e)||zot(t)||zot(o)||zot(n)||(this.x=e,this.y=t,this.width=o,this.height=n,this.contract=function(e,t,o,n){return zot(e)||(zot(t)&&(t=e),zot(o)?o=2*e:o+=e,zot(n)?n=2*t:n+=t,this.x+=e,this.y+=t,this.width-=o,this.height-=n),this})},kt.Damp=function(e,t){z_d("14");var o;if(o=zob(kt.Damp,arguments,"startValue, damp",this))return o;this.lastValue=zot(e)?0:e,this.damp=zot(t)?.1:t},kt.Damp.prototype.convert=function(e){return this.lastValue=this.lastValue+(e-this.lastValue)*this.damp},kt.Damp.prototype.immediate=function(e){return this.lastValue=e,this},kt.Proportion=function(t,o,n,r,i,a,l){var e,s,c;if(e=zob(kt.Proportion,arguments,"baseMin, baseMax, targetMin, targetMax, factor, targetRound, clamp",this))return e;z_d("15"),zot(n)&&(n=0),zot(r)&&(r=1),zot(i)&&(i=1),zot(a)&&(a=!1),zot(l)&&(l=!0),this.convert=function(e){if(!isNaN(e)&&o-t!=0)return l&&(e=Math.max(e,t),e=Math.min(e,o)),s=(e-t)/(o-t),c=0<i?n+(r-n)*s:r-(r-n)*s,a&&(c=Math.round(c)),c}},kt.ProportionDamp=function(e,t,o,n,r,i,a,l){var s;if(s=zob(kt.ProportionDamp,arguments,"baseMin, baseMax, targetMin, targetMax, damp, factor, targetRound, clamp",this))return s;z_d("16"),zot(o)&&(o=0),zot(n)&&(n=1),zot(r)&&(r=.1),zot(i)&&(i=1),zot(a)&&(a=!1),zot(l)&&(l=!0),this.damp=r;var c,u,d,h,g=this,p=0;c=e,p=o;var f=setInterval(m,20);function m(){isNaN(c)||t-e==0||(l&&(c=Math.max(c,e),c=Math.min(c,t)),u=(c-e)/(t-e),d=n-o,p+=((h=0<i?o+d*u:n-d*u)-p)*g.damp)}this.immediate=function(e){return g.convert(e),m(),p=h,a&&(p=Math.round(p)),g},this.convert=function(e){return c=e,a?Math.round(p):p},this.dispose=function(){return clearInterval(f),!0}},kt.Dictionary=function(e){z_d("17"),this.length=0,this.unique=e;var o=this.objects=[],n=this.values=[];this.add=function(e,t){zot(e)||(zot(t)&&(t=!0),this.unique&&this.remove(e),o.push(e),n.push(t),this.length++)},this.at=function(e){if(!zot(e)){var t=o.indexOf(e);return-1<t?n[t]:null}},this.remove=function(e){if(zot(e))return!1;var t=o.indexOf(e);return-1<t&&(o.splice(t,1),n.splice(t,1),this.length--,!0)},this.clear=function(){return o=this.objects=[],n=this.values=[],this.length=null,this},this.dispose=function(){return n=o=null,!(this.length=null)}},kt.Hierarchy=function(o){z_d("17.5");var t=this;function n(e){var r=[],i=[];return function o(e,n){loop(e,function(e,t){r.push(t.obj),i.push(e),t.open&&o(t.list,n+1)})}(e,0),[r,i]}zot(o)||(t.processSimple=function(e){var a=0,t={};return function n(e,r,i){e.constructor=={}.constructor?loop(e,function(e,t){var o={};r["id"+a]={obj:e,level:i,open:!1,opened:!1,list:o},a++,n(t,o,i+1)}):Array.isArray(e)&&loop(e,function(e){r["id"+a]={obj:e},a++})}(o,t,0),t},t.processComplex=function(e){return function o(e,n){loop(e,function(e,t){t.level=n,t.open=!1,t.opened=!1,t.list&&o(t.list,n+1)})}(e,0),e},zot(o.id0)?t.data=t.processSimple(o):t.data=t.processComplex(o),t.getLinearList=function(e){return zot(e)&&(e=t.data),n(e)[0]},t.getLinearIDs=function(e){return zot(e)&&(e=t.data),n(e)[1]},t.getData=function(n){var r;return function o(e){loop(e,function(e,t){if(e==n)return r=t;o(t.list)})}(t.data),r},t.getNextSibling=function(n){var r,i;return function o(e){loop(e,function(e,t){if(!i&&r)return i=e;e==n?r=t:o(t.list)})}(t.data),i},t.getPrevSibling=function(r){var i=[];return function o(e,n){loop(e,function(e,t){if(e==r)return i[n]||i[n-1];i[n]=e,o(t.list,n+1)})}(t.data,0),answer})},kt.Pick=function(e){z_d("17.6"),this.choices=e,this.num=function(e){for(var t=[],o=0;o<e;o++)t.push(kt.Pick.choose(this));return this.choices=kt.Pick.series(t),this};var r=this;this.loop=function(e,t){for(var o,n=0;n<e;n++)if(void 0!==(o=t(kt.Pick.choose(r),n,e)))return o}},kt.Pick.prototype.type="Pick",kt.Pick.series=function(){return kt.series.apply(null,arguments)},kt.Pick.rand=function(e,t,o,n){return kt.rand(e,t,o,n)},kt.Pick.choose=function(e,t){if(null==t&&(t=!0),null==e)return e;if("Pick"==e.type||t){var o=e.choices||e;if(Array.isArray(o)){var n=o[Math.floor(Math.random()*o.length)];return kt.Pick.choose(n)}return o.constructor==={}.constructor?zot(o.noPick)?zot(o.max)?o:(zot(o.integer)&&(o.integer=!1),n=kt.Pick.rand(o.min,o.max,o.integer,o.negative)):o.noPick:"function"==typeof o?kt.Pick.choose(o()):e}return e},kt.scrollX=function(e,t){return z_d("18"),kt.abstractScroll("X","Left",e,t)},kt.scrollY=function(e,t){return z_d("19"),kt.abstractScroll("Y","Top",e,t)},kt.abstractScroll=function(e,t,o,n){z_d("20");var r="X"==e?"Y":"X";if(zot(o)){var i=navigator.applicationName;if(-1!=navigator.userAgent.indexOf("Safari")||"Safari"==i);return document.documentElement&&document.documentElement["scroll"+t]||document.body["scroll"+t]}if(zot(n))window.scrollTo(kt["scroll"+r](),o);else{n<50&&(n=50);var a=n/50,l=kt["scroll"+e](),s=(o-l)/a,c=0,u=setInterval(function(){c++,l+=s,window.scrollTo(kt["scroll"+r](),l),a<=c&&(window.scrollTo(kt["scroll"+r](),o),clearInterval(u))},50)}return o},kt.windowWidth=function(){return z_d("21"),isNaN(window.innerWidth)?window.clientWidth:window.innerWidth},kt.windowHeight=function(){return z_d("22"),isNaN(window.innerHeight)?window.clientHeight:window.innerHeight},kt.getQueryString=function(e){if(z_d("22.5"),zot(e)&&(e=location.search.replace("?","")),""!=e){for(var t=e.split("&"),o={},n=0;n<t.length;n++){var r=t[n].split("=");void 0===o[r[0]]?o[r[0]]=decodeURIComponent((r[1]+"").replace(/\+/g,"%20")):"string"==typeof o[r[0]]?o[r[0]]=[o[r[0]],decodeURIComponent((r[1]+"").replace(/\+/g,"%20"))]:o[r[0]].push(decodeURIComponent((r[1]+"").replace(/\+/g,"%20")))}return o}},kt.swapHTML=function(e,t){return z_d("17.2"),kt.swapProperties("innerHTML",zid(e),zid(t))},kt.urlEncode=function(e){z_d("23");e=(e+"").toString();return encodeURIComponent(e).replace(/!/g,"%21").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29").replace(/\*/g,"%2A").replace(/%20/g,"+")},kt.urlDecode=function(e){return z_d("24"),decodeURIComponent((e+"").replace(/\+/g,"%20"))},kt.setCookie=function(e,t,o){if(z_d("25"),!zot(e)&&!zot(t)){if(o){var n=new Date;n.setTime(n.getTime()+24*o*60*60*1e3);var r="; expires="+n.toGMTString()}else r="";return document.cookie=e+"="+escape(t)+r+"; path=/",!0}},kt.getCookie=function(e){z_d("26");var t,o=document.cookie.split(/;\s*/),n=new Array;for(l=0;l<o.length;l++)n[(t=o[l].split("="))[0]]=t[1];if(void 0!==n[e])return unescape(n[e])},kt.deleteCookie=function(e){return z_d("27"),!zot(kt.getCookie(e))&&(kt.setCookie(e,"",-1),!0)},"undefined"==typeof createjs)return zon&&zog("ZIM >= 4.3.0 requires createjs namespace to be loaded (import createjs before zim)"),kt;function Se(e,t){e._enabled=t?(e.mouseChildren=!0,e.mouseEnabled=!0):(e.mouseChildren=!1,e.mouseEnabled=!1)}kt.Stage=function(e){z_d("50.44"),zot(e)||(this.cjsStage_constructor(e),this.type="Stage",this.cache=function(e,t,o,n,r,i){if(zot(o))if(zot(e)){var a=this.getBounds();if(!zot(a)){var l=0<this.borderWidth?this.borderWidth/2:0;e=a.x-l,t=a.y-l,o=a.width+2*l,n=a.height+2*l}}else o=e,n=t,t=e=0;return this.cjsStage_cache(e,t,o,n,r,i),this},this.loop=function(e,t,o,n,r){return kt.loop(this,e,t,o,n,r)},this.hitTestGrid=function(e,t,o,n,r,i,a,l,s,c,u,d){return kt.hitTestGrid(this,e,t,o,n,r,i,a,l,s,c,u,d)})},kt.extend(kt.Stage,createjs.Stage,["cache"],"cjsStage",!1),kt.StageGL=function(e,t){z_d("50.45"),this.cjsStageGL_constructor(e,t),this.type="StageGL",this.cache=function(e,t,o,n,r,i){if(zot(o))if(zot(e)){var a=this.getBounds();if(!zot(a)){var l=0<this.borderWidth?this.borderWidth/2:0;e=a.x-l,t=a.y-l,o=a.width+2*l,n=a.height+2*l}}else o=e,n=t,t=e=0;return this.cjsStageGL_cache(e,t,o,n,r,i),this},this.loop=function(e,t,o,n,r){return kt.loop(this,e,t,o,n,r)},this.hitTestGrid=function(e,t,o,n,r,i,a,l,s,c,u,d){return kt.hitTestGrid(this,e,t,o,n,r,i,a,l,s,c,u,d)}},kt.extend(kt.StageGL,createjs.StageGL,["cache"],"cjsStageGL",!1),kt.containerCheck=!1,kt.Container=function(e,t,o,n,r,i,a){var l;if(l=zob(kt.Container,arguments,"a, b, c, d, style, group, inherit",this))return l;kt.containerCheck||(z_d("50.5"),kt.containerCheck=!0),this.cjsContainer_constructor(),this.type="Container",this.group=i;var s=!1===r?{}:kt.getStyle(this.type,this.group,a);zot(e)&&(e=null!=s.a?s.a:null),zot(t)&&(t=null!=s.b?s.b:null),zot(o)&&(o=null!=s.c?s.c:null),zot(n)&&(n=null!=s.d?s.d:null);var c=u(e,t,o,n);function u(e,t,o,n){var r=[];return zot(e)?r=[e,t,o,n]:zot(o)?(r[0]=0,r[2]=e,r[1]=0,r[3]=t):(r[0]=e,r[2]=o,r[1]=t,r[3]=n),zot(r[3])&&(r[3]=r[2]),r}zot(e)||this.setBounds(c[0],c[1],c[2],c[3]),this.cache=function(e,t,o,n,r,i){var a=this.getBounds();if(zot(o))if(zot(e)){if(!zot(a)){var l=0<this.borderWidth?this.borderWidth/2:0;e=a.x-l,t=a.y-l,o=a.width+2*l,n=a.height+2*l}}else o=e,n=t,t=e=0;return"Triangle"==this.type&&(e-=this.borderWidth?this.borderWidth:0,o+=this.borderWidth?2*this.borderWidth:0,t-=this.borderWidth?this.borderWidth:0,n+=this.borderWidth?2*this.borderWidth:0),this.cjsContainer_cache(e,t,o,n,r,i),a&&this.setBounds(a.x,a.y,a.width,a.height),this},!(this.setBounds=function(e,t,o,n){var r=u(e,t,o,n);return this.cjsContainer_setBounds(r[0],r[1],r[2],r[3]),this})!==r&&Oe(this,s),this.clone=function(){var e=this.getBounds();return zot(e)&&(e={x:null,y:null,width:null,height:null}),this.cloneChildren(this.cloneProps(new kt.Container(e.x,e.y,e.width,e.height,r,this.group,a)))},this.hasProp=function(e){return!zot(this[e])||this.hasOwnProperty(e)}},kt.Container.prototype.dispose=function(){return function e(t){t.removeAllEventListeners();if(t.numChildren)for(var o=t.numChildren-1;0<=o;o--)e(t.getChildAt(o));t.parent&&t.parent.removeChild(t)}(this),!0},zimify(kt.Container.prototype),kt.extend(kt.Container,createjs.Container,["cache","setBounds","clone"],"cjsContainer",!1),kt.Shape=function(e,t,o,n,r,i,a,l){var s;if(s=zob(kt.Shape,arguments,"a, b, c, d, graphics, style, group, inherit",this))return s;z_d("50.6"),this.cjsShape_constructor(r),this.type="Shape",this.group=a;var c=!1===i?{}:kt.getStyle(this.type,this.group,l),u=this;zot(e)&&(e=null!=c.a?c.a:null),zot(t)&&(t=null!=c.b?c.b:null),zot(o)&&(o=null!=c.c?c.c:null),zot(n)&&(n=null!=c.d?c.d:null);var d=h(e,t,o,n);function h(e,t,o,n){var r=[];return zot(o)?(r[0]=0,r[2]=e,r[1]=0,r[3]=t):(r[0]=e,r[2]=o,r[1]=t,r[3]=n),zot(r[3])&&(r[3]=r[2]),r}zot(e)||this.setBounds(d[0],d[1],d[2],d[3]),this.cache=function(e,t,o,n,r,i){if(zot(o))if(zot(e)){var a=this.getBounds();if(!zot(a)){var l=0<this.borderWidth?this.borderWidth/2:0;e=a.x-l,t=a.y-l,o=a.width+2*l,n=a.height+2*l}}else o=e,n=t,t=e=0;return this.cjsShape_cache(e,t,o,n,r,i),this},!(this.setBounds=function(e,t,o,n){var r=h(e,t,o,n);return this.cjsShape_setBounds(r[0],r[1],r[2],r[3]),this})!==i&&Oe(this,c),this.clone=function(e){zot(e)&&(e=!0);var t=this.getBounds();zot(t)&&(t={x:null,y:null,width:null,height:null});var o=u.cloneProps(new kt.Shape(t.x,t.y,t.width,t.height,r,i,a,l));return o.graphics=e?u.graphics.clone():u.graphics,o},this.hasProp=function(e){return!zot(this[e])||this.hasOwnProperty(e)},this.dispose=function(){this.graphics.c(),this.removeAllEventListeners(),this.parent&&this.parent.removeChild(this)}},kt.extend(kt.Shape,createjs.Shape,["cache","clone","setBounds"],"cjsShape",!1),zimify(kt.Shape.prototype),kt.Bitmap=function(l,s,c,e,t,o,n){var r;if(r=zob(kt.Bitmap,arguments,"image, width, height, id, style, group, inherit",this))return r;z_d("50.7"),this.cjsBitmap_constructor(l);var u=this;this.type="Bitmap",this.group=o;var i=!1===t?{}:kt.getStyle(this.type,this.group,n);this.id=u.fileID=null!=i.id?i.id:e,zot(s)&&(s=null!=i.width?i.width:null),zot(c)&&(c=null!=i.height?i.height:null),zot(s)||zot(c)||u.setBounds(0,0,s,c),zot(s)&&(s=100),zot(c)&&(c=100),zimDefaultFrame&&(zimDefaultFrame.canvas.getContext("2d")?this.imageData=zimDefaultFrame.canvas.getContext("2d").createImageData(s,c):this.imageData=document.createElement("canvas").getContext("2d").createImageData(s,c),this.drawImageData=function(e,t,o,n,r,i){if(zot(e)&&(e=0),zot(t)&&(t=0),zot(o)&&(o=0),zot(n)&&(n=0),zot(r)&&(r=s),zot(i)&&(i=c),!u.proxyCanvas){var a=u.proxyCanvas=document.createElement("canvas");a.setAttribute("width",s),a.setAttribute("height",c),u.proxyContext=a.getContext("2d"),l=u.image=a}u.proxyContext&&u.proxyContext.putImageData(u.imageData,e,t,o,n,r,i)},zot(l)&&u.drawImageData(),l.match&&l.match(/data:image/i)&&setTimeout(function(){u.stage&&u.stage.update(),setTimeout(function(){u.stage&&u.stage.update()},50)},50)),!(this.cache=function(e,t,o,n,r,i){if(zot(o))if(zot(e)){if(!zot(l=this.getBounds())){var a=0<this.borderWidth?this.borderWidth/2:0;e=l.x-a,t=l.y-a,o=l.width+2*a,n=l.height+2*a}}else o=e,n=t,t=e=0;var l=this.getBounds();return this.cjsBitmap_cache(e,t,o,n,r,i),this.setBounds(l.x,l.y,l.width,l.height),this})!==t&&Oe(this,i),this.clone=function(){return this.cloneProps(new kt.Bitmap(l,null,null,u.fileID,t,this.group,n))},this.hasProp=function(e){return!zot(this[e])||this.hasOwnProperty(e)},this.dispose=function(){this.removeAllEventListeners(),this.parent&&this.parent.removeChild(this)}},kt.Bitmap.fromData=function(e,t){var o=new kt.Bitmap(e);setTimeout(function(){t(o)},50)},kt.extend(kt.Bitmap,createjs.Bitmap,["cache","clone"],"cjsBitmap",!1),zimify(kt.Bitmap.prototype),kt.Sprite=function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v){var y;if(y=zob(kt.Sprite,arguments,"image, cols, rows, count, offsetX, offsetY, spacingX, spacingY, width, height, animations, json, id, globalControl, spriteSheet, label, style, group, inherit",this))return y;z_d("50.8"),this.type="Sprite",this.group=z;var b,w=!1===m?{}:kt.getStyle(this.type,this.group,v),j=this;if(zot(d)&&!zot(e)){zot(t)&&(t=null!=w.cols?w.cols:1),zot(o)&&(o=null!=w.rows?w.rows:1),zot(n)&&(n=null!=w.count?w.count:t*o),zot(r)&&(r=null!=w.offsetX?w.offsetX:0),zot(i)&&(i=null!=w.offsetY?w.offsetY:0),zot(a)&&(a=null!=w.spacingX?w.spacingX:0),zot(l)&&(l=null!=w.spacingY?w.spacingY:0),zot(s)&&(s=null!=w.width?w.width:e.width),zot(c)&&(c=null!=w.height?w.height:e.height);var x=(s-r+a)/t-a,C=(c-i+l)/o-l,k=[],T=0;e:for(var A=0;A<o;A++)for(var P=0;P<t;P++){if(++T>n)break e;k.push([r+P*(x+a),i+A*(C+l),x,C])}S(e,k,u)}else if(p)u=(b=p).animations;else{if(!d)return;if(k=d.frames,u=d.animations,zot(e)){var B=d.images?d.images[0]:null;if(B.split){var I=B.split("/").pop();if("EmptyAsset"!=frame.asset(I).type)S(frame.asset(I),k,u);else if("EmptyAsset"!=frame.asset(B).type){frame.asset(B);S(frame.asset(B),k,u)}else b=new createjs.SpriteSheet(d)}else b=new createjs.SpriteSheet(d)}else S(e,k,u)}function S(e,t,o){var n={images:[e.image],frames:t,animations:o||[]};b=new createjs.SpriteSheet(n)}this.animations=u,this.cjsSprite_constructor(b,f),zot(f)||this.stop(),zot(h)&&(h=kt.makeID()),this.id=h,zot(g)&&(g=!0),j.globalControl=g;var D,L=0;this.parseFrames=function(e,t,o,n){var i=[],a=Number.MAX_VALUE,l=0;if(zot(e))zot(t)&&(t=0),zot(o)&&(o=j.totalFrames-1),s(t,o);else{if(zot(j.animations)||zot(j.animations[e]))return[];r(j.animations[e])}function r(e){var t;Array.isArray(e)?(s((t=e)[0],t[1],t[3]),t[2]&&!zot(j.animations[t[2]])&&r(j.animations[t[2]])):e.constructor=={}.constructor?function(e){if(zot(e.frames))return;zot(e.speed)&&(e.speed=1);for(var t=0;t<e.frames.length;t++)e.speed<a&&(a=e.speed),e.speed>l&&(l=e.speed),i.push({f:e.frames[t],s:e.speed});e.next&&!zot(j.animations[e.next])&&r(j.animations[e.next])}(e):isNaN(e)||i.push({f:Math.floor(e),s:1})}function s(e,t,o){if(zot(o)&&(o=1),e<t)for(var n=e;n<=t;n++)r(n);else for(n=t;n<=e;n++)r(e-(n-t));function r(e){o<a&&(a=o),l<o&&(l=o),i.push({f:e,s:o})}}if(n)return i;a=kt.constrain(kt.decimals(a),.1),l=kt.constrain(kt.decimals(l),.1);for(var c,u=[],d=a!=l,h=0;h<i.length;h++)if(c=i[h],d)for(var g=0;g<kt.constrain(Math.round(a<1?c.s/a:c.s),.1);g++)u.push(c.f);else u.push(c.f);return u},this.run=function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k){var T,A;if(T=zob(this.run,arguments,"time, label, call, params, wait, waitedCall, waitedParams, loop, loopCount, loopWait, loopCall, loopParams, loopWaitCall, loopWaitParams, rewind, rewindWait, rewindCall, rewindParams, rewindWaitCall, rewindWaitParams, startFrame, endFrame, tweek, id, globalControl"))return T;if(zot(x)&&(x=1),zot(C)||(j.id=C),zot(k)||(j.globalControl=k),Array.isArray(t)){var P,B;A=[];for(var I,S=0,E=0;E<t.length;E++){(P=t[E]).lookup=j.parseFrames(P.label,P.startFrame,P.endFrame),0==E&&(I=P.lookup[0]),delete P.startFrame,delete P.endFrame,P.obj=kt.merge(P.obj,{normalizedFrame:P.lookup.length-1}),P.set=kt.merge(P.set,{normalizedFrames:{noPick:P.lookup},normalizedFrame:0}),zot(P.wait)&&(P.wait=S*x),B=P.label,delete P.label,A.push(P),S=0;var M=zot(P.time)?e:P.time;0<w-b&&(S=M/(w-b)/2)}if(0==A.length)return this;1==A.length?(e=A[0].time,t=B,O()):j.gotoAndStop(I)}else O();function O(){D=j.parseFrames(t,b,w),L=0,j.gotoAndStop(D[L]),b=w=null,A={normalizedFrame:D.length-1}}if(zot(e)&&(e=1e3),j.running&&j.stopAnimate(j.id),j.running=!0,!Array.isArray(A)){S=0;0<w-b&&(S=e/Math.abs(w-b)/2),D&&0<D.length&&(S=e/D.length/2),zot(c)&&(c=S*x),zot(f)&&(f=S*x)}return kt.animate({target:j,obj:A,time:e,ease:"linear",call:function(){o&&"function"==typeof o&&o(n||j),j.running=!1,j.stop()},params:n,wait:r,waitedCall:i,waitedParams:a,loop:l,loopCount:s,loopWait:c,loopCall:u,loopParams:d,loopWaitCall:h,loopWaitParams:g,rewind:p,rewindWait:f,rewindCall:m,rewindParams:z,rewindWaitCall:v,rewindWaitParams:y,override:!1,id:j.id}),j.runPaused=!1,j},this.runPaused=!0,this.pauseRun=function(e){return zot(e)&&(e=!0),j.runPaused=e,j.globalControl?kt.pauseAnimate(e,j.id):j.pauseAnimate(e,j.id),j},this.stopRun=function(){return j.runPaused=!0,j.running=!1,j.globalControl?kt.stopAnimate(j.id):j.stopAnimate(j.id),j},Object.defineProperty(this,"frame",{get:function(){return this.currentFrame},set:function(e){e=Math.round(e),this.paused?this.gotoAndStop(e):this.gotoAndPlay(e)}}),Object.defineProperty(this,"normalizedFrame",{get:function(){return L},set:function(e){L=Math.round(e),this.gotoAndStop(D[L])}}),Object.defineProperty(this,"normalizedFrames",{get:function(){return D},set:function(e){D=e}}),Object.defineProperty(this,"totalFrames",{get:function(){return b.getNumFrames()},set:function(e){zog("zim.Sprite - totalFrames is read only")}}),!1!==m&&Oe(this,w),this.clone=function(){return this.cloneProps(new kt.Sprite(e,t,o,n,r,i,a,l,s,c,u,d,null,g,p,m,this.group,v))},this.hasProp=function(e){return!zot(this[e])||this.hasOwnProperty(e)},this.dispose=function(){this.removeAllEventListeners(),this.parent&&this.parent.removeChild(this)}},kt.extend(kt.Sprite,createjs.Sprite,"clone","cjsSprite",!1),zimify(kt.Sprite.prototype),kt.MovieClip=function(e,t,o,n,r,i,a){var l;if(l=zob(kt.MovieClip,arguments,"mode, startPosition, loop, labels, style, group, inherit",this))return l;z_d("50.9"),this.type="MovieClip",this.group=i;var s=!1===r?{}:kt.getStyle(this.type,this.group,a);zot(e)&&(e=null!=s.mode?s.mode:null),zot(t)&&(t=null!=s.startPosition?s.startPosition:null),zot(o)&&(o=null!=s.loop?s.loop:null),zot(n)&&(n=null!=s.labels?s.labels:null),this.cjsMovieClip_constructor(e,t,o,n),!1!==r&&Oe(this,s),this.clone=function(){return this.cloneProps(new kt.MovieClip(e,t,o,n,r,this.group,a))},this.hasProp=function(e){return!zot(this[e])||this.hasOwnProperty(e)},this.dispose=function(){this.removeAllEventListeners(),this.parent&&this.parent.removeChild(this)}},kt.extend(kt.MovieClip,createjs.MovieClip,"clone","cjsMovieClip",!1),zimify(kt.MovieClip.prototype),kt.SVGContainer=function(e,A,B,t,o,n){var r;if(r=zob(kt.SVGContainer,arguments,"svg, splitTypes, geometric, style, group, inherit",this))return r;z_d("50.95"),this.group=o;var i=!1===t?{}:kt.getStyle("SVGContainer",this.group,n);if(zot(e.draggable)){if(!e.getAttribute){a=new DOMParser;e=a.parseFromString(e,"image/svg+xml").documentElement}s=this.svg=e}else var a=new DOMParser,l=(e=e.innerHTML?a.parseFromString(e.innerHTML,"text/xml"):e).getElementsByTagName("svg"),s=this.svg=l?e.getElementsByTagName("svg")[0]:null;if(!zot(s))var c=s.getAttribute("width"),u=s.getAttribute("height");if(c&&(c=Number(c.trim())),u&&(u=Number(u.trim())),this.zimContainer_constructor(c,u),this.type="SVGContainer",!zot(s)){zot(A)&&(A=!0),zot(B)&&(B=!0);var I,S=this,d=black,h=black,g=black,p=black,f=2,m=2,z=1,v=1,y=1,b=1,P=new Point(0,0),w=e.getElementsByTagName("svg");0==w.length&&(w=[e]),function c(e){loop(e,function(e){var t=e.tagName.toLowerCase();if("path"==t&&function(o){var n=["M","m","L","l","H","h","V","v","C","c","S","s","Q","q","T","t","A","a","z","Z"],r=["m","l","h","v","c","s","q","t","a","z"],i=new Point(0,0),e=(o.getAttribute("id"),o.getAttribute("d"));e=(e=(e=(e=e.replace(/,/g," ")).replace(/([a-zA-Z])/g," $1 ")).replace(/-/g," -")).replace(/\s+/g," ");var a,l,s,t=E(o),c=t[0],u=t[1],d=t[2],h=(t[3],t[4],[]),g=[0,0],p=new Point(0,0),f=new Point(0,0,0,0),m=new Point(0,0,0,0,0,0),z=(new Point(0,0,0,0,0,0,0),e.split(" ")),v=z.slice(1,z.length),y=[],b=!1,w="",x=!1,C="squiggle",k=null;function T(e){w=y[y.length-1],2<=h.length&&("z"!=w&&"Z"!=w||(C="blob")),(a="squiggle"==C?new Squiggle(u,d,h):new Blob(c,u,d,h)).loc(0,0,S),w=y[y.length-1],y[y.length-2],0<=r.indexOf(w)?(g[0]=h[h.length-1][0],g[1]=h[h.length-1][1],P.x=h[h.length-1][0],P.y=h[h.length-1][1],(h=[]).push([g[0],g[1]])):(g=[0,0],h=[[0,0]]),y=[],"z"!=w&&"Z"!=w&&y.push(w),i.x=0,i.y=0;var t=o.getAttribute("transform");(t||I)&&M(a,t||I)}loop(v,function(e,t){if(0==t&&(P.x=0,P.y=0,g=[0,0],w=""),-1==n.indexOf(e)){if("lxo"==s&&(s="lx",y.push("l"),b=!0),"lyo"==s&&(s="ly",b=!0),"Lxo"==s&&(s="Lx",y.push("L"),b=!0),"Lyo"==s&&(s="Ly",b=!0),l=Number(e),l=Math.round(100*l)/100,"X"==s?(P.x=l,s="Y"):"Y"==s?(P.y=l,s="Lxo",h.push([P.x,P.y])):"x"==s?(P.x=P.x+l,s="y"):"y"==s&&(P.y=P.y+l,s="lxo",h.push([P.x,P.y])),"H"==s||"h"==s?(i.x=h[h.length-1][0],i.y=h[h.length-1][1],i.x=i.x+("h"==s?l:l-P.x),h.push([i.x,i.y]),s="Lx"):"V"!=s&&"v"!=s||(i.x=h[h.length-1][0],i.y=h[h.length-1][1],i.y=i.y+("v"==s?l:l-P.y),h.push([i.x,i.y]),s="lx"),"Lx"==s?(p.x=l,s="Ly"):"Ly"==s?(p.y=l,i.x=p.x,i.y=p.y,h.push([i.x,i.y]),s="Lx"):"lx"==s?(0<y.length&&(0!=i.x&&0!=i.y?(P.x=i.x,P.y=i.y):(P.x=i.x+P.x,P.y=i.y+P.y)),p.x=P.x+l,s=b?"lyo":"ly"):"ly"==s&&(p.y=P.y+l,i.x=p.x,i.y=p.y,h.push([i.x,i.y]),s="lx"),"qx"==s||"Qx"==s)0<h.length?(P.x=h[h.length-1][0],P.y=h[h.length-1][1]):(P.x=0,P.y=0),f.x="qx"==s?P.x+l:l,s="qx"==s?"qy":"Qy";else if("qy"==s||"Qy"==s){if(f.y="qy"==s?P.y+l:l,s="qy"==s?"qz":"Qz",x){x=!1;var o=h[h.length-1];o[6]=-o[4],o[7]=-o[5],o[8]="mirror",i.x=f.x,i.y=f.y,h[h.length]=[i.x,i.y,0,0,-o[6],o[7],0,0,"free"],s="qy"==s?"qx":"Qx"}}else if("qz"==s||"Qz"==s)f.z="qz"==s?P.x+l:l,s="qz"==s?"qq":"Qq";else if("qq"==s||"Qq"==s){f.w="qq"==s?P.y+l:l;var o=h[h.length-1];i.x=o[0],i.y=o[1],1==h.length?(o[2]=0,o[3]=0,o[4]=0,o[5]=0,o[6]=2/3*(f.x-i.x),o[7]=2/3*(f.y-i.y),o[8]="free"):h[h.length]=[i.x,i.y,0,0,0,0,2/3*(f.x-i.x),2/3*(f.y-i.y),"free"],i.x=f.z,i.y=f.w,h[h.length]=[i.x,i.y,0,0,2/3*(f.x-i.x),2/3*(f.y-i.y),0,0,"free"],s="qq"==s?"qx":"Qx"}if("cx"==s||"Cx"==s)0<h.length?(P.x=h[h.length-1][0],P.y=h[h.length-1][1]):(P.x=0,P.y=0),m.x="cx"==s?P.x+l:l,s="cx"==s?"cy":"Cy";else if("cy"==s||"Cy"==s)m.y="cy"==s?P.y+l:l,s="cy"==s?"cz":"Cz";else if("cz"==s||"Cz"==s)m.z="cz"==s?P.x+l:l,s="cz"==s?"cq":"Cq";else if("cq"==s||"Cq"==s){if(m.q="cq"==s?P.y+l:l,s="cq"==s?"cr":"Cr",x){var o=h[h.length-1];o[2]=0,o[3]=0,zot(o[4])&&(o[4]=0),zot(o[5])&&(o[5]=0),o[6]=-(m.x-m.z),o[7]=-(m.y-m.q),o[8]="mirror",i.x=m.z,i.y=m.q,h[h.length]=[i.x,i.y,0,0,m.x-i.x,m.y-i.y,0,0,"free"],s="cr"==s?"cx":"Cx"}}else if("cr"==s||"Cr"==s)m.r="cr"==s?P.x+l:l,s="cr"==s?"cs":"Cs";else if("cs"==s||"Cs"==s){m.s="cs"==s?P.y+l:l;var o=h[h.length-1];1==h.length&&(o[2]=0,o[3]=0,o[4]=0,o[5]=0),o[6]=m.x-o[0],o[7]=m.y-o[1],o[8]="free",i.x=m.r,i.y=m.s,h[h.length]=[i.x,i.y,0,0,m.z-i.x,m.q-i.y,0,0,"free"],s="cs"==s?"cx":"Cx"}}else y.push(e),"s"!=e&&(x=!1),1<y.length&&("M"!=e&&"m"!=e||(T(y),P.y="M"==e?P.x=0:(P.x=h[h.length-1][0],h[h.length-1][1]),h=[],(y=[]).push(e))),"M"==e?s="X":"m"==e?s="x":"L"==e?(s="Lx",A&&k&&"l"!=k&&T(y),k="l"):"l"==e?(s="lx",A&&k&&"l"!=k&&T(y),k="l"):"H"==e?(s="H",A&&k&&"l"!=k&&T(y),k="l"):"h"==e?(s="h",A&&k&&"l"!=k&&T(y),k="l"):"V"==e?(s="V",A&&k&&"l"!=k&&T(y),k="l"):"v"==e?(s="v",A&&k&&"l"!=k&&T(y),k="l"):"C"==e?(s="Cx",A&&k&&"c"!=k&&T(y),k="c"):"c"==e?(s="cx",A&&k&&"c"!=k&&T(y),k="c"):"S"==e?(x=!0,s="Cx",A&&k&&"c"!=k&&T(y),k="c"):"s"==e?(x=!0,s="cx",A&&k&&"c"!=k&&T(y),k="c"):"Q"==e?(s="Qx",A&&k&&"q"!=k&&T(y),k="q"):"q"==e?(s="qx",A&&k&&"q"!=k&&T(y),k="q"):"T"==e?(x=!0,s="Qx",A&&k&&"q"!=k&&T(y),k="q"):"t"==e?(x=!0,s="qx",A&&k&&"q"!=k&&T(y),k="q"):"A"==e?C=null:"z"!=e&&"Z"!=e||(C="blob")}),T()}(e),"circle"==t&&C("circle",e),"rect"==t&&C("rect",e),"ellipse"==t&&C("ellipse",e),"line"==t&&C("line",e),"polygon"==t&&C("polygon",e),"polyline"==t&&C("polyline",e),"g"==t){var o,n,r,i,a,l=e.getAttribute("style");if(l){var s=x(l);o=s[0],n=s[1],r=s[2],i=s[3],a=s[4]}I=e.getAttribute("transform"),h=e.getAttribute("fill")?e.getAttribute("fill"):zot(o)?d:o,p=e.getAttribute("stroke")?e.getAttribute("stroke"):zot(n)?g:n,m=e.getAttribute("stroke-width")?e.getAttribute("stroke-width"):zot(r)?f:r,v=e.getAttribute("fill-opacity")?e.getAttribute("fill-opacity"):zot(i)?z:i,b=e.getAttribute("stroke-opacity")?e.getAttribute("stroke-opacity"):zot(a)?y:a}c(e.children),"g"==e.tagName.toLowerCase()&&(h=d,p=g,m=f,v=z,b=y,I=null)})}(w),!1!==t&&Oe(this,i),this.clone=function(){return S.cloneProps(new kt.SVGContainer(e,A,B,t,this.group,n))}}function x(e){var r,i,a,l,s,t=e.split(";");return loop(t,function(e){var t=(e=e.replace(/,/g,"")).split(":"),o=t[0].trim().toLowerCase(),n=t[1].trim().toLowerCase().replace("px","");"fill"==o&&(r=n),"stroke"==o&&(i=n),"stroke-width"==o&&(a=n),"opacity"==o&&(s=l=n),"fill-opacity"==o&&(l=n),"stroke-opacity"==o&&(s=n)}),[r,i,a,l,s]}function E(e){var t,o,n,r,i,a=e.getAttribute("style");if(a){var l=x(a);t=l[0],o=l[1],n=l[2],r=l[3],i=l[4]}t=e.getAttribute("fill")?e.getAttribute("fill"):zot(t)?h:t,o=e.getAttribute("stroke")?e.getAttribute("stroke"):zot(o)?p:o,n=e.getAttribute("stroke-width")?e.getAttribute("stroke-width"):zot(n)?m:n,r=e.getAttribute("fill-opacity")?e.getAttribute("fill-opacity"):zot(r)?v:r,i=e.getAttribute("stroke-opacity")?e.getAttribute("stroke-opacity"):zot(i)?b:i;var s=e.getAttribute("x")?e.getAttribute("x"):0;s=e.getAttribute("cx")?e.getAttribute("cx"):s;var c=e.getAttribute("y")?e.getAttribute("y"):0;return c=e.getAttribute("cy")?e.getAttribute("cy"):c,zot(r)||zot(t)||(t=convertColor(t,"rgba",Number(r))),zot(i)||zot(o)||(o=convertColor(o,"rgba",Number(i))),[t,o,Number(n),Number(r),Number(i),Number(s),Number(c)]}function C(e,t){var o,n,r,i,a,l,s,c,u,d=E(t),h=d[0],g=d[1],p=d[2],f=(d[3],d[4],d[5]),m=d[6];if("circle"==e){var z=Number(t.getAttribute("r").trim()),v=.5523*z;o=B?new Circle(Number(t.getAttribute("r")),h,g,p):new Blob(h,g,p,4,z,v,"mirror")}else if("rect"==e)if(B)o=new Rectangle(Number(t.getAttribute("width")),Number(t.getAttribute("height")),h,g,p,Number(t.getAttribute("rx")));else{var y=Number(t.getAttribute("width")),b=Number(t.getAttribute("height")),w=Number(t.getAttribute("rx")),x=Number(t.getAttribute("ry"));if(w&&x){var C=.5523*w,k=.5523*x;o=new Blob(h,g,p,[[w,0,0,0,-C,0,0,0,"free"],[y-w,0,0,0,0,0,C,0,"free"],[y,x,0,0,0,-k,0,0,"free"],[y,b-x,0,0,0,0,0,k,"free"],[y-w,b,0,0,C,0,0,0,"free"],[w,b,0,0,0,0,-C,0,"free"],[0,b-x,0,0,0,k,0,0,"free"],[0,x,0,0,0,0,0,-k,"free"]])}else o=new Blob(h,g,p,[[0,0],[y,0],[y,b],[0,b]])}else if("line"==e)o=new Squiggle(g,p,[[Number(t.getAttribute("x1")),Number(t.getAttribute("y1"))],[Number(t.getAttribute("x2")),Number(t.getAttribute("y2"))]]);else if("polygon"==e||"polyline"==e){var T=t.getAttribute("points");T=(T=T.replace(/-/g," -")).replace(/\s+/g," ");var A=[];loop(T.split(" "),function(e){var t=e.split(",");A.push([Number(t[0].trim()),Number(t[1].trim())])}),o="polygon"==e?new Blob(h,g,p,A):new Squiggle(g,p,A)}else"ellipse"==e&&(o=new Blob(h,g,p,(r=n=0,i=Number(t.getAttribute("rx")),a=Number(t.getAttribute("ry")),[[n-i,r,0,0,n,(u=r+a)+(s=.5522848*a)-a,n,r-s,"mirror"],[n,r-a,0,0,n-(l=.5522848*i),r,(c=n+i)+l-i,r,"mirror"],[c,r,0,0,n,r-s,n+l-l,u+s-a,"mirror"],[n,u,0,0,c-i+l,r,n-l,r,"mirror"]])));o.loc(f,m,S);var P=t.getAttribute("transform");(P||I)&&M(o,P||I),"Rectangle"!=o.type&&"Circle"!=o.type||o.transform({showReg:!1})}function M(l,e){var t=e.split(")");loop(t,function(e){if(""!=e){var t=e.trim().split("("),o=t[0].trim().toLowerCase(),n=t[1].trim().toLowerCase().replace("px","").replace("deg","");if("translate"==o){var r=n.split(",");l.mov(Number(r[0].trim()),r[1]?Number(r[1].trim()):0)}if("scale"==o){var i=n.split(",");"Blob"==l.type||"Squiggle"==l.type?1==i.length?l.transformPoints("scale",Number(i[0].trim())):2==i.length&&(l.transformPoints("scaleX",Number(i[0].trim())),l.transformPoints("scaleY",Number(i[1].trim()))):1==i.length?l.sca(Number(i[0].trim())):2==i.length&&l.sca(Number(i[0].trim()),Number(i[1].trim()))}if("rotate"==o){var a=n.split(",");1==a.length?a.push(0,0):2==a.length&&a.push(0),l.rot(Number(a[0].trim()),Number(a[1].trim()),Number(a[2].trim()))}"skewX"==o&&(l.skewX=n),"skewY"==o&&(l.skewY=n)}})}},kt.extend(kt.SVGContainer,kt.Container,"clone","zimContainer",!1),kt.Circle=function(e,t,o,n,r,i,a,l,s){var c;if(c=zob(kt.Circle,arguments,"radius, color, borderColor, borderWidth, dashed, percent, style, group, inherit",this))return c;z_d("51"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Circle",this.group=l;var u=!1===a?{}:kt.getStyle(this.type,this.group,s);zot(e)&&(e=null!=u.radius?u.radius:50),zot(r)&&(r=null!=u.dashed&&u.dashed),zot(o)&&(o=null!=u.borderColor?u.borderColor:null),zot(n)&&(n=null!=u.borderWidth?u.borderWidth:null),o<0||n<0?o=n=null:null!=o&&null==n&&(n=1),zot(t)&&(t=null!=u.color?u.color:0<n?"rgba(0,0,0,0)":"black"),zot(i)&&(i=null!=u.percent?u.percent:100);var d=function(){return arguments}(e,t,o,n,i);e=kt.Pick.choose(e),t=kt.Pick.choose(t),o=kt.Pick.choose(o),n=kt.Pick.choose(n),i=kt.Pick.choose(i);var h=this,g=e,p=t,f=o,m=n;this.mouseChildren=!1;var z=this.shape=new createjs.Shape;this.addChild(z);var v,y,b,w,x,C,k=z.graphics;function T(){k.c(),h.colorCommand=v=k.f(p).command,(zot(m)||0<m)&&(zot(f)&&zot(m)||(zot(f)&&(f="black"),h.borderColorCommand=y=k.s(f).command,h.borderWidthCommand=b=k.ss(m).command,r&&(h.borderDashedCommand=w=k.sd([10,10],5).command)));var e=2*g;if("number"==typeof i&&0<=i&&i<100){var t=360*i/100/2;k.arc(0,0,g,(-t-90)*Math.PI/180,(t-90)*Math.PI/180,!1).cp(),e=g-Math.cos(t*Math.PI/180)*g}else k.dc(0,0,g);h.setBounds(-g,-g,2*g,e)}T(),Object.defineProperty(h,"color",{get:function(){return p},set:function(e){zot(e)&&(e="black"),p=e,v.style=p}}),this.setColorRange=function(e,t){return C=zot(t)?(x=h.color,e):(x=zot(e)?h.color:e,t),h};var A=0;Object.defineProperty(h,"colorRange",{get:function(){return A},set:function(e){A=e,zot(x)||zot(C)||(h.color=kt.colorRange(x,C,e))}}),Object.defineProperty(h,"borderColor",{get:function(){return f},set:function(e){f=e,y?y.style=f:T()}}),Object.defineProperty(h,"borderWidth",{get:function(){return m},set:function(e){0<e||(e=0),m=e,b&&0!=m?(b.width=m,r&&(w.segments=[20,10],w.offset=5)):T()}}),Object.defineProperty(h,"radius",{get:function(){return g},set:function(e){g=e,T()}}),!1!==a&&Oe(this,u),this.clone=function(e){return h.cloneProps(e?new kt.Circle(h.radius,h.color,h.borderColor,h.borderWidth,r,i,a,this.group,s):new kt.Circle(d[0],d[1],d[2],d[3],r,d[4],a,this.group,s))}},kt.extend(kt.Circle,kt.Container,"clone","zimContainer",!1),kt.Rectangle=function(t,o,e,n,r,i,a,l,s,c){var u;if(u=zob(kt.Rectangle,arguments,"width, height, color, borderColor, borderWidth, corner, dashed, style, group, inherit",this))return u;z_d("52"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Rectangle",this.group=s;var d=!1===l?{}:kt.getStyle(this.type,this.group,c);zot(t)&&(t=null!=d.width?d.width:null),zot(o)&&(o=null!=d.height?d.height:zot(t)?100:t),zot(t)&&(t=o),zot(i)&&(i=null!=d.corner?d.corner:0),zot(a)&&(a=null!=d.dashed&&d.dashed),zot(n)&&(n=null!=d.borderColor?d.borderColor:null),zot(r)&&(r=null!=d.borderWidth?d.borderWidth:null),n<0||r<0?n=r=null:null!=n&&null==r&&(r=1),zot(e)&&(e=null!=d.color?d.color:0<r?"rgba(0,0,0,0)":"black");var h=function(){return arguments}(t,o,e,n,r);t=kt.Pick.choose(t),o=kt.Pick.choose(o),e=kt.Pick.choose(e),n=kt.Pick.choose(n),r=kt.Pick.choose(r);var g=this,p=e,f=n,m=r;this.mouseChildren=!1;var z=this.shape=new createjs.Shape;this.addChild(z);var v,y,b,w,x,C=z.graphics;function k(){C.c(),g.colorCommand=v=C.f(p).command,(zot(m)||0<m)&&(zot(f)&&zot(m)||(zot(f)&&(f="black"),g.borderColorCommand=y=C.s(f).command,g.borderWidthCommand=b=C.ss(m).command,a&&(g.borderDashedCommand=borderDashedObj=C.sd([10,10],5).command))),Array.isArray(i)?C.rc(0,0,t,o,i[0],i[1],i[2],i[3]):0<i?C.rr(0,0,t,o,i):C.r(0,0,t,o),g.setBounds(0,0,t,o)}k(),Object.defineProperty(g,"color",{get:function(){return p},set:function(e){zot(e)&&(e="black"),p=e,v.style=p}}),this.setColorRange=function(e,t){return x=zot(t)?(w=g.color,e):(w=zot(e)?g.color:e,t),g};var T=0;Object.defineProperty(g,"colorRange",{get:function(){return T},set:function(e){T=e,zot(w)||zot(x)||(g.color=kt.colorRange(w,x,e))}}),Object.defineProperty(g,"borderColor",{get:function(){return f},set:function(e){f=e,y?y.style=f:k()}}),Object.defineProperty(g,"borderWidth",{get:function(){return m},set:function(e){0<e||(e=0),m=e,b&&0!=m?(b.width=m,a&&(borderDashedObj.segments=[20,10],borderDashedObj.offset=5)):k()}}),!1!==l&&Oe(this,d),this.clone=function(e){return g.cloneProps(e?new kt.Rectangle(t,o,g.color,g.borderColor,g.borderWidth,i,a,l,this.group,c):new kt.Rectangle(h[0],h[1],h[2],h[3],h[4],i,a,l,this.group,c))}},kt.extend(kt.Rectangle,kt.Container,"clone","zimContainer",!1),kt.Triangle=function(s,c,t,e,o,n,u,d,h,r,i,a){var l;if(l=zob(kt.Triangle,arguments,"a, b, c, color, borderColor, borderWidth, center, adjust, dashed, style, group, inherit",this))return l;z_d("53"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Triangle",this.group=i;var g=!1===r?{}:kt.getStyle(this.type,this.group,a);zot(s)&&(s=null!=g.a?g.a:100),zot(c)&&(c=null!=g.b?g.b:s),zot(t)&&(t=null!=g.c?g.c:c),-1==t&&(t=Math.sqrt(Math.pow(s,2)+Math.pow(c,2))),zot(u)&&(u=null==g.center||g.center),zot(d)&&(d=null!=g.adjust?g.adjust:0),zot(o)&&(o=null!=g.borderColor?g.borderColor:null),zot(n)&&(n=null!=g.borderWidth?g.borderWidth:null),o<0||n<0?o=n=null:null!=o&&null==n&&(n=1),zot(e)&&(e=null!=g.color?g.color:0<n?"rgba(0,0,0,0)":"black");var p=function(){return arguments}(s,c,t,e,o,n);s=kt.Pick.choose(s),c=kt.Pick.choose(c),t=kt.Pick.choose(t),this.a=s,this.b=c,this.c=t,e=kt.Pick.choose(e),o=kt.Pick.choose(o),n=kt.Pick.choose(n);var f=this,m=e,z=o,v=n;this.mouseChildren=!1;var y=[s,c,t];y.sort(function(e,t){return t-e});var b=y[0],w=y[1],x=y[2],C=[y.indexOf(s),y.indexOf(c),y.indexOf(t)];if(w+x<b)zog("zim display - Triangle(): invalid triangle lengths");else{var k=this.shape=new createjs.Shape;this.addChild(k);var T,A,P,B,I,S=k.graphics;M(),Object.defineProperty(f,"color",{get:function(){return m},set:function(e){zot(e)&&(e="black"),m=e,T.style=m}}),this.setColorRange=function(e,t){return I=zot(t)?(B=f.color,e):(B=zot(e)?f.color:e,t),f};var E=0;Object.defineProperty(f,"colorRange",{get:function(){return E},set:function(e){E=e,zot(B)||zot(I)||(f.color=kt.colorRange(B,I,e))}}),Object.defineProperty(f,"borderColor",{get:function(){return z},set:function(e){z=e,A?A.style=z:M()}}),Object.defineProperty(f,"borderWidth",{get:function(){return v},set:function(e){0<e||(e=0),v=e,P&&0!=v?(P.width=v,h&&(borderDashedObj.segments=[20,10],borderDashedObj.offset=5)):M()}}),!1!==r&&Oe(this,g),this.clone=function(e){return f.cloneProps(e?new kt.Triangle(s,c,t,f.color,f.borderColor,f.borderWidth,u,d,h,r,this.group,a):new kt.Triangle(p[0],p[1],p[2],p[3],p[4],p[5],u,d,h,r,this.group,a))}}function M(){S.c(),f.colorCommand=T=S.f(m).command,(zot(v)||0<v)&&(zot(z)&&zot(v)||(zot(z)&&(z="black"),f.borderColorCommand=A=S.s(z).command,f.borderWidthCommand=P=S.ss(v).command,h&&(f.borderDashedCommand=borderDashedObj=S.sd([10,10],5).command))),S.mt(0,0),f.one={x:0,y:0},S.lt(s,0),f.two={x:s,y:0};var e=180*Math.acos((Math.pow(w,2)+Math.pow(x,2)-Math.pow(b,2))/(2*w*x))/Math.PI,t=180*Math.asin(w*Math.sin(e*Math.PI/180)/b)/Math.PI,o=[e,t,180-e-t];f.angles=[o[C[1]],o[C[2]],o[C[0]]];var n=f.angles[1],r=Math.cos(n*Math.PI/180)*c,i=Math.sin(n*Math.PI/180)*c,a=Math.max(s,s-r),l=i;f.setBounds(0,0,a,l),k.y=l,S.lt(s-r,0-i),f.three={x:s-r,y:0-i},S.cp(),u&&(f.regX=a/2,f.regY=l/2),d&&(f.shape.y+=d)}},kt.extend(kt.Triangle,kt.Container,"clone","zimContainer"),kt.Squiggle=function(e,k,T,A,P,B,I,S,E,M,t,O,j,D,L,Y,o,n,r,X,i,R){var a;if(a=zob(kt.Squiggle,arguments,"color, thickness, points, length, controlLength, controlType, lockControlType, showControls, lockControls, handleSize, allowToggle, move, dashed, onTop, stickColor, selectColor, selectPoints, editPoints, interactive, style, group, inherit",this))return a;z_d("53.2"),this.group=i;var _=!1===X?{}:kt.getStyle("Squiggle",this.group,R);zot(k)&&(k=null!=_.thickness?_.thickness:6),zot(A)&&(A=null!=_.length?_.length:300),zot(T)&&(T=null!=_.points?_.points:5);var W="number"==typeof T?T:T.length;if(0!=W){zot(P)&&(P=null!=_.controlLength?_.controlLength:A/W),this.zimContainer_constructor(A,P,null,null,!1),this.type="Squiggle",zot(j)&&(j=null!=_.dashed&&_.dashed),zot(e)&&(e=null!=_.color?_.color:kt.blue),e.style&&(this.colorCommand=e,e="black"),zot(B)&&(B=null!=_.controlType?_.controlType:"mirror"),zot(I)&&(I=null!=_.lockControlType&&_.lockControlType),zot(r)&&(r=null==_.interactive||_.interactive),zot(S)&&(S=null!=_.showControls?_.showControls:r);var F=S;zot(E)&&(E=null!=_.lockControls?_.lockControls:!r),zot(M)&&(M=null!=_.handleSize?_.handleSize:kt.mobile()?20:10),zot(t)&&(t=null!=_.allowToggle?_.allowToggle:r),zot(O)&&(O=null!=_.move?_.move:r),zot(L)&&(L=null!=_.stickColor?_.stickColor:"#111"),zot(Y)&&(Y=null!=_.selectColor?_.selectColor:"#fff"),zot(o)&&(o=null!=_.selectPoints?_.selectPoints:r),this.stickColor=L,zot(D)&&(D=null==_.onTop||_.onTop),zot(n)&&(n=null!=_.editPoints?_.editPoints:r);var H,V,N,G=this;this.types=["mirror","straight","free","none"];this.interactive=r,this.num=W,this.onTop=D,this.move=O,this.editPoints=n,this.allowToggle=t,this.lockControlType=I,this.selectPoints=o,this.lockControls=E;var q,U,K,Z,Q,J,$,ee,te,oe,ne=e,re=k,l=G.move,ie=2;h(),G.selectionManager.on("keydown",function(e){if(G.selectPoints&&G.keyFocus&&37<=e.keyCode&&e.keyCode<=40){var t=ae();if(0<t.length){for(var o=0;o<t.length;o++){var n=t[o];37==e.keyCode?n.x-=G.selectionManager.shiftKey?10:1:39==e.keyCode?n.x+=G.selectionManager.shiftKey?10:1:38==e.keyCode?n.y-=G.selectionManager.shiftKey?10:1:40==e.keyCode&&(n.y+=G.selectionManager.shiftKey?10:1),ee(n)}te(),G.stage&&G.stage.update()}}}),G.selectionManager.on("keyup",function(e){if(G.selectPoints&&G.keyFocus&&37<=e.keyCode&&e.keyCode<=40){var t=ae();if(0<t.length)for(var o=0;o<t.length;o++)le(t[o])}}),G.selectionManager.on("undo",function(){if(G.selectPoints&&G.keyFocus&&G.lastPoints){var e=kt.copy(G.lastPoints);G.lastPoints=kt.copy(G.points),G.points=e,G.stage&&G.stage.update()}}),ee=function(e){if(!G.lockControls)if(e.rect1){var t=(n=e).x-n.startX,o=n.y-n.startY;n.rect1.x=n.rect1.startX+t,n.rect1.y=n.rect1.startY+o,n.rect2.x=n.rect2.startX+t,n.rect2.y=n.rect2.startY+o}else{var n,r=e,i=r.other,a=(n=r.ball).index,l=B;if(zot(H[a][4])||(l=H[a][4]),"straight"==l||"mirror"==l){var s=r.x-n.x,c=r.y-n.y;if("mirror"==l)i.x=n.x-s,i.y=n.y-c;else{var u=Math.atan2(c,s),d=-i.stickLength*Math.cos(u+Math.PI),h=-i.stickLength*Math.sin(u+Math.PI);i.x=n.x-d,i.y=n.y-h}}}},Object.defineProperty(G,"move",{get:function(){return O},set:function(e){O!=e&&((O=e)?se():ce())}}),Object.defineProperty(G,"interactive",{get:function(){return r},set:function(e){r=e,G.showControls=r,G.allowToggle=r,G.editPoints=r,G.lockControls=!r,G.selectPoints=r,G.move=r,G.points=G.points}}),Object.defineProperty(G,"allowToggle",{get:function(){return t},set:function(e){t!=e&&((t=e)?G.move&&se():!F&&G.move&&ce())}});var s,c,u=E;Object.defineProperty(G,"lockControls",{get:function(){return u},set:function(e){u=e,G.controls.mouseEnabled=e?G.controls.mouseChildren=!1:G.controls.mouseChildren=!0}}),G.lockControls=u,Object.defineProperty(G,"controlsVisible",{get:function(){return F},set:function(e){(F=e)?G.showControls():G.hideControls()}}),Object.defineProperty(G,"color",{get:function(){return ne},set:function(e){zot(e)&&(e="black"),ne=e,q.style=ne}}),this.setColorRange=function(e,t){return c=zot(t)?(s=G.color,e):(s=zot(e)?G.color:e,t),G};var d=0;Object.defineProperty(G,"colorRange",{get:function(){return d},set:function(e){d=e,zot(s)||zot(c)||(G.color=kt.colorRange(s,c,e))}}),Object.defineProperty(G,"thickness",{get:function(){return re},set:function(e){0<e||(e=0),re=e,U&&0!=re?(U.width=re,j&&(K.segments=[20,10],K.offset=5)):te()}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==G},set:function(e){kt.KEYFOCUS=G}}),kt.KEYFOCUS||function(){if(!G.selectPoints)return;G.keyFocus=!0;var e=document.activeElement;e&&e.blur()}(),Object.defineProperty(G,"points",{get:function(){for(var e,t,o=[],n=0;n<H.length;n++)t=H[n],e=[kt.decimals(t[0].x),kt.decimals(t[0].y),kt.decimals(t[1].x),kt.decimals(t[1].y),kt.decimals(t[2].x),kt.decimals(t[2].y),kt.decimals(t[3].x),kt.decimals(t[3].y)],t[4]&&"mirror"!==t[4]&&e.push(t[4]),o.push(e);return o},set:function(e){G.dispose(!0),T=e,G.shape&&(G.shape.graphics.clear(),G.sticks.graphics.clear(),G.controls.noDrag(),G.removeAllChildren(),delete G.shape,delete G.sticks,delete G.controls),h(),G.lockControls=u}}),Object.defineProperty(G,"pointsAdjusted",{get:function(){var r,i,a=[],l=G.pointObjects;return kt.loop(l.length,function(e,t){if(po=l[e],i=H[e],0==po[0].rotation&&0==po[0].scaleX&&0==po[0].scaleY)r=[kt.decimals(i[0].x),kt.decimals(i[0].y),kt.decimals(i[1].x),kt.decimals(i[1].y),kt.decimals(i[2].x),kt.decimals(i[2].y),kt.decimals(i[3].x),kt.decimals(i[3].y)];else{var o=po[0].localToLocal(po[2].x,po[2].y,po[0].parent),n=po[0].localToLocal(po[3].x,po[3].y,po[0].parent);r=[kt.decimals(i[0].x),kt.decimals(i[0].y),kt.decimals(i[1].x),kt.decimals(i[1].y),kt.decimals(o.x-i[0].x),kt.decimals(o.y-i[0].y),kt.decimals(n.x-i[0].x),kt.decimals(n.y-i[0].y)]}i[4]&&"mirror"!==i[4]&&r.push(i[4]),a.push(r)}),a},set:function(e){zon&&zog("Squiggle() - pointsAdjusted is read only")}}),Object.defineProperty(G,"pointObjects",{get:function(){return H},set:function(e){zon&&zog("Squiggle() - pointObjects is read only - but its contents can be manipulated - use squiggle.update() after changes")}}),Object.defineProperty(G,"pointControls",{get:function(){return N},set:function(e){zon&&zog("Squiggle() - pointControls is read only - but its contents can be manipulated - use blob.update() after changes")}}),Object.defineProperty(G,"pointCircles",{get:function(){return V},set:function(e){zon&&zog("Squiggle() - pointCircles is read only - but its contents can be manipulated - use blob.update() after changes")}}),Object.defineProperty(G,"segmentPoints",{get:function(){var n=[],r=G.pointsAdjusted;return kt.loop(r.length-1,function(e,t){var o=G.getSegmentPoint(r[e],r[e+1]);n.push(o)}),n},set:function(e){zon&&zog("Squiggle() - segmentPoints is read only")}}),Object.defineProperty(G,"segmentRatios",{get:function(){var o=[],n=0;kt.loop(G.segmentPoints,function(e){var t=kt.distanceAlongCurve(e);o.push(t),n+=t});var t=[],r=0;return kt.loop(o,function(e){r+=e/n,t.push(r)}),t},set:function(e){zon&&zog("Squiggle() - segmentRatios is read only")}}),G.getPointAngle=function(e){var t=G.pointObjects[e][0],o=G.pointObjects[e][2],n=G.pointObjects[e][3],r=t.localToGlobal(o.x,o.y),i=t.localToGlobal(n.x,n.y);return kt.angle(r.x,r.y,i.x,i.y)},G.getSegmentPoint=function(e,t){if(!zot(e)&&!zot(t)){0==e[2]&&0==e[3]||(e[4]-=e[2],e[5]-=e[3],e[6]-=e[2],e[7]-=e[3],e[0]+=e[2],e[1]+=e[3],e[2]=0,e[3]=0),0==t[2]&&0==t[3]||(t[4]-=t[2],t[5]-=t[3],t[6]-=t[2],t[7]-=t[3],t[0]+=t[2],t[1]+=t[3],t[2]=0,t[3]=0);var o={x:e[0],y:e[1]},n={x:e[0]+e[6],y:e[1]+e[7]},r={x:t[0]+t[4],y:t[1]+t[5]},i={x:t[0],y:t[1]};return 0==oe.x&&0==oe.y||(o.x+=oe.x,n.x+=oe.x,r.x+=oe.x,i.x+=oe.x,o.y+=oe.y,n.y+=oe.y,r.y+=oe.y,i.y+=oe.y),[o,n,r,i]}},G.getAdjacentSegmentData=function(e){zot(e)&&(e=0);var t=G.pointsAdjusted;return 2==G.num?[[G.getSegmentPoint(t[0],t[1])],[0]]:0==e?[[G.getSegmentPoint(t[0],t[1]),G.getSegmentPoint(t[1],t[2])],[0,1]]:e>=G.num-2?[[G.getSegmentPoint(t[G.num-3],t[G.num-2]),G.getSegmentPoint(t[G.num-2],t[G.num-1])],[G.num-3,G.num-2]]:[[G.getSegmentPoint(t[e-1],t[e]),G.getSegmentPoint(t[e],t[e+1]),G.getSegmentPoint(t[e+1],t[e+2])],[e-1,e,e+1]]},G.getCurvePoint=function(o,e,t,n){(zot(o)||isNaN(o))&&(o=0),zot(e)&&(e=G.segmentRatios),zot(t)&&(t=G.segmentPoints),zot(n)&&(n=!1);var r=e,i=t,a=kt.loop(r,function(e,t){if(o<=e)return t}),l=0<a?r[a-1]:0,s=0<a?r[a]-r[a-1]:r[a];if(s){var c=(o-l)/s,u=kt.pointAlongCurve(i[a],c,n),d=G.localToGlobal(u.x,u.y);return d.angle=u.angle,d.z=a,zot(d)?void 0:d}},this.dispose=function(e){if(G.shape){G.shape.cursor="default";for(var t=0;t<G.points.length;t++)G.pointObjects[t][1].removeAllEventListeners();for(t=0;t<V.length;t++)V[t].removeAllEventListeners();G.sticks.removeFrom(G),G.controls.removeFrom(G),G.shape.removeAllEventListeners(),G.controls.removeAllEventListeners(),G.off("mousedown",G.toggleEvent),G.off("click",G.clickEvent),G.toggleStageEvent&&G.stage.off("stagemousedown",G.toggleStageEvent),!e&&G.selectPoints&&G.selectionManager.removeAllEventListeners()}}}function h(){oe&&oe.removeAllEventListeners(),G.num=W="number"==typeof T?T:T.length,W=Math.max(2,W),P=A/W,Z=G.shape=new kt.Shape({style:!1}).addTo(G);var n=G.sticks=new kt.Shape({style:!1}).addTo(G);M<=0&&n.removeFrom();var m=Z.graphics;m.c();var z=n.graphics;z.c();var e=M/10*8,t=M;G.selectPoints?(G.selectedBalls=new kt.SelectionSet,G.selectedRect1s=new kt.SelectionSet,G.selectedRect2s=new kt.SelectionSet,G.selectionManager=new kt.SelectionManager([G.selectedBalls,G.selectedRect1s,G.selectedRect2s],"ctrl",!1)):G.selectionManager=new kt.SelectionManager(null,"ctrl");var o,r,i,a,l,s,c,u,d=kt.mobile();oe=G.controls=new kt.Container({style:!1}).addTo(G),G.interactive&&oe.drag({onTop:!d}),H=[],N=[],V=[];for(var h=0;h<W;h++){if((i=new kt.Container({style:!1}).addTo(oe)).num=h,"number"==typeof T){var g=kt.Pick.choose(P);r=new kt.Container(g,k,null,null,!1).addTo(G).loc({x:h*A/(W-1)-g/2,y:h%2*g}),s=new kt.Circle(e,G.selectPoints&&G.selectedBalls.isSelected(h)?Y:kt.light,kt.dark,2,null,null,!1).centerReg(r).loc({x:g/2,y:0}),a=new kt.Rectangle(t,t,G.selectPoints&&G.selectedRect1s.isSelected(h)?Y:C(B),0==M?null:kt.dark,0==M?null:2,null,null,!1).centerReg(r).loc({x:0,y:0}),l=new kt.Rectangle(t,t,G.selectPoints&&G.selectedRect2s.isSelected(h)?Y:C(B),0==M?null:kt.dark,0==M?null:2,null,null,!1).centerReg(r).loc({x:g,y:0});var p=r.localToLocal(s.x,s.y,oe);s.x=p.x,s.y=p.y,s.addTo(i,null,!1);var f=r.localToLocal(a.x,a.y,oe);a.x="none"==B?0:f.x-s.x,a.y="none"==B?0:f.y-s.y,a.addTo(i,null,!1);var v=r.localToLocal(l.x,l.y,oe);l.x="none"==B?0:v.x-s.x,l.y="none"==B?0:v.y-s.y,l.addTo(i,null,!1),i.x=s.x,i.y=s.y,s.x=0,s.y=0,"none"==B&&s.addTo(i,null,!1)}else c=(u=T[h])[8]?u[8]:B,i.loc({x:u[0],y:u[1]}),s=new kt.Circle(e,kt.light,kt.dark,2,null,null,!1).centerReg(i).loc({x:u[2],y:u[3]}),a=new kt.Rectangle(t,t,C(c),0==M?null:kt.dark,0==M?null:2,null,null,!1).centerReg(i,0).loc({x:u[4],y:u[5]}),l=new kt.Rectangle(t,t,C(c),0==M?null:kt.dark,0==M?null:2,null,null,!1).centerReg(i,0).loc({x:u[6],y:u[7]});s.mySet=i,s.rect1=a,s.rect2=l,s.index=h,d?s.on("mousedown",w):s.on("dblclick",x),a.ball=s,(a.other=l).ball=s,l.other=a,0==M&&(s.expand(10),a.expand(10),l.expand(10)),d&&(s.expand(),a.expand(),l.expand()),o=[i,s,a,l,u?u[8]:B],H.push(o),V.push(s),N.push(i)}var y,b=!1;function w(e){b?(e.preventDefault(),x(e)):(b=!0,setTimeout(function(){b=!1},300))}function x(e){if(!G.lockControlType){var t=e.target,o=H[t.index][4]?H[t.index][4]:B;Math.abs(t.rect1.x)<=2&&Math.abs(t.rect1.y)<=2&&Math.abs(t.rect2.x)<=2&&Math.abs(t.rect2.y)<=2&&(o="none"),"none"==o&&t.parent.addChildAt(t,0),"none"==(o=G.types[(G.types.indexOf(o)+(G.shiftKey?-1:1)+G.types.length)%G.types.length])&&(t.rect1.x=t.rect1.y=t.rect2.x=t.rect2.y=0,t.parent.addChild(t),e.stopImmediatePropagation()),H[t.index][4]=o,t.rect1.color=C(o),t.rect2.color=C(o),te();var n=new createjs.Event("change");n.controlType="bezierSwitch",G.dispatchEvent(n),t.stage.update()}}function C(e){var t={straight:kt.pink,free:kt.yellow,none:kt.blue};return t[e]?t[e]:kt.purple}(te=function(){m.c();var e=kt.mobile()?10:6;if(k<e){m.s("rgba(0,0,0,.01)").ss(e);var t=(i=H[0][0]).localToLocal(H[0][1].x,H[0][1].y,Z);m.mt(t.x,t.y);for(var o=0;o<H.length;o++){var n=o,r=(o+1)%H.length,i=H[n][0],a=H[n][1],l=H[n][2],s=H[n][3],c=H[r][0],u=H[r][1],d=H[r][2],h=(H[r][3],i.localToLocal(s.x,s.y,Z)),g=c.localToLocal(d.x,d.y,Z),p=c.localToLocal(u.x,u.y,Z);o!=H.length-1&&m.bt(h.x,h.y,g.x,g.y,p.x,p.y)}}G.colorCommand||(G.colorCommand=q=m.s(ne).command),G.thicknessCommand||(G.thicknessCommand=U=m.ss(re).command),j&&(G.dashedCommand||(G.dashedCommand=K=m.sd([10,10],5).command)),t=(i=H[0][0]).localToLocal(H[0][1].x,H[0][1].y,Z),m.mt(t.x,t.y),z.c().s(G.stickColor).ss(1);for(o=0;o<H.length;o++){n=o,r=(o+1)%H.length,i=H[n][0],a=H[n][1],l=H[n][2],s=H[n][3],c=H[r][0],u=H[r][1],d=H[r][2],H[r][3],h=i.localToLocal(s.x,s.y,Z),g=c.localToLocal(d.x,d.y,Z),p=c.localToLocal(u.x,u.y,Z);o!=H.length-1&&m.bt(h.x,h.y,g.x,g.y,p.x,p.y);t=i.localToLocal(a.x,a.y,Z);var f=i.localToLocal(l.x,l.y,Z);0==o&&(l.visible=0),0!=o&&z.mt(t.x,t.y).lt(f.x,f.y),o!=H.length-1&&z.mt(t.x,t.y).lt(h.x,h.y),o==H.length-1&&(s.visible=0)}j&&m.append(G.dashedCommand),m.append(G.thicknessCommand),m.append(G.colorCommand)})(),oe.on("mousedown",function(e){if(!G.lockControls){if(G.selectPoints&&(G.keyFocus=!0),y={x:e.target.x,y:e.target.y},e.target.rect1){(o=e.target).startX=o.x,o.startY=o.y,o.rect1.startX=o.rect1.x,o.rect1.startY=o.rect1.y,o.rect2.startX=o.rect2.x,o.rect2.startY=o.rect2.y}else{var t=e.target;t.startX=t.x,t.startY=t.y;var o,n=(o=t.ball).index,r=B;if(zot(H[n][4])||(r=H[n][4]),"straight"==r){var i=t.other,a=i.x-o.x,l=i.y-o.y;i.stickLength=Math.sqrt(Math.pow(a,2)+Math.pow(l,2))}}if(G.selectPoints){var s=G.selectionManager.currentSet;if(s&&s.selections&&0<s.selections.length)for(var c=0;c<s.selections.length;c++){var u=G.pointObjects[s.selections[c]];u[1].startX=u[1].x,u[1].startY=u[1].y,u[2].startX=u[2].x,u[2].startY=u[2].y,u[3].startX=u[3].x,u[3].startY=u[3].y}}}}),G.selectPoints&&oe.tap(function(e){if(e.target.rect1){var t=e.target;G.selectedBalls.toggle(t.parent.num)}else{var o=e.target;o.color="white",(t=o.ball).rect1==o?G.selectedRect1s.toggle(t.parent.num):G.selectedRect2s.toggle(t.parent.num)}for(var n=0;n<G.pointObjects.length;n++){var r=G.pointObjects[n];r[1].color=G.selectedBalls.isSelected(n)?kt.white:kt.light,r[2].color=G.selectedRect1s.isSelected(n)?kt.white:C(r[4]),r[3].color=G.selectedRect2s.isSelected(n)?kt.white:C(r[4])}e.target.stage.update()}),oe.on("pressmove",function(e){if(!G.lockControls)if(G.selectPoints){var t=ae();if(-1==t.indexOf(e.target))ee(e.target),te();else if(0<t.length){diffX=e.target.x-e.target.startX,diffY=e.target.y-e.target.startY;for(var o=0;o<t.length;o++){var n=t[o];n.x=n.startX+diffX,n.y=n.startY+diffY,ee(n)}te()}}else ee(e.target),te()}),oe.on("pressup",function(e){if(!G.lockControls){var t=e.target.x!=y.x||e.target.y!=y.y,o=new createjs.Event("change");e.target.rect1?(o.controlType="bezierPoint",function(e){if(G.selectPoints){var t=ae();if(t&&-1==t.indexOf(e))le(e);else if(t&&0<t.length)for(var o=0;o<t.length;o++)le(t[o]);else le(e)}else le(e)}(e.target)):o.controlType="bezierHandle",t&&G.dispatchEvent(o)}}),G.changeControl=function(e,t,o,n,r,i,a,l,s){var c;if(c=zob(G.changeControl,arguments,"index, type, rect1X, rect1Y, rect2X, rect2Y, circleX, circleY, update"))return c;if(zot(e))for(var u=0;u<H.length;u++)G.changeControl(u,t,o,n,r,i,a,l);else{var d=H[e];"none"==(d[4]=t)?(zot(a)||(d[2].x=a),zot(l)||(d[2].y=l),d[2].x=d[1].x,d[2].y=d[1].y,d[3].x=d[1].x,d[3].y=d[1].y,d[1].parent.addChild(d[1])):(zot(o)||(d[2].x=o),zot(n)||(d[2].y=n),zot(r)||(d[3].x=r),zot(i)||(d[3].y=i),zot(a)||(d[1].x=a),zot(l)||(d[1].y=l),d[1].parent.addChildAt(d[1],0)),s&&(G.update(),G.stage&&G.stage.update())}},G.transformPoints=function(e,t,o,n){return G.points=kt.transformPoints(G.points,e,t,o,n),G},G.update=function(){return normalize?G.points=G.pointsAdjusted:te(),G},G.interactive&&(O&&Z.drag({onTop:!1}),Q=Z.on("mousedown",function(){y={x:Z.x,y:Z.y},G.selectPoints&&(G.keyFocus=!0),function(){if(G.onTop){var e=G.parent.numChildren-1;"Keyboard"==G.parent.getChildAt(e).type&&e--,G.parent.setChildIndex(G,e)}}()}),J=Z.on("pressmove",function(){oe.x=Z.x,oe.y=Z.y,n.x=Z.x,n.y=Z.y}),$=Z.on("pressup",function(){var e=Z.x!=y.x||Z.y!=y.y,t=Z.localToLocal(0,0,G.parent);if(G.x=t.x,G.y=t.y,oe.x=oe.y=n.x=n.y=Z.x=Z.y=0,e){var o=new createjs.Event("change");o.controlType="move",G.dispatchEvent(o)}G.stage.update()}),G.move||ce(!0)),G.toggleEvent=G.on("mousedown",function(){G.allowToggle&&(F||(G.showControls(),G.dispatchEvent("controlsshow")))}),G.added(function(){G.toggleStageEvent=G.stage.on("stagemousedown",function(e){G.allowToggle&&G.stage&&F&&!G.hitTestPoint(e.stageX,e.stageY,!1)&&(G.hideControls(),G.dispatchEvent("controlshide"))})}),G.clickEvent=G.on("click",function(){G.ctrlKey&&setTimeout(function(){G.clone(!0).addTo(G.stage).mov(0,100),G.allowToggle&&(G.hideControls(),G.dispatchEvent("controlshide"));var e=new createjs.Event("change");e.controlType="move",G.dispatchEvent(e),G.stage.update()},50)}),G.hideControls=function(){return G.toggled=!1,oe.visible=!1,n.visible=!1,F=!1,G.stage&&G.stage.update(),!G.allowToggle&&G.move&&ce(),G},S||G.hideControls(),G.showControls=function(){return G.toggled=!0,oe.visible=!0,n.visible=!0,F=!0,oe.x=Z.x,oe.y=Z.y,n.x=Z.x,n.y=Z.y,G.addChildAt(Z,0),G.move&&!G.allowToggle&&se(),G.stage&&G.stage.update(),G},G.toggle=function(e){return!0===e?G.showControls():!1===e?G.hideControls():F?G.hideControls():G.showControls(),G},G.recordData=function(e){zot(e)&&(e=!1);var t={type:"Blob",index:G.parent?G.parent.getChildIndex(G):-1,x:G.x,y:G.y,points:G.recordPoints(),color:G.color,thickness:G.thickness,move:G.move,toggle:G.allowToggle,controlsVisible:F};return e?JSON.stringify(t):t},G.setData=function(e,t){if(!zot(e)){if(t)try{e=JSON.parse(e)}catch(e){return}var o=e.index;zot(o)&&(o=-1),delete e.index;var n=e.points;for(var r in zot(n)||G.setPoints(n),delete e.points,G.num=n.length,e)G[r]=e[r];return G.parent&&G.parent.setChildIndex(G,o),G.update(),G}},G.recordPoints=function(e){zot(e)&&(e=!1);var t=G.points;if(e){if(!G.pane){var o=G.pane=new kt.Pane({container:G.stage,width:Math.min(500,G.stage.width-20),height:Math.min(500,G.stage.height-20),draggable:!0});(G.textArea=new kt.TextArea(Math.min(400,G.stage.width-70),Math.min(400,G.stage.height-70))).centerReg(o)}G.textArea.text=JSON.stringify(t),G.pane.show()}return t},!(G.setPoints=function(e){for(var t,o,n=0;n<e.length;n++)t=H[n],o=e[n],zot(t)||(t[0].x=o[0],t[0].y=o[1],t[1].x=o[2],t[1].y=o[3],t[2].x=o[4],t[2].y=o[5],t[3].x=o[6],t[3].y=o[7],t[4]=o[8]);return G.update(),G})!==X&&Oe(G,_),G.clone=function(e){e?G.colorCommand:G.color,e?G.colorCommand:G.color;return G.cloneProps(new kt.Squiggle(e?G.colorCommand:G.color,G.thickness,G.recordPoints(),A,P,B,I,oe.visible,E,M,G.allowToggle,G.move,j,D,L,G.editPoints,X,G.group,R))},G.shape.on("mousedown",function(e){G.editPoints&&(G.controlsVisible?(G.pressX=e.stageX,G.pressY=e.stageY):(G.pressX=null,G.pressY=null))}),G.shape.on("pressup",function(e){if(G.editPoints&&G.pressX&&Math.abs(G.pressX-e.stageX)<ie&&Math.abs(G.pressY-e.stageY)<ie){G.selectPoints&&(G.lastPoints=kt.copy(G.points));var t=G.points,o=G.globalToLocal(e.stageX,e.stageY),n=kt.closestPointAlongCurve(o,G.segmentPoints);t.splice(n+1,0,[o.x,o.y,0,0,0,0,0,0]),G.points=t,G.changeControl({index:n+1,type:"mirror",update:!0}),G.lastSelectedIndex=n+1,G.lastSelected=G.controls.getChildAt(G.lastSelectedIndex),G.stage.update()}}),G.controls.on("click",function(e){G.lastSelected=e.target.parent;var t=G.lastSelectedIndex=G.controls.getChildIndex(e.target.parent);if(G.editPoints&&G.selectionManager.shiftKey&&"Circle"==e.target.type){if(G.controls.numChildren<=2)return;var o=G.points;G.selectPoints&&(G.lastPoints=kt.copy(o)),o.splice(t,1),G.points=o,G.stage.update(),G.lastSelected=G.lastSelectedIndex=null}}),F||G.hideControls(),G.dispatchEvent("update")}function ae(){var e=[],t=G.selectionManager.currentSet;if(t&&t.selections&&0<t.selections.length)for(var o=0;o<t.selections.length;o++){var n=G.pointObjects[t.selections[o]];if(t==G.selectedBalls)e.push(n[1]);else if(t==G.selectedRect1s)e.push(n[2]);else{if(t!=G.selectedRect2s)continue;e.push(n[3])}}return e}function le(e){if("Circle"==e.type){var t=e,o=t.mySet,n=t.rect1,r=t.rect2;n.x-=t.x,n.y-=t.y,r.x-=t.x,r.y-=t.y,o.x+=t.x,o.y+=t.y,t.x=0,t.y=0}}function se(){l||(l=!0,Z.drag({onTop:!1}),Q=Z.on("mousedown",Q),J=Z.on("pressmove",J),$=Z.on("pressup",$))}function ce(e){(e||l)&&(l=!1,Z.noDrag(),Z.off("mousedown",Q),Z.off("pressmove",J),Z.off("pressup",$))}},kt.extend(kt.Squiggle,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Blob=function(e,t,o,k,T,A,P,B,n,I,S,r,E,M,O,j,D,i,a,l,L,s,Y){var c;if(c=zob(kt.Blob,arguments,"color, borderColor, borderWidth, points, radius, controlLength, controlType, lockControlType, showControls, lockControls, handleSize, allowToggle, move, dashed, onTop, stickColor, selectColor, selectPoints, editPoints, interactive, style, group, inherit",this))return c;z_d("53.5"),this.group=s;var X=!1===L?{}:kt.getStyle("Blob",this.group,Y);zot(T)&&(T=null!=X.radius?X.radius:100),this.zimContainer_constructor(-T,-T,2*T,2*T,!1),this.type="Blob",zot(M)&&(M=null!=X.dashed&&X.dashed),zot(t)&&(t=null!=X.borderColor?X.borderColor:null),zot(o)&&(o=null!=X.borderWidth?X.borderWidth:null),t<0||o<0?t=o=null:null!=t&&null==o&&(o=1),zot(e)&&(e=null!=X.color?X.color:0<o?"rgba(0,0,0,0)":kt.green),e.style&&(this.colorCommand=e,e="black"),t&&t.style&&(this.borderColorCommand=t,t="black"),zot(k)&&(k=null!=X.points?X.points:4);var R="number"==typeof k?k:k.length,_=A;zot(A)&&(A=null!=X.controlLength?X.controlLength:4*T/R),zot(P)&&(P=null!=X.controlType?X.controlType:"straight"),zot(B)&&(B=null!=X.lockControlType&&X.lockControlType),zot(l)&&(l=null==X.interactive||X.interactive),zot(n)&&(n=null!=X.showControls?X.showControls:l);var W=n;zot(I)&&(I=null!=X.lockControls?X.lockControls:!l),zot(S)&&(S=null!=X.handleSize?X.handleSize:kt.mobile()?20:10),zot(r)&&(r=null!=X.allowToggle?X.allowToggle:l),zot(E)&&(E=null!=X.move?X.move:l),zot(j)&&(j=null!=X.stickColor?X.stickColor:"#111"),zot(D)&&(D=null!=X.selectColor?X.selectColor:"#fff"),zot(i)&&(i=null!=X.selectPoints?X.selectPoints:l),this.stickColor=j,zot(O)&&(O=null==X.onTop||X.onTop),zot(a)&&(a=null!=X.editPoints?X.editPoints:l);var F=this;this.interactive=l,this.num=R,this.editPoints=a,this.selectPoints=i,this.lockControls=I,this.onTop=O,this.move=E,this.allowToggle=r,this.lockControlType=B;this.types=["mirror","straight","free","none"];var H,V,N,G,q,U,K,Z,Q,J,$,ee,te,oe,ne=e,re=t,ie=o,u=F.move,ae=2;function d(){if(oe&&oe.removeAllEventListeners(),F.selectPoints?(F.selectedBalls=new kt.SelectionSet,F.selectedRect1s=new kt.SelectionSet,F.selectedRect2s=new kt.SelectionSet,F.selectionManager=new kt.SelectionManager([F.selectedBalls,F.selectedRect1s,F.selectedRect2s],"ctrl",!1)):F.selectionManager=new kt.SelectionManager(null,"ctrl"),!((R="number"==typeof k?k:k.length)<=0)){zot(_)&&(A=4*T/R),Z=F.shape=new kt.Shape({style:!1}).addTo(F);var n=F.sticks=new kt.Shape({style:!1}).addTo(F);S<=0&&n.removeFrom();var f=Z.graphics;f.c();var m=n.graphics;m.c();var e,t,o,r,i,a,l,s,c=S/10*8,u=S,d=kt.mobile();oe=F.controls=new kt.Container({style:!1}).addTo(F),F.interactive&&oe.drag({onTop:!d}),H=[],N=[],V=[];for(var h=0;h<R;h++){if((o=new kt.Container({style:!1}).addTo(oe)).num=h,"number"==typeof k){var g=kt.Pick.choose(A);(t=new kt.Container(g,T,null,null,!1).reg(g/2,T).addTo(F)).rotation=h/R*360,a=new kt.Circle(c,F.selectPoints&&F.selectedBalls.isSelected(h)?D:kt.light,kt.dark,2,null,null,!1).centerReg(t).loc({x:g/2,y:0}),r=new kt.Rectangle(u,u,F.selectPoints&&F.selectedRect1s.isSelected(h)?D:C(P),0==S?null:kt.dark,0==S?null:2,null,null,!1).centerReg(t).loc({x:0,y:0}),i=new kt.Rectangle(u,u,F.selectPoints&&F.selectedRect2s.isSelected(h)?D:C(P),0==S?null:kt.dark,0==S?null:2,null,null,!1).centerReg(t).loc({x:g,y:0});var p=t.localToLocal(a.x,a.y,oe);a.x=p.x,a.y=p.y,a.addTo(o,null,!1);var z=t.localToLocal(r.x,r.y,oe);r.x="none"==P?0:z.x-a.x,r.y="none"==P?0:z.y-a.y,r.addTo(o,null,!1);var v=t.localToLocal(i.x,i.y,oe);i.x="none"==P?0:v.x-a.x,i.y="none"==P?0:v.y-a.y,i.addTo(o,null,!1),o.x=a.x,o.y=a.y,a.x=0,a.y=0,"none"==P&&a.addTo(o,null,!1)}else l=(s=k[h])[8]?s[8]:P,o.loc({x:s[0],y:s[1]}),a=new kt.Circle(c,kt.light,kt.dark,2,null,null,!1).centerReg(o).loc({x:s[2],y:s[3]}),r=new kt.Rectangle(u,u,C(l),0==S?null:kt.dark,0==S?null:2,null,null,!1).centerReg(o,0).loc({x:s[4],y:s[5]}),i=new kt.Rectangle(u,u,C(l),0==S?null:kt.dark,0==S?null:2,null,null,!1).centerReg(o,0).loc({x:s[6],y:s[7]});a.mySet=o,a.rect1=r,a.rect2=i,a.index=h,0==S&&(a.expand(10),r.expand(10),i.expand(10)),d?a.on("mousedown",w):a.on("dblclick",x),r.ball=a,(r.other=i).ball=a,i.other=r,d&&(a.expand(),r.expand(),i.expand()),e=[o,a,r,i,s?s[8]:P],H.push(e),V.push(a),N.push(o)}var y,b=!1;(te=function(){f.c(),F.colorCommand||(F.colorCommand=G=f.f(ne).command),(zot(ie)||0<ie)&&(zot(re)&&zot(ie)||(zot(re)&&(re="black"),F.borderColorCommand||(F.borderColorCommand=q=f.s(re).command),F.borderWidthCommand||(F.borderWidthCommand=U=f.ss(ie).command),M&&(F.borderDashedCommand||(F.borderDashedCommand=K=f.sd([10,10],5).command))));var e=(r=H[0][0]).localToLocal(H[0][1].x,H[0][1].y,Z);f.mt(e.x,e.y),m.c().s(F.stickColor).ss(1);for(var t=0;t<H.length;t++){var o=t,n=(t+1)%H.length,r=H[o][0],i=H[o][1],a=H[o][2],l=H[o][3],s=H[n][0],c=H[n][1],u=H[n][2],d=(H[n][3],r.localToLocal(l.x,l.y,Z)),h=s.localToLocal(u.x,u.y,Z),g=s.localToLocal(c.x,c.y,Z);f.bt(d.x,d.y,h.x,h.y,g.x,g.y);e=r.localToLocal(i.x,i.y,Z);var p=r.localToLocal(a.x,a.y,Z);m.mt(e.x,e.y).lt(p.x,p.y),m.mt(e.x,e.y).lt(d.x,d.y)}f.cp(),f.append(F.colorCommand),M&&f.append(F.borderDashedCommand),F.borderWidthCommand&&f.append(F.borderWidthCommand),F.borderColorCommand&&f.append(F.borderColorCommand)})(),oe.on("mousedown",function(e){if(!F.lockControls){if(F.selectPoints&&(F.keyFocus=!0),y={x:e.target.x,y:e.target.y},e.target.rect1){(o=e.target).startX=o.x,o.startY=o.y,o.rect1.startX=o.rect1.x,o.rect1.startY=o.rect1.y,o.rect2.startX=o.rect2.x,o.rect2.startY=o.rect2.y}else{var t=e.target;t.startX=t.x,t.startY=t.y;var o,n=(o=t.ball).index,r=P;if(zot(H[n][4])||(r=H[n][4]),"straight"==r){var i=t.other,a=i.x-o.x,l=i.y-o.y;i.stickLength=Math.sqrt(Math.pow(a,2)+Math.pow(l,2))}}if(F.selectPoints){var s=F.selectionManager.currentSet;if(s&&s.selections&&0<s.selections.length)for(var c=0;c<s.selections.length;c++){var u=F.pointObjects[s.selections[c]];u[1].startX=u[1].x,u[1].startY=u[1].y,u[2].startX=u[2].x,u[2].startY=u[2].y,u[3].startX=u[3].x,u[3].startY=u[3].y}}}}),F.selectPoints&&oe.tap(function(e){if(e.target.rect1){var t=e.target;F.selectedBalls.toggle(t.parent.num)}else{var o=e.target;o.color="white",(t=o.ball).rect1==o?F.selectedRect1s.toggle(t.parent.num):F.selectedRect2s.toggle(t.parent.num)}for(var n=0;n<F.pointObjects.length;n++){var r=F.pointObjects[n];r[1].color=F.selectedBalls.isSelected(n)?kt.white:kt.light,r[2].color=F.selectedRect1s.isSelected(n)?kt.white:C(r[4]),r[3].color=F.selectedRect2s.isSelected(n)?kt.white:C(r[4])}e.target.stage.update()}),oe.on("pressmove",function(e){if(!F.lockControls)if(F.selectPoints){var t=le();if(-1==t.indexOf(e.target))ee(e.target),te();else if(0<t.length){diffX=e.target.x-e.target.startX,diffY=e.target.y-e.target.startY;for(var o=0;o<t.length;o++){var n=t[o];n.x=n.startX+diffX,n.y=n.startY+diffY,ee(n)}te()}}else ee(e.target),te()}),oe.on("pressup",function(e){if(!F.lockControls){var t=e.target.x!=y.x||e.target.y!=y.y,o=new createjs.Event("change");e.target.rect1?(o.controlType="bezierPoint",function(e){if(F.selectPoints){var t=le();if(t&&-1==t.indexOf(e))se(e);else if(t&&0<t.length)for(var o=0;o<t.length;o++)se(t[o]);else se(e)}else se(e)}(e.target)):o.controlType="bezierHandle",t&&F.dispatchEvent(o)}}),F.changeControl=function(e,t,o,n,r,i,a,l,s){var c;if(c=zob(F.changeControl,arguments,"index, type, rect1X, rect1Y, rect2X, rect2Y, circleX, circleY, update"))return c;if(zot(e)){for(var u=0;u<H.length;u++)F.changeControl(u,t,o,n,r,i,a,l);return F}var d=H[e];return"none"==(d[4]=t)?(zot(a)||(d[1].x=a),zot(l)||(d[1].y=l),d[2].x=d[1].x,d[2].y=d[1].y,d[3].x=d[1].x,d[3].y=d[1].y,d[1].parent.addChild(d[1])):(zot(a)||(d[1].x=a),zot(l)||(d[1].y=l),zot(o)||(d[2].x=o),zot(n)||(d[2].y=n),zot(r)||(d[3].x=r),zot(i)||(d[3].y=i),d[1].parent.addChildAt(d[1],0)),d[2].color=C(t),d[3].color=C(t),s&&(F.update(),F.stage&&F.stage.update()),F},F.transformPoints=function(e,t,o,n){return F.points=kt.transformPoints(F.points,e,t,o,n),F},F.update=function(e){return e?F.points=F.pointsAdjusted:te(),F},F.move&&F.interactive&&Z.drag({onTop:!1}),Q=Z.on("mousedown",function(){y={x:Z.x,y:Z.y},F.selectPoints&&(F.keyFocus=!0),function(){if(F.onTop){var e=F.parent.numChildren-1;"Keyboard"==F.parent.getChildAt(e).type&&e--,F.parent.setChildIndex(F,e)}}()}),J=Z.on("pressmove",function(){oe.x=Z.x,oe.y=Z.y,n.x=Z.x,n.y=Z.y}),$=Z.on("pressup",function(){var e=Z.x!=y.x||Z.y!=y.y,t=Z.localToLocal(0,0,F.parent);if(F.x=t.x,F.y=t.y,oe.x=oe.y=n.x=n.y=Z.x=Z.y=0,e){var o=new createjs.Event("change");o.controlType="move",F.dispatchEvent(o)}F.stage.update()}),E||ue(!0),F.toggleEvent=F.on("mousedown",function(){F.allowToggle&&(W||(F.showControls(),F.dispatchEvent("controlsshow")))}),F.added(function(){F.toggleStageEvent=F.stage.on("stagemousedown",function(e){F.allowToggle&&F.stage&&W&&!F.hitTestPoint(e.stageX,e.stageY,!1)&&(F.hideControls(),F.dispatchEvent("controlshide"))})}),F.clickEvent=F.on("click",function(){F.ctrlKey&&setTimeout(function(){F.clone(!0).addTo(F.stage).mov(100),F.allowToggle&&(F.hideControls(),F.dispatchEvent("controlshide"));var e=new createjs.Event("change");e.controlType="move",F.dispatchEvent(e),F.stage.update()},50)}),F.hideControls=function(){return F.toggled=!1,oe.visible=!1,n.visible=!1,W=!1,F.stage&&F.stage.update(),!F.allowToggle&&F.move&&ue(),F},W||F.hideControls(),F.showControls=function(){return F.toggled=!0,oe.visible=!0,n.visible=!0,W=!0,oe.x=Z.x,oe.y=Z.y,n.x=Z.x,n.y=Z.y,F.addChildAt(Z,0),F.move&&!F.allowToggle&&ce(),F.stage&&F.stage.update(),F},F.toggle=function(e){return!0===e?F.showControls():!1===e?F.hideControls():W?F.hideControls():F.showControls(),F},F.recordData=function(e){zot(e)&&(e=!1);var t={type:"Blob",index:F.parent?F.parent.getChildIndex(F):-1,x:F.x,y:F.y,points:F.recordPoints(),color:F.color,borderColor:F.borderColor,borderWidth:F.borderWidth,move:F.move,toggle:F.allowToggle,controlsVisible:W};return e?JSON.stringify(t):t},F.setData=function(e,t){if(!zot(e)){if(t)try{e=JSON.parse(e)}catch(e){return}var o=e.index;zot(o)&&(o=-1),delete e.index;var n=e.points;for(var r in zot(n)||F.setPoints(n),delete e.points,this.num=n.length,e)F[r]=e[r];return F.parent&&F.parent.setChildIndex(F,o),F}},F.recordPoints=function(e){zot(e)&&(e=!1);var t=F.points;if(e){if(!o){var o=F.pane=new kt.Pane({displayClose:!1,container:F.stage,width:Math.min(500,F.stage.width-20),height:Math.min(500,F.stage.height-20),draggable:!0}),n=F.textArea=new kt.TextArea(Math.min(400,F.stage.width-70),Math.min(400,F.stage.height-70));n.centerReg(o)}n.text=JSON.stringify(t),o.show()}return t},!(F.setPoints=function(e){for(var t,o,n=0;n<e.length;n++)t=H[n],o=e[n],zot(t)||(t[0].x=o[0],t[0].y=o[1],t[1].x=o[2],t[1].y=o[3],t[2].x=o[4],t[2].y=o[5],t[3].x=o[6],t[3].y=o[7],t[4]=o[8],t[2].color=C(t[4]),t[3].color=C(t[4]));return F.update(),F})!==L&&Oe(F,X),F.clone=function(e){e?F.colorCommand:F.color,e?F.colorCommand:F.color;return F.cloneProps(new kt.Blob(e?F.colorCommand:F.color,e?F.borderColorCommand:F.borderColor,F.borderWidth,F.recordPoints(),T,A,P,B,oe.visible,I,S,F.allowToggle,F.move,M,O,j,F.editPoints,L,F.group,Y))},F.shapeMousedownEvent=F.shape.on("mousedown",function(e){F.editPoints&&(F.controlsVisible?(F.pressX=e.stageX,F.pressY=e.stageY):(F.pressX=null,F.pressY=null))}),F.shapePressupEvent=F.shape.on("pressup",function(e){if(F.editPoints&&F.pressX&&Math.abs(F.pressX-e.stageX)<ae&&Math.abs(F.pressY-e.stageY)<ae){F.selectPoints&&(F.lastPoints=kt.copy(F.points));var t=F.points,o=F.globalToLocal(e.stageX,e.stageY),n=kt.closestPointAlongCurve(o,F.segmentPoints);t.splice(n+1,0,[o.x,o.y,0,0,0,0,0,0]),F.points=t,F.changeControl({index:n+1,type:"mirror",update:!0}),F.lastSelectedIndex=n+1,F.lastSelected=F.controls.getChildAt(F.lastSelectedIndex),F.stage.update()}}),F.controlsClickEvent=F.controls.on("click",function(e){F.lastSelected=e.target.parent;var t=F.lastSelectedIndex=F.controls.getChildIndex(e.target.parent);if(F.editPoints&&F.selectionManager.shiftKey&&"Circle"==e.target.type){if(F.controls.numChildren<=2)return;var o=F.points;F.selectPoints&&(F.lastPoints=kt.copy(o)),o.splice(t,1),F.points=o,F.stage.update()}}),W||F.hideControls(),F.dispatchEvent("update")}function w(e){b?(e.preventDefault(),x(e)):(b=!0,setTimeout(function(){b=!1},300))}function x(e){if(!F.lockControlType){var t=e.target,o=H[t.index][4]?H[t.index][4]:P;Math.abs(t.rect1.x)<=2&&Math.abs(t.rect1.y)<=2&&Math.abs(t.rect2.x)<=2&&Math.abs(t.rect2.y)<=2&&(o="none"),"none"==o&&t.parent.addChildAt(t,0),"none"==(o=F.types[(F.types.indexOf(o)+(F.shiftKey?-1:1)+F.types.length)%F.types.length])&&(t.rect1.x=t.rect1.y=t.rect2.x=t.rect2.y=0,t.parent.addChild(t),e.stopImmediatePropagation()),H[t.index][4]=o,t.rect1.color=C(o),t.rect2.color=C(o),te();var n=new createjs.Event("change");n.controlType="bezierSwitch",F.dispatchEvent(n),t.stage.update()}}function C(e){var t={mirror:kt.purple,free:kt.yellow,none:kt.blue};return t[e]?t[e]:kt.pink}}function le(){var e=[],t=F.selectionManager.currentSet;if(t&&t.selections&&0<t.selections.length)for(var o=0;o<t.selections.length;o++){var n=F.pointObjects[t.selections[o]];if(t==F.selectedBalls)e.push(n[1]);else if(t==F.selectedRect1s)e.push(n[2]);else{if(t!=F.selectedRect2s)continue;e.push(n[3])}}return e}function se(e){if(F.selectPoints&&"Circle"==e.type){var t=e,o=t.mySet,n=t.rect1,r=t.rect2;n.x-=t.x,n.y-=t.y,r.x-=t.x,r.y-=t.y,o.x+=t.x,o.y+=t.y,t.x=0,t.y=0}}function ce(){u||(u=!0,Z.drag({onTop:!1}),Q=Z.on("mousedown",Q),J=Z.on("pressmove",J),$=Z.on("pressup",$))}function ue(e){(e||u)&&(u=!1,Z.noDrag(),Z.off("mousedown",Q),Z.off("pressmove",J),Z.off("pressup",$))}d(),F.selectionManager.on("keydown",function(e){if(F.selectPoints&&F.keyFocus&&37<=e.keyCode&&e.keyCode<=40){var t=le();if(0<t.length){for(var o=0;o<t.length;o++){var n=t[o];37==e.keyCode?n.x-=F.selectionManager.shiftKey?10:1:39==e.keyCode?n.x+=F.selectionManager.shiftKey?10:1:38==e.keyCode?n.y-=F.selectionManager.shiftKey?10:1:40==e.keyCode&&(n.y+=F.selectionManager.shiftKey?10:1),ee(n)}te(),F.stage&&F.stage.update()}}}),F.selectionManager.on("keyup",function(e){if(F.selectPoints&&F.keyFocus&&37<=e.keyCode&&e.keyCode<=40){var t=le();if(0<t.length)for(var o=0;o<t.length;o++)se(t[o])}}),F.selectionManager.on("undo",function(){if(F.selectPoints&&F.keyFocus&&F.lastPoints){var e=kt.copy(F.lastPoints);F.lastPoints=kt.copy(F.points),F.points=e,F.stage&&F.stage.update()}}),ee=function(e){if(!F.lockControls)if(e.rect1){var t=(n=e).x-n.startX,o=n.y-n.startY;n.rect1.x=n.rect1.startX+t,n.rect1.y=n.rect1.startY+o,n.rect2.x=n.rect2.startX+t,n.rect2.y=n.rect2.startY+o}else{var n,r=e,i=r.other,a=(n=r.ball).index,l=P;if(zot(H[a][4])||(l=H[a][4]),"straight"==l||"mirror"==l){var s=r.x-n.x,c=r.y-n.y;if("mirror"==l)i.x=n.x-s,i.y=n.y-c;else{var u=Math.atan2(c,s),d=-i.stickLength*Math.cos(u+Math.PI),h=-i.stickLength*Math.sin(u+Math.PI);i.x=n.x-d,i.y=n.y-h}}}},Object.defineProperty(F,"move",{get:function(){return E},set:function(e){E!=e&&((E=e)?ce():ue())}}),Object.defineProperty(F,"interactive",{get:function(){return l},set:function(e){l=e,F.showControls=l,F.allowToggle=l,F.editPoints=l,F.lockControls=!l,F.selectPoints=l,F.move=l,F.points=F.points}}),Object.defineProperty(F,"allowToggle",{get:function(){return r},set:function(e){r!=e&&((r=e)?F.move&&ce():!W&&F.move&&ue())}}),Object.defineProperty(F,"controlsVisible",{get:function(){return W},set:function(e){(W=e)?F.showControls():F.hideControls()}});var h,g,p=I;Object.defineProperty(F,"lockControls",{get:function(){return p},set:function(e){p=e,F.controls.mouseEnabled=e?F.controls.mouseChildren=!1:F.controls.mouseChildren=!0}}),F.lockControls=p,Object.defineProperty(F,"color",{get:function(){return ne},set:function(e){zot(e)&&(e="black"),ne=e,G.style=ne}}),this.setColorRange=function(e,t){return g=zot(t)?(h=F.color,e):(h=zot(e)?F.color:e,t),F};var f=0;Object.defineProperty(F,"colorRange",{get:function(){return f},set:function(e){f=e,zot(h)||zot(g)||(F.color=kt.colorRange(h,g,e))}}),Object.defineProperty(F,"borderColor",{get:function(){return re},set:function(e){zot(e)||(re=e,q?q.style=re:te())}}),Object.defineProperty(F,"borderWidth",{get:function(){return ie},set:function(e){zot(e)||(0<e||(e=0),ie=e,U&&0!=ie?(U.width=ie,M&&(K.segments=[20,10],K.offset=5)):te())}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==F},set:function(e){kt.KEYFOCUS=F}}),F.selectPoints&&!kt.KEYFOCUS&&function(){F.keyFocus=!0;var e=document.activeElement;e&&e.blur()}(),Object.defineProperty(F,"points",{get:function(){for(var e,t,o=[],n=0;n<H.length;n++)t=H[n],e=[kt.decimals(t[0].x),kt.decimals(t[0].y),kt.decimals(t[1].x),kt.decimals(t[1].y),kt.decimals(t[2].x),kt.decimals(t[2].y),kt.decimals(t[3].x),kt.decimals(t[3].y)],t[4]&&"straight"!==t[4]&&e.push(t[4]),o.push(e);return o},set:function(e){F.dispose(!0),k=e,F.shape&&(F.shape.graphics.clear(),F.sticks.graphics.clear(),F.controls.noDrag(),F.removeAllChildren(),delete F.shape,delete F.sticks,delete F.controls),d(),F.lockControls=p}}),Object.defineProperty(F,"pointsAdjusted",{get:function(){var r,i,a=[],l=F.pointObjects;return kt.loop(l.length,function(e,t){if(po=l[e],i=H[e],0==po[0].rotation&&0==po[0].scaleX&&0==po[0].scaleY)r=[kt.decimals(i[0].x),kt.decimals(i[0].y),kt.decimals(i[1].x),kt.decimals(i[1].y),kt.decimals(i[2].x),kt.decimals(i[2].y),kt.decimals(i[3].x),kt.decimals(i[3].y)];else{var o=po[0].localToLocal(po[2].x,po[2].y,po[0].parent),n=po[0].localToLocal(po[3].x,po[3].y,po[0].parent);r=[kt.decimals(i[0].x),kt.decimals(i[0].y),kt.decimals(i[1].x),kt.decimals(i[1].y),kt.decimals(o.x-i[0].x),kt.decimals(o.y-i[0].y),kt.decimals(n.x-i[0].x),kt.decimals(n.y-i[0].y)]}i[4]&&"mirror"!==i[4]&&r.push(i[4]),a.push(r)}),a},set:function(e){zon&&zog("Blob() - pointsAdjusted is read only")}}),Object.defineProperty(F,"pointObjects",{get:function(){return H},set:function(e){zon&&zog("Blob() - pointObjects is read only - but its contents can be manipulated - use blob.update() after changes")}}),Object.defineProperty(F,"pointControls",{get:function(){return N},set:function(e){zon&&zog("Blob() - pointControls is read only - but its contents can be manipulated - use blob.update() after changes")}}),Object.defineProperty(F,"pointCircles",{get:function(){return V},set:function(e){zon&&zog("Blob() - pointCircles is read only - but its contents can be manipulated - use blob.update() after changes")}}),Object.defineProperty(F,"segmentPoints",{get:function(){var n=F.pointsAdjusted,r=[];return kt.loop(n.length,function(e,t){var o=F.getSegmentPoint(n[e],n[e<t-1?e+1:0]);r.push(o)}),r},set:function(e){zon&&zog("Blob() - segmentPoints is read only")}}),Object.defineProperty(F,"segmentRatios",{get:function(){var o=[],n=0;kt.loop(F.segmentPoints,function(e){var t=kt.distanceAlongCurve(e);o.push(t),n+=t});var t=[],r=0;return kt.loop(o,function(e){r+=e/n,t.push(r)}),t},set:function(e){zon&&zog("Blob() - segmentRatios is read only")}}),F.getPointAngle=function(e){var t=F.pointObjects[e][0],o=F.pointObjects[e][2],n=F.pointObjects[e][3],r=t.localToGlobal(o.x,o.y),i=t.localToGlobal(n.x,n.y);return kt.angle(r.x,r.y,i.x,i.y)},F.getSegmentPoint=function(e,t){if(!zot(e)&&!zot(t)){0==e[2]&&0==e[3]||(e[4]-=e[2],e[5]-=e[3],e[6]-=e[2],e[7]-=e[3],e[0]+=e[2],e[1]+=e[3],e[2]=0,e[3]=0),0==t[2]&&0==t[3]||(t[4]-=t[2],t[5]-=t[3],t[6]-=t[2],t[7]-=t[3],t[0]+=t[2],t[1]+=t[3],t[2]=0,t[3]=0);var o={x:e[0],y:e[1]},n={x:e[0]+e[6],y:e[1]+e[7]},r={x:t[0]+t[4],y:t[1]+t[5]},i={x:t[0],y:t[1]};return 0==oe.x&&0==oe.y||(o.x+=oe.x,n.x+=oe.x,r.x+=oe.x,i.x+=oe.x,o.y+=oe.y,n.y+=oe.y,r.y+=oe.y,i.y+=oe.y),[o,n,r,i]}},F.getAdjacentSegmentData=function(e){zot(e)&&(e=0);var t=F.pointsAdjusted;if(2==F.num)return[[F.getSegmentPoint(t[0],t[1]),F.getSegmentPoint(t[1],t[0])],[0,1]];if(0==e)return[[F.getSegmentPoint(t[F.num-1],t[0]),F.getSegmentPoint(t[0],t[1]),F.getSegmentPoint(t[1],t[2])],[F.num-1,0,1]];if(e>=F.num-1)return[[F.getSegmentPoint(t[F.num-2],t[F.num-1]),F.getSegmentPoint(t[F.num-1],t[0]),F.getSegmentPoint(t[0],t[1])],[F.num-2,F.num-1,0]];var o=e+2>=F.num?0:e+2;return[[F.getSegmentPoint(t[e-1],t[e]),F.getSegmentPoint(t[e],t[e+1]),F.getSegmentPoint(t[e+1],t[o])],[e-1,e,e+1]]},F.getCurvePoint=function(o,e,t,n){zot(e)&&(e=F.segmentRatios),zot(t)&&(t=F.segmentPoints),zot(n)&&(n=!1);var r=e,i=t,a=kt.loop(r,function(e,t){if(o<=e)return t}),l=0<a?r[a-1]:0,s=0<a?r[a]-r[a-1]:r[a],c=(o-l)/s,u=kt.pointAlongCurve(i[a],c,n),d=F.localToGlobal(u.x,u.y);return d.angle=u.angle,d.z=a,zot(d)?void 0:d},this.dispose=function(e){if(F.shape){F.shape.cursor="default";for(var t=0;t<F.pointObjects.length;t++)F.pointObjects[t][1].removeAllEventListeners();for(t=0;t<V.length;t++)V[t].removeAllEventListeners();return F.sticks.removeFrom(F),F.controls.removeFrom(F),F.shape.removeAllEventListeners(),F.controls.removeAllEventListeners(),F.off("mousedown",F.toggleEvent),F.off("click",F.clickEvent),F.toggleStageEvent&&F.stage.off("stagemousedown",F.toggleStageEvent),!e&&F.selectPoints&&F.selectionManager.removeAllEventListeners(),!0}}},kt.extend(kt.Blob,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Label=function(e,n,t,o,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E){var M;if(M=zob(kt.Label,arguments,"text, size, font, color, rollColor, shadowColor, shadowBlur, align, valign, lineWidth, lineHeight, fontOptions, backing, outlineColor, outlineWidth, backgroundColor, backgroundBorderColor, backgroundBorderWidth, corner, backgroundDashed, padding, paddingHorizontal, paddingVertical, shiftHorizontal, shiftVertical, rollPersist, labelWidth, labelHeight, maxSize, style, group, inherit",this))return M;z_d("54"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Label",this.group=S;var O=!1===I?{}:kt.getStyle(this.type,this.group,E);zot(e)&&(e=null!=O.text?O.text:"LABEL");var j=!1;""===e&&(e=" ",j=!0),zot(n)&&(n=null!=O.size?O.size:36),zot(t)&&(t=null!=O.font?O.font:"arial"),zot(o)&&(o=null!=O.color?O.color:"black"),zot(r)&&(r=null!=O.rollColor?O.rollColor:o),(zot(i)||"ignore"==i)&&(i=null!=O.shadowColor&&"ignore"!=i?O.shadowColor:-1),(zot(a)||"ignore"==a)&&(a=null!=O.shadowBlur&&"ignore"!=a?O.shadowBlur:14),zot(l)&&(l=null!=O.align?O.align:"left"),zot(s)&&(s=null!=O.valign?O.valign:"top"),zot(d)&&(d=null!=O.fontOptions?O.fontOptions:""),zot(g)&&zot(O.outlineColor)||!zot(p)||(p=null!=O.outlineWidth?O.outlineWidth:Math.round(.2*n)),zot(p)&&zot(O.outlineWidth)||!zot(g)||(g=null!=O.outlineColor?O.outlineColor:"#000000"),zot(p)&&(p=null!=O.outlineWidth?O.outlineWidth:0),(zot(f)||"ignore"==f)&&(f=null!=O.backgroundColor&&"ignore"!=f?O.backgroundColor:null),(zot(b)||"ignore"==b)&&(b=null!=O.padding&&"ignore"!=b?O.padding:10),zot(w)&&(w=null!=O.paddingHorizontal?O.paddingHorizontal:b),zot(x)&&(x=null!=O.paddingVertical?O.paddingVertical:b),zot(C)&&(C=null!=O.shiftHorizontal?O.shiftHorizontal:0),zot(k)&&(k=null!=O.shiftVertical?O.shiftVertical:0),zot(c)&&(c=null!=O.lineWidth?O.lineWidth:null),zot(u)&&(u=null!=O.lineHeight?O.lineHeight:null),(zot(h)||"ignore"==h)&&(h=null!=O.backing&&"ignore"!=h?O.backing:null),zot(T)&&null!=O.rollPersist&&O.rollPersist,null!=O.labelWidth&&(c=O.labelWidth),zot(A)||(c=A),"middle"==l&&(l="center"),zot(B)&&null!=O.maxSize&&O.maxSize,n=B?Math.min(n,B):n;var D=this;this.mouseChildren=!1,this.paddingVertical=x,this.paddingHorizontal=w;var L,Y,X=this.label=new createjs.Text(String(e),d+" "+n+"px "+t,o);if(X.textAlign=l,X.lineWidth=c,X.lineHeight=u,X.textBaseline="alphabetic",0<p){var R=this.outlineLabel=X.clone();R.color=g,R.outline=p,this.addChild(R)}function _(){var e,t=X.getBounds();if("baseline"==s?e=t.y:"top"==s?(X.y=n-n/6,R&&(R.y=n-n/6),e=0):"center"==s||"middle"==s?(e=-t.height/2,X.y=.3*n,R&&(R.y=.3*n)):e=-t.height,h)if("Pattern"==h.type)D.setBounds(t.x-w,e-x,t.width+2*w,t.height+2*x);else{var o=h.getBounds();D.setBounds(o.x,o.y,o.width,o.height)}else zot(f)?(D.setBounds(t.x,e,t.width,t.height),W.graphics.c().f("black").r(D.getBounds().x,D.getBounds().y,D.getBounds().width,D.getBounds().height)):(D.setBounds(t.x,e,t.width,t.height),D.removeChild(D.background),D.background=new kt.Rectangle(D.getBounds().width+2*w,D.getBounds().height+2*x,f,m,z,v,y,!1),kt.center(D.background,D,0),D.setBounds(D.background.x,D.background.y,D.background.width,D.background.height));kt.center(X,D),kt.pos(X,"left"==l||"right"==l?h||D.background?w:0:null,"top"==s||"baseline"==s||"bottom"==s?h||D.background?x:0:null,"right"==l,"bottom"==s),"baseline"!=s&&(X.y+=n/32),X.x+=C,X.y+=k,R&&(kt.center(R,D,D.numChildren-2),"baseline"!=s&&(R.y+=n/32),R.x+=C,R.y+=k)}if(-1!=i&&0<a&&(X.shadow=new createjs.Shadow(i,3,3,a)),this.addChild(X),zot(h)&&zot(f)){var W=new createjs.Shape;D.hitArea=W}if(_(),!zot(h)){if("Pattern"==h.type){if(D.backing=new kt.Container(D.width,D.height,null,null,!1).centerReg(null,null,!1),-1!=i&&0<a)new kt.Rectangle(D.width-2,D.height-2,"#666",null,null,null,null,!1).center(D.backing).shadow=new createjs.Shadow(i,3,3,a);var F=D.backing.mask=new kt.Rectangle(D.width,D.height,f,null,null,null,null,!1).addTo(D.backing);h.centerReg(F),h.setMask(F.shape),D.backing.pattern=h}else D.backing=h;h.center(D,0)}Object.defineProperty(D,"text",{get:function(){return" "==X.text&&j?"":X.text},set:function(e){j=!1,""===e&&(e=" ",j=!0),X.text=String(e),R&&(R.text=String(e)),_(),zot(c)||zot(P)||V()}}),Object.defineProperty(D,"size",{get:function(){return n},set:function(e){n=B?Math.min(e,B):e;var t=this.label.font.match(/^(.*\s)(\d*\.?\d*)+px(.*)$/i);t&&(this.label.font=t[1]+e+"px"+t[3],_())}}),Object.defineProperty(D,"color",{get:function(){return o},set:function(e){r==o&&(r=e),o=e,X.color=o,kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}}),this.setColorRange=function(e,t){return Y=zot(t)?(L=D.color,e):(L=zot(e)?D.color:e,t),D};var H=0;function V(){for(D.size=200;D.height>P||D.width>c;)D.size=D.size/2;for(var e=0;D.height<=P&&D.width<=c&&(e++,D.size=Math.ceil(D.size+1),!(50<e)););D.size=D.size-1}Object.defineProperty(D,"colorRange",{get:function(){return H},set:function(e){H=e,zot(L)||zot(Y)||(D.color=kt.colorRange(L,Y,e))}}),Object.defineProperty(D,"outlineColor",{get:function(){return g},set:function(e){g=e,R&&(R.color=g),kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}}),Object.defineProperty(D,"rollColor",{get:function(){return r},set:function(e){r=e}}),this._enabled=!0,Object.defineProperty(D,"enabled",{get:function(){return D._enabled},set:function(e){Se(D,e),X.color=o,D.mouseChildren=!1,kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}}),this.showRollColor=function(e){return zot(e)&&(e=!0),X.color=e?r:o,D.stage&&D.stage.update(),D},this.mouseoverEvent=this.on("mouseover",function(e){D.showRollColor&&D.showRollColor()}),this.mouseoutEvent=this.on("mouseout",function(e){D.rollPersist||D.showRollColor(!1)}),this.pressupEvent=this.on("pressup",function(e){D.rollPersist&&D.showRollColor(!1)}),Object.defineProperty(D,"labelWidth",{get:function(){return c},set:function(e){0<e&&(c=e,D.label.lineWidth=e),P&&V(),kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}}),Object.defineProperty(D,"labelHeight",{get:function(){return P},set:function(e){0<e&&(P=e),c&&V(),kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}}),zot(c)||zot(P)||V(),Oe(this,O),this.clone=function(){return D.cloneProps(new kt.Label(D.text,n,t,o,r,i,a,l,s,c,u,d,zot(h)?null:h.clone(),g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,this.group,E))}},kt.extend(kt.Label,kt.Container,"clone","zimContainer"),kt.LabelOnPath=function(o,i,a,l,e,t,n,r,s,c,u){var d;if(d=zob(kt.LabelOnPath,arguments,"label, path, percentAngle, percents, showPath, allowToggle, interactive, onTop, style, group, inherit",this))return d;z_d("54.5"),this.zimContainer_constructor(null,null,null,null,!1),this.type="LabelOnPath",this.group=c;var h=!1===s?{}:kt.getStyle(this.type,this.group,u);zot(o)&&(o=null!=h.label?h.label:new kt.Label("Label on Path")),zot(i)&&(i=null!=h.path?h.path:new kt.Squiggle({points:[[0,0,0,0,-86,57,86,-57],[300,150,0,0,-133,21,133,-21]]})),zot(a)&&(a=null!=h.percentAngle?h.percentAngle:100),zot(l)&&(l=null!=h.percents?h.percents:null),zot(e)&&(e=null==h.showPath||h.showPath),zot(t)&&(t=null==h.allowToggle||h.allowToggle),zot(n)&&(n=null==h.interactive||h.interactive),zot(r)&&(r=null!=h.onTop&&h.onTop),i.addTo(this);var g=this;this.path=i,this.allowToggle=t,i.interactive=n,"string"==typeof o&&(o=new kt.Label(o));var p=i.alpha;e||i.alp(0),i.onTop=r;var f=this.letters=(new kt.Container).addTo(this);if(!l){l=[];for(var m=0;m<o.text.length;m++)l.push(kt.decimals(1/(o.text.length-("Blob"==i.type?0:1))*100*m))}function z(){for(var e=f.numChildren-1;0<=e;e--)f.getChildAt(e).dispose();g.numLetters=o.text.length;for(e=0;e<g.numLetters;e++){var t=o.clone();t.text=o.text[e],t.centerReg(f).reg(null,t.height),""!=t.text&&" "!=t.text&&t.expand(0),g.allowToggle&&(t.cursor="pointer"),t.on("mousedown",function(){g.allowToggle&&g.toggle()})}g.resize()}this.percents=l,this.resize=function(){for(var e=i.segmentRatios,t=i.segmentPoints,o=0;o<this.numLetters;o++){var n=i.getCurvePoint(l[o]/100,e,t,!0);if(n){var r=this.globalToLocal(n.x,n.y);r&&f.getChildAt(o).loc(r).rot((180<n.angle?n.angle-360:n.angle)*a/100)}}return this},z(),this.showPath=function(e){return this.toggle(!0),i.toggle(e),this},this.hidePath=function(){return this.toggle(!1),this},Object.defineProperty(g,"text",{get:function(){return o.text},set:function(e){o.text=e,l=[];for(var t=0;t<o.text.length;t++)l.push(kt.decimals(1/(o.text.length-("Blob"==i.type?0:1))*100*t));z()}}),Object.defineProperty(g,"interactive",{get:function(){return n},set:function(e){n=e,i.interactive=e,this.ticker&&kt.Ticker.remove(this.ticker),n&&(this.ticker=kt.Ticker.add(function(){g.resize()}))}}),this.interactive&&(this.ticker=kt.Ticker.add(function(){g.resize()}));var v=g.toggled=e;this.toggle=function(e){if(this.allowToggle)return(v=zot(e)?!v:!!e)?(i.alp(p),this.interactive&&(i.showControls(),f.mouseEnabled=!1,f.mouseChildren=!1,f.cursor="default",this.controlHideEvent&&i.off("controlshide",this.controlHideEvent),this.controlHideEvent=i.on("controlshide",function(){f.mouseEnabled=!0,f.mouseChildren=!0,f.cursor="pointer",p=i.alpha,i.alp(0),v=!1,g.toggled=v},null,!0))):(p=i.alpha,i.alp(0),f.mouseEnabled=!0,f.mouseChildren=!0,f.cursor="pointer"),g.toggled=v,g.stage.update(),g},Oe(this,h),this.clone=function(){return g.cloneProps(new kt.LabelOnPath(g.label.clone(),g.path.clone(),a,kt.copy(l),e,t,n,r,s,this.group,u))},this.dispose=function(){return this.ticker&&kt.Ticker.remove(this.ticker),this.zimContainer_dispose(),!0}},kt.extend(kt.LabelOnPath,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Button=function(n,r,t,i,a,o,l,s,c,e,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H,V,N,G,q){var U;if(U=zob(kt.Button,arguments,"width, height, label, backgroundColor, rollBackgroundColor, color, rollColor, borderColor, borderRollColor, borderWidth, corner, shadowColor, shadowBlur, hitPadding, gradient, gloss, dashed, backing, rollBacking, rollPersist, icon, rollIcon, toggle, toggleBacking, rollToggleBacking, toggleIcon, rollToggleIcon, toggleEvent, wait, waitTime, waitBackgroundColor, rollWaitBackgroundColor, waitColor, rollWaitColor, waitModal, waitEnabled, waitBacking, rollWaitBacking, waitIcon, rollWaitIcon, align, valign, indent, indentHorizontal, indentVertical, style, group, inherit",this))return U;z_d("55"),this.group=G;var K=!1===N?{}:kt.getStyle("Button",G,q);zot(n)&&(n=null!=K.width?K.width:200),zot(r)&&(r=null!=K.height?K.height:60),this.zimContainer_constructor(n,r,null,null,!1),this.type="Button",zot(i)&&(i=null!=K.backgroundColor?K.backgroundColor:"#C60"),zot(a)&&(a=null!=K.rollBackgroundColor?K.rollBackgroundColor:"#F93"),zot(o)&&(o=null!=K.color?K.color:"white"),zot(l)&&(l=null!=K.rollColor?K.rollColor:"white"),zot(S)&&(S=null!=K.waitBackgroundColor?K.waitBackgroundColor:i),zot(E)&&(E=null!=K.rollWaitBackgroundColor?K.rollWaitBackgroundColor:a);var Z=s,Q=e;zot(s)&&(s=null!=K.borderColor?K.borderColor:null),zot(e)&&(e=null!=K.borderWidth?K.borderWidth:null),s<0||e<0?s=e=null:null!=s&&null==e&&(e=1),zot(c)&&(c=null!=K.borderRollColor?K.borderRollColor:s),zot(u)&&(u=null!=K.corner?K.corner:20),zot(d)&&(d=null!=K.shadowColor?K.shadowColor:"rgba(0,0,0,.3)"),zot(h)&&(h=null!=K.shadowBlur?K.shadowBlur:14),zot(g)&&(g=null!=K.hitPadding?K.hitPadding:0),zot(_)&&(_=null!=K.align?K.align:"center"),zot(W)&&(W=null!=K.valign?K.valign:"center"),zot(F)&&(F=null!=K.indent?K.indent:10),zot(H)&&(H=null!=K.indentHorizontal?K.indentHorizontal:F),zot(V)&&(V=null!=K.indentVertical?K.indentVertical:F),zot(p)&&(p=null!=K.gradient?K.gradient:0),zot(f)&&(f=null!=K.gloss?K.gloss:0),zot(t)&&(t=zot(b)?null!=K.label?K.label:"PRESS":"");var J=(!zot(x)||!zot(C)||!zot(k)||!zot(T)||!zot(A))&&zot(B)&&zot(L)&&zot(Y);J&&zot(P)&&(P=kt.mobile()?"mousedown":"click"),"string"!=typeof t&&"number"!=typeof t||(t=new kt.Label({text:t,size:null!=K.size?K.size:36,font:null!=K.font?K.font:"arial",color:null!=K.color?K.color:o,rollColor:null!=K.rollColor?K.rollColor:l,align:_,valign:W,rollPersist:null!=K.rollPersist&&K.rollPersist,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",style:!1,group:this.group})),zot(y)&&(y=null!=K.rollPersist&&K.rollPersist),this.rollPersist=y,zot(m)&&(m=null!=K.dashed&&K.dashed),zot(x)||"Label"!=x.type||zon&&zog("ZIM Button() - do not pass Label to toggle parameter - just pass a String");var $=this;this.mouseChildren=!1,this.cursor="pointer",$.focus=!1,$.rolled=!1,zot(z)&&(z=null!=K.backing?K.backing.clone():null),zot(z)?$.backing=new kt.Rectangle(n,r,i,null,null,u,m,!1).centerReg(null,null,!1):$.backing=z,$.rollBacking=zot(v)?null!=K.rollBacking?K.rollBacking.clone():null:v,$.waitBacking=zot(L)?null!=K.waitBacking?K.waitBacking.clone():null:L,$.rollWaitBacking=zot(Y)?null!=K.rollWaitBacking?K.rollWaitBacking.clone():null:Y,$.toggleBacking=zot(C)?null!=K.toggleBacking?K.toggleBacking.clone():null:C,$.rollToggleBacking=zot(k)?null!=K.rollToggleBacking?K.rollToggleBacking.clone():null:k;for(var ee,te,oe=["backing","rollBacking","toggleBacking","rollToggleBacking","waitBacking","rollWaitBacking"],ne=0;ne<oe.length;ne++)ee=oe[ne],(te=$[ee])&&("Pattern"==te.type?te=re(ee,te):-1!=d&&0<h&&(te.shadow=new createjs.Shadow(d,3,3,h)),te.x=n/2,te.y=r/2);function re(e,t){($[e]=new kt.Container(n,r,null,null,!1).centerReg(null,null,!1),-1!=d&&0<h)&&(new kt.Rectangle(n-2,r-2,"#666",null,null,u,null,!1).center($[e]).shadow=new createjs.Shadow(d,3,3,h));var o=$[e].mask=new kt.Rectangle(n,r,0<=e.indexOf("roll")?a:i,null,null,u,null,!1).addTo($[e]);return t.centerReg(o),t.setMask(o.shape),$[e].pattern=t,$[e]}$.addChild($.backing),e&&($.border=new kt.Rectangle(n,r,"rgba(0,0,0,0)",s,e,u,null,!1),$.addChild($.border)),$.icon=zot(b)?null!=K.icon?K.icon.clone():null:b,$.rollIcon=zot(w)?null!=K.rollIcon?K.rollIcon.clone():null:w,$.waitIcon=zot(X)?null!=K.waitIcon?K.waitIcon.clone():null:X,$.rollWaitIcon=zot(R)?null!=K.rollWaitIcon?K.rollWaitIcon.clone():null:R,$.toggleIcon=zot(T)?null!=K.toggleIcon?K.toggleIcon.clone():null:T,$.rollToggleIcon=zot(A)?null!=K.rollToggleIcon?K.rollToggleIcon.clone():null:A;var ie,ae,le=["icon","rollIcon","toggleIcon","rollToggleIcon","waitIcon","rollWaitIcon"];for(ne=0;ne<le.length;ne++){var se=le[ne],ce=$[se];ce&&(ce.x=n/2,ce.y=r/2)}if($.icon&&$.addChild($.icon),Array.isArray(u)||(u=[u,u,u,u]),0<p){var ue=new createjs.Shape;ue.graphics.lf(["rgba(255,255,255,"+p+")","rgba(0,0,0,"+p+")"],[0,1],0,0,0,r-e),ue.graphics.rc(e/2,e/2,n-e,r-e,u[0],u[1],u[2],u[3]),this.addChild(ue)}if(0<f){var de=new createjs.Shape;de.graphics.f("rgba(255,255,255,"+f+")"),de.graphics.rc(e/2,e/2,n-e,(r-e)/2,u[0],u[1],0,0),de.graphics.f("rgba(0,0,0,"+f+")"),de.graphics.rc(e/2,r/2,n-e,(r-e)/2,0,0,u[2],u[3]),this.addChild(de)}function he(){(ae=new createjs.Shape).graphics.f("#000").r(-g,-g,n+2*g,r+2*g),$.hitArea=ie=ae}if(0<g&&he(),this.addChild(t),t.center(this),t.y+=1,this.label=t,kt.pos(t,"left"==_||"right"==_?H:null,"top"==W||"bottom"==W?V:null,"right"==_,"bottom"==W),this.toggled=!1,J){var ge=t.text;this.on(P,function(){$.toggled=!$.toggled,pe()})}function pe(){$.toggled?(zot(x)||($.text=x),$.rolled?($.rollToggleBacking?Ae("rollToggleBacking",$.rollToggleBacking):$.toggleBacking&&Ae("toggleBacking",$.toggleBacking),$.rollToggleIcon?Ae("rollToggleIcon",$.rollToggleIcon):$.toggleIcon&&Ae("toggleIcon",$.toggleIcon)):($.toggleBacking&&Ae("toggleBacking",$.toggleBacking),$.toggleIcon&&Ae("toggleIcon",$.toggleIcon))):($.text=ge,fe()),$.stage&&$.stage.update()}function fe(){$.rolled?(zot(z)&&!$.rollBacking&&($.backing.color=a),$.rollBacking?Ae("rollBacking",$.rollBacking):$.backing&&Ae("backing",$.backing),$.rollIcon?Ae("rollIcon",$.rollIcon):$.icon?Ae("icon",$.icon):Ae("icon",null)):(zot(z)&&($.backing.color=i),$.backing&&Ae("backing",$.backing),$.icon?Ae("icon",$.icon):Ae("icon",null))}var me,ze,ve,ye,be=!(this.toggle=function(e){return J?(zot(e)?$.toggled=!$.toggled:$.toggled=e,pe()):zon&&zog("zim.Button() - can't toggle with wait parameters provided"),$}),we=$.waiting=!1,xe=$.label.color,Ce=$.label.rollColor,ke=this.on("mousedown",function(){be=!0,Te()});function Te(){zot(B)&&zot(L)&&zot(Y)||$.waiting||(we=!0,zot(D)&&(D=!0),j&&(ye=$.stage.on("stagemousedown",function(e){$.hitTestPoint(e.stageX,e.stageY)||$.clearWait()},null,!0)),setTimeout(function(){$.waiting=!0},50),ze=t.text,zot(M)||($.label.color=M),zot(O)||($.label.rollColor=O),ve=$.enabled,!D&&$.enabled&&($.enabled=!1),zot(B)||($.text=B),$.rolled?(zot(z)&&!$.rollWaitBacking&&($.backing.color=E),$.rollWaitBacking?Ae("rollWaitBacking",$.rollWaitBacking):$.waitBacking&&Ae("waitBacking",$.waitBacking),$.rollWaitIcon?Ae("rollWaitIcon",$.rollWaitIcon):$.waitIcon&&Ae("waitIcon",$.waitIcon)):(zot(z)&&!$.waitBacking&&($.backing.color=S),$.waitBacking&&Ae("waitBacking",$.waitBacking),$.waitIcon&&Ae("waitIcon",$.waitIcon)),zot(I)&&(I=3e4),me&&me.clear(),me=timeout(I,function(){$.enabled||($.enabled=ve),$.clearWait(),$.dispatchEvent("waited")}),$.stage&&$.stage.update())}function Ae(e,t){if(0<=e.indexOf("con")){for(var o=0;o<le.length;o++){var n=le[o],r=$[n];$.removeChild(r)}$[e]&&$.addChildAt($[e],1)}else{if(!$[e])return;for(o=0;o<oe.length;o++){var i=oe[o],a=$[i];$.removeChild(a)}$[e]&&$.addChildAt($[e],0)}}this.wait=function(){Te()},this.clearWait=function(){return me&&(ye&&$.stage.off("stagemousedown",ye),me.clear(),$.text=ze,fe(),$.label.color=xe,$.label.rollColor=Ce,setTimeout(function(){$.waiting=!1},55),we=!1,$.stage&&$.stage.update()),$},this.removeWait=function(){return $.clearWait(),B=null,$.waitBacking=null,$.rollWaitBacking=null,$.off("mousedown",ke),$},this.on("pressup",function(){be=!1,$.rollPersist&&!Pe&&Be()});var Pe=!1;function Be(){$.rolled=!1,we||$.waiting?(zot(z)&&zot($.waitBacking)&&($.backing.color=zot(S)?i:S),$.waitBacking?Ae("waitBacking",$.waitBacking):Ae("backing",$.backing),$.waitIcon?Ae("waitIcon",$.waitIcon):$.icon?Ae("icon",$.icon):Ae("icon")):$.toggled&&J?(zot(z)&&zot($.toggleBacking)&&($.backing.color=i),$.toggleBacking?Ae("toggleBacking",$.toggleBacking):Ae("backing",$.backing),$.toggleIcon?Ae("toggleIcon",$.toggleIcon):$.icon?Ae("icon",$.icon):Ae("icon")):(zot(z)?$.backing.color=i:zot(z.mask)||($.backing.mask.color=i),Ae("backing",$.backing),$.icon?Ae("icon",$.icon):Ae("icon")),$.border&&($.border.borderColor=s),$.label.showRollColor&&$.label.showRollColor(!1),$.stage&&$.stage.update()}function Ie(e,t){return zot(e)||($.contains($[e])&&($.removeChild($[e]),t&&$.addChildAt(t,0<=e.indexOf("con")?$.numChildren-1:0),$.stage&&$.stage.update()),t?(zot(z)&&"backing"==e&&(z=t),"Pattern"==t.type&&(t=re(e,t)),$[e]=t,$[e].x=n/2,$[e].y=r/2):$[e]=null),$}this.on("mouseover",function(e){$.rolled=!0,Pe=!0,we?(zot(z)&&zot($.rollWaitBacking)&&($.backing.color=zot(E)?a:E),Ae("rollWaitBacking",$.rollWaitBacking),$.rollWaitIcon&&Ae("rollWaitIcon",$.rollWaitIcon)):J&&$.toggled?(zot(z)&&zot($.rollToggleBacking)&&($.backing.color=a),Ae("rollToggleBacking",$.rollToggleBacking),$.rollToggleIcon&&Ae("rollToggleIcon",$.rollToggleIcon)):(zot(z)?$.backing.color=a:zot(z.mask)||($.backing.mask.color=a),Ae("rollBacking",$.rollBacking),$.rollIcon&&Ae("rollIcon",$.rollIcon));$.border&&($.border.borderColor=c);$.label.showRollColor&&$.label.showRollColor();$.stage&&$.stage.update()}),this.on("mouseout",function e(t){Pe=!1;$.off("mouseout",e);$.rollPersist&&be||Be()}),Object.defineProperty($,"text",{get:function(){return" "==t.text?"":t.text},set:function(e){t.text=e,t.center(this),t.y+=1}}),Object.defineProperty($,"color",{get:function(){return o},set:function(e){o=e,$.label&&!zot($.label.color)&&($.label.color=o),kt.OPTIMIZE||!zns&&OPTIMIZE||!$.stage||$.stage.update()}}),Object.defineProperty($,"rollColor",{get:function(){return l},set:function(e){l=e,$.label&&($.label.rollColor=l)}}),Object.defineProperty($,"backgroundColor",{get:function(){return i},set:function(e){i=e,$.backing.color?$.backing.color=i:$.backing.mask&&($.backing.mask.color=i),kt.OPTIMIZE||!zns&&OPTIMIZE||!$.stage||$.stage.update()}}),Object.defineProperty($,"rollBackgroundColor",{get:function(){return a},set:function(e){a=e,$.rollBacking&&$.rollBacking.color?$.rollBacking.color=a:$.rollBacking&&$.rollBacking.mask&&($.rollBacking.mask.color=a)}}),Object.defineProperty($,"borderColor",{get:function(){return s},set:function(e){s=e,$.rolled||($.backing&&$.backing.borderColor&&($.backing.borderColor=e),$.border&&($.border.borderColor=e))}}),Object.defineProperty($,"borderRollColor",{get:function(){return c},set:function(e){c=e,$.rolled&&($.backing&&$.backing.borderColor&&($.backing.borderColor=e),$.border&&($.border.borderColor=e))}}),Object.defineProperty($,"hitPadding",{get:function(){return g},set:function(e){0==(g=e)?ie&&(this.hitArea=null):he()}}),this._enabled=!0,this.startMouseChildren=this.mouseChildren,Object.defineProperty($,"enabled",{get:function(){return $._enabled},set:function(e){$._enabled&&($.startMouseChildren=$.mouseChildren),e?(Se($,e),$.mouseChildren=$.startMouseChildren):(Be(),Se($,e)),t.color=t.color,kt.OPTIMIZE||!zns&&OPTIMIZE||!$.stage||$.stage.update()}}),this.setBacking=function(e,t){Ie(e,t)},!(this.setIcon=function(e,t){Ie(e,t)})!==N&&!1!==N&&Oe(this,K),this.clone=function(){var e=new kt.Button(n,r,t.clone(),i,a,o,l,Z,c,Q,u,d,h,g,p,f,m,zot(z)?null:$.backing.clone(),zot(v)?null:$.rollBacking.clone(),y,zot(b)?null:b.clone(),zot(w)?null:w.clone(),x,zot(C)?null:C.clone(),zot(k)?null:k.clone(),zot(T)?null:T.clone(),zot(A)?null:A.clone(),P,B,I,S,E,M,O,j,D,zot(L)?null:L.clone(),zot(Y)?null:Y.clone(),zot(X)?null:X.clone(),zot(R)?null:R.clone(),_,W,F,H,V,N,this.group);return $.cloneProps(e)}},kt.extend(kt.Button,kt.Container,"clone","zimContainer",!1),kt.CheckBox=function(t,o,e,n,r,i,a,l,s,c,u,d,h,p){var f;if(f=zob(kt.CheckBox,arguments,"size, label, startChecked, color, backgroundColor, borderColor, borderWidth, corner, margin, indicatorType, indicatorColor, style, group, inherit",this))return f;z_d("56"),this.zimContainer_constructor(null,null,null,null,!1),this.type="CheckBox",this.group=h;var m=!1===d?{}:kt.getStyle(this.type,this.group,p);zot(t)&&(t=null!=m.size?m.size:60),zot(o)&&(o=null!=m.label?m.label:null),zot(e)&&(e=null!=m.startChecked&&m.startChecked);var z=e;zot(n)&&(n=null!=m.color?m.color:"#111"),zot(r)&&(r=null!=m.backgroundColor?m.backgroundColor:"rgba(255,255,255,.8)"),zot(i)&&(i=null!=m.borderColor?m.borderColor:"#111"),zot(a)&&(a=null!=m.borderWidth?m.borderWidth:t/10),i<0||a<0?i=a=null:null!=i&&null==a&&(a=t/10),zot(l)&&(l=null!=m.corner?m.corner:0),"string"!=typeof o&&"number"!=typeof o||(o=new kt.Label({text:o,size:5*t/6,color:n,valign:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),zot(s)&&(s=null!=m.margin?m.margin:t/5),"box"!=c&&"square"!=c&&"x"!=c&&(c=null!=m.indicatorType?m.indicatorType:"check"),zot(u)&&(u=null!=m.indicatorColor?m.indicatorColor:0<a?i:"black"),this.setBounds(-s,-s,t+2*s,t+2*s);var v=this;this.cursor="pointer";var y=new kt.Rectangle(t,t,r,null,null,l),b=new kt.Rectangle(5*t/7,5*t/7,"rgba(0,0,0,0)",i,a,l);b.x=t/7,b.y=t/7,this.addChild(y,b);var w=t;o&&(o.center(v),o.x=v.getBounds().width,this.label=o,this.setBounds(-s,-s,t+3*s+o.getBounds().width,Math.max(t+2*s,o.getBounds().height)),w=o.x+o.width);var x=new kt.Shape({style:!1});g=x.graphics,g.f("rgba(0,0,0,.01)").r(this.getBounds().x,this.getBounds().y,w+2*s,this.getBounds().height),this.hitArea=x;var C=new kt.Shape({style:!1}),k=C.graphics;"check"==c?k.f(u).p("AnQAdICBiaIEEDZIF8nfICfB4In/KPg"):"box"==c||"square"==c?k.f(u).dr(-35,-35,70,70):k.f(u).p("AmJEVIEUkTIkXkWIB4h5IEWEYIETkTIB4B3IkTESIEQERIh4B4IkRkRIkSEVg");C.setBounds(-47.5,-47.5,95,95);var T=t/161;C.scaleX=C.scaleY=T,C.alpha=.9,C.x=t/2,C.y=t/2,z&&this.addChild(C),this.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(e){z=!z,v.setChecked(z),v.dispatchEvent("change")}),Object.defineProperty(v,"checked",{get:function(){return z},set:function(e){v.setChecked(e)}}),Object.defineProperty(v,"text",{get:function(){if(o)return o.text},set:function(e){o&&(o.text=e,kt.OPTIMIZE||!zns&&OPTIMIZE||!v.stage||v.stage.update())}}),Object.defineProperty(C,"indicatorColor",{get:function(){return u},set:function(e){z&&v.removeChild(C),C=new createjs.Shape,k=C.graphics,u=e,k.f(u).p("AnQAdICBiaIEEDZIF8nfICfB4In/KPg"),C.scaleX=C.scaleY=T,C.alpha=.9,C.x=t/2,C.y=t/2,z&&v.addChild(C),kt.OPTIMIZE||!zns&&OPTIMIZE||!v.stage||v.stage.update()}}),Object.defineProperty(v,"indicator",{get:function(){return C},set:function(e){zog("ZIM CheckBox - check is read only")}}),this._enabled=!0,Object.defineProperty(v,"enabled",{get:function(){return v._enabled},set:function(e){Se(v,e)}}),!(this.setChecked=function(e){return zot(e)&&(e=!0),(z=e)?v.addChild(C):v.removeChild(C),kt.OPTIMIZE||!zns&&OPTIMIZE||!v.stage||v.stage.update(),v})!==d&&Oe(this,m),this.clone=function(){return v.cloneProps(new kt.CheckBox(t,o?o.clone():"",e,n,r,i,a,l,s,c,u,d,this.group,p))}},kt.extend(kt.CheckBox,kt.Container,"clone","zimContainer",!1),kt.RadioButtons=function(s,a,l,c,u,d,h,g,p,o,f,n,e,r){var t;if(t=zob(kt.RadioButtons,arguments,"size, buttons, vertical, color, backgroundColor, borderColor, borderWidth, spacing, margin, always, indicatorColor, style, group, inherit",this))return t;z_d("57"),this.zimContainer_constructor(null,null,null,null,!1),this.type="RadioButtons",this.group=e;var m=!1===n?{}:kt.getStyle(this.type,this.group,r);zot(s)&&(s=null!=m.size?m.size:60),s=Math.max(5,s),zot(a)&&(a=null!=m.buttons?m.buttons:["A","B","C"]),zot(l)&&(l=null==m.vertical||m.vertical),zot(c)&&(c=null!=m.color?m.color:"#111"),zot(u)&&(u=null!=m.backgroundColor?m.backgroundColor:"rgba(255,255,255,.8)"),zot(d)&&(d=null!=m.borderColor?m.borderColor:"#111"),zot(h)&&(h=null!=m.borderWidth?m.borderWidth:s/9),d<0||h<0?d=h=null:null!=d&&null==h&&(h=s/10),zot(g)&&(g=l?null!=m.spacing?m.spacing:.2*s:null!=m.spacing?m.spacing:s),zot(p)&&(p=null!=m.margin?m.margin:s/5),zot(f)&&(f=null!=m.indicatorColor?m.indicatorColor:0<h?d:"black");var z,v=this;if(this.cursor="pointer",this.labels=[],this.indicators=[],"string"==typeof a){var i=a;a=[];for(var y=0;y<i.length;y++)a.push({label:i[y]})}var b=new kt.Container({style:!1});function w(e){var t=b.getChildIndex(e.target);o&&v.selectedIndex==t||(v.setSelected(t),v.dispatchEvent("change"))}this.addChild(b),function(){for(var e,t,o=!1,n=a.length-1;0<=n;n--)(e=a[n]).selected&&!0===e.selected&&(o?e.selected="false":(o=!0,v.id=e.id));b.removeAllChildren(),v.buttons=[];for(var r=0,n=0;n<a.length;n++){if("string"==typeof(e=a[n])||"number"==typeof e){var i={selected:!1,label:new kt.Label({text:e,size:5*s/6,color:null!=m.color?m.color:c,valign:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:v.group})};e=i}(e.label&&"string"==typeof e.label||"number"==typeof e.label)&&(e.label=new kt.Label({text:e.label,size:null!=m.size?m.size:5*s/6,color:null!=m.color?m.color:c,valign:"center"})),v.labels.push(e.label),e.index=n,a[n]=e,(t=C(e.selected,e.label)).type="RadioButton",(t.obj=e).selected&&(z=t.obj),b.addChild(t),l?(t.y=r,r+=t.getBounds().height+g):(t.x=r,r+=t.getBounds().width+g)}}();for(var x=0;x<b.numChildren;x++)b.getChildAt(x).on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",w);function C(e,t){var o=new kt.Container({style:!1});v.buttons.push(o),o.mouseChildren=!1,o.setBounds(-p,-p,s+2*p,s+2*p);var n=new kt.Shape({style:!1}),r=n.graphics;r.f(u).dc(s/2,s/2,s/1.85),r.s(d).ss(h).dc(s/2,s/2,s/2-s/2/5),o.addChild(n);var i=o.check=new kt.Circle(s/5.2,f,null,null,null,null,!1);v.indicators.push(i),i.mouseEnabled=!1,i.alpha=.95,i.regX=i.regY=-s/2;var a=s;t&&(o.addChild(t),t.x=o.getBounds().width,t.y=s/2,o.setBounds(-p,-p,s+2*p+t.getBounds().width,Math.max(s+2*p,t.getBounds().height)),a=t.x+t.width,o.text=t.text),e&&(o.addChild(i),v.label=t,v.label&&(v.text=t.text));var l=new kt.Shape({style:!1});return(r=l.graphics).f("rgba(0,0,0,.01)").r(o.getBounds().x,o.getBounds().y,a+2*p,o.getBounds().height),o.hitArea=l,o}this.getBounds()||this.setBounds(0,0,s,s),this.setBounds(-p,-p,this.getBounds().width+2*p,this.getBounds().height),this.setSelected=function(e){if(zot(e)&&(e=-1),-1==e||b.getChildAt(e)){for(var t,o=0;o<b.numChildren;o++)(t=b.getChildAt(o)).removeChild(t.check);if(0<=e){t=b.getChildAt(e);var n=-2;z&&(n=z.index),z=t.obj}return-1==e||n==z.index?(z=null,v.id=null,v.label=null,v.text=""):(t.addChild(t.check),v.id=z.id,v.label=z.label,v.label&&(v.text=v.label.text)),kt.OPTIMIZE||!zns&&OPTIMIZE||!v.stage||v.stage.update(),v}},Object.defineProperty(v,"selected",{get:function(){return z},set:function(e){zog("ZIM RadioButton - selected is read only")}}),Object.defineProperty(v,"selectedIndex",{get:function(){return z?z.index:-1},set:function(e){var t=e;o&&v.selectedIndex==t||v.setSelected(t)}}),this._enabled=!0,Object.defineProperty(v,"enabled",{get:function(){return v._enabled},set:function(e){Se(v,e)}}),Oe(this,m),this.clone=function(){for(var e=kt.copy(a),t=0;t<e.length;t++)e[t].label=e[t].label.clone();return v.cloneProps(new kt.RadioButtons(s,e,l,c,u,d,h,g,p,o,f,n,this.group,r))}},kt.extend(kt.RadioButtons,kt.Container,"clone","zimContainer",!1),kt.Toggle=function(o,r,t,e,i,n,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b){var w;if(w=zob(kt.Toggle,arguments,"width, height, label, startToggled, backgroundColor, margin, indicatorType, indicatorColor, toggleBackgroundColor, color, borderColor, borderWidth, corner, indicatorCorner, shadowColor, shadowBlur, time, labelLeft, style, group, inherit",this))return w;z_d("57.5"),this.group=y;var x=!1===v?{}:kt.getStyle("Toggle",this.group,b);zot(o)&&(o=null!=x.width?x.width:80),zot(r)&&(r=null!=x.height?x.height:50),this.zimContainer_constructor(o,r,null,null,!1),this.type="Toggle",zot(i)&&(i=null!=x.backgroundColor?x.backgroundColor:"#C60"),zot(n)&&(n=null!=x.margin?x.margin:10),zot(a)&&(a=null!=x.indicatorType?x.indicatorType:"circle"),zot(l)&&(l=null!=x.indicatorColor?x.indicatorColor:"#fff"),zot(s)&&(s=null!=x.toggleBackgroundColor?x.toggleBackgroundColor:"#F93"),zot(c)&&(c=null!=x.color?x.color:"#111"),zot(u)&&(u=null!=x.borderColor?x.borderColor:null),zot(d)&&(d=null!=x.borderWidth?x.borderWidth:null),u<0||d<0?u=d=null:null!=u&&null==d&&(d=1),zot(h)&&(h=null!=x.corner?x.corner:"circle"!=a?0:25),zot(g)&&(g=null!=x.indicatorCorner?x.indicatorCorner:0),zot(p)&&(p=null!=x.shadowColor?x.shadowColor:"rgba(0,0,0,.3)"),zot(f)&&(f=null!=x.shadowBlur?x.shadowBlur:14),zot(e)&&(e=null!=x.startToggled&&x.startToggled),zot(m)&&(m=null!=x.time?x.time:100);var C=this;function k(e){var t=C.indicator.x,o=m;if(!0===e&&(o=0),"rectangle"==a||"square"==a?C.indicator.pos(.2*r,null,C.toggled):C.indicator.pos(.175*r,null,C.toggled),0<m&&C.indicator.animate({props:{x:t},from:!0,time:o}),C.background.color=C.toggled?s:i,C.zimAccessibility){var n="Toggle set to "+(C.toggled?C.label?C.label.text+".":"on.":C.labelLeft?C.labelLeft.text+".":"off.");setTimeout(function(){C.zimAccessibility.talk(n)},50)}}C.cursor="pointer","string"!=typeof t&&"number"!=typeof t||(t=this.label=new kt.Label({text:t,size:5*r/6,color:c,valign:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),"string"!=typeof z&&"number"!=typeof z||(z=this.labelLeft=new kt.Label({text:z,size:5*r/6,color:c,valign:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),this.background=new kt.Rectangle(o,r,i,u,d,h).addTo(this),this.indicator="rectangle"==a||"square"==a?new kt.Rectangle(.65*r,.65*r,l,null,null,g).center(this.background).pos(.2*r,null,e):new kt.Circle(.35*r,l).center(this.background).pos(.175*r,null,e),this.toggled=e,C.background.color=C.toggled?s:i,-1!=p&&0<f&&(this.background.shadow=new createjs.Shadow(p,3,3,f)),t&&(this.addChild(t),t.x=o+2+n+d,t.y=r/2,this.label=t,this.setBounds(-n,-n,o+3*n+d+t.getBounds().width,Math.max(r+2*n,t.getBounds().height))),z&&(this.addChild(z),z.x=0,C.background.x+=z.width+3+n+d,C.label.x+=z.width+3+n+d,z.y=r/2,this.labelLeft=z,this.setBounds(-n,-n,C.getBounds().width+z.width+3+n+d,C.getBounds().height)),this.expand(kt.mobile()?20:10),this.tap(function(e){if(z){var t=C.localToGlobal(z.width+3+n+d+o/2,0);if(e.stageX<t.x-o/2&&!C.toggled||e.stageX>=t.x+o/2&&C.toggled)return}C.toggled=!C.toggled,k(),C.dispatchEvent("change")},kt.mobile()?20:10),new kt.Swipe(this).on("swipe",function(e){0!=e.swipeX&&(1==e.swipeX&&C.toggled||(-1!=e.swipeX||C.toggled)&&(C.toggled=!C.toggled,k(),C.dispatchEvent("change")))}),Object.defineProperty(C,"text",{get:function(){if(t)return t.text},set:function(e){t&&(t.text=e,kt.OPTIMIZE||!zns&&OPTIMIZE||!C.stage||C.stage.update())}}),Object.defineProperty(C,"textLeft",{get:function(){if(z)return z.text},set:function(e){z&&(z.text=e,kt.OPTIMIZE||!zns&&OPTIMIZE||!C.stage||C.stage.update())}}),C.toggle=function(e,t){var o=C.toggled;return zot(e)&&(e=!0),C.toggled=e,o!=C.toggled&&k(t),C},this._enabled=!0,Object.defineProperty(C,"enabled",{get:function(){return C._enabled},set:function(e){Se(C,e)}}),!1!==v&&Oe(this,x),this.clone=function(){return C.cloneProps(new kt.Toggle(o,r,t?t.clone():"",e,i,n,a,l,s,c,u,d,h,g,p,f,m,z?z.clone():"",v,this.group,b))}},kt.extend(kt.Toggle,kt.Container,"clone","zimContainer",!1),kt.Tip=function(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X){var R;if(R=zob(kt.Tip,arguments,"text, align, valign, margin, marginH, marginV, outside, target, size, font, color, rollColor, shadowColor, shadowBlur, textAlign, textValign, lineWidth, lineHeight, fontOptions, backing, outlineColor, outlineWidth, backgroundColor, backgroundBorderColor, backgroundBorderWidth, corner, backgroundDashed, padding, paddingHorizontal, paddingVertical, shiftHorizontal, shiftVertical, rollPersist, labelWidth, labelHeight, maxSize, style, group, inherit",this))return R;z_d("57.6"),this.group=Y;var _=!1===L?{}:kt.getStyle("Tip",this.group,X);zot(e)&&(e=null!=_.text?_.text:"Here's a tip!"),zot(n)&&(n=null!=_.margin?_.margin:40),zot(r)&&(r=null!=_.marginH?_.marginH:n),zot(i)&&(i=null!=_.marginV?_.marginV:n),zot(t)&&(t=null!=_.align?_.align:"right"),zot(o)&&(o=null!=_.valign?_.valign:"bottom"),zot(a)&&(a=null!=_.outside&&_.outside),zot(x)&&(x=null!=_.backgroundColor?_.backgroundColor:blue),zot(u)&&(u=null!=_.color?_.color:white),zot(T)&&(T=null!=_.corner?_.corner:25),zot(T)&&(T=null!=_.corner?_.corner:25),zot(T)&&(T=null!=_.corner?_.corner:25),zot(B)&&(B=null!=_.paddingHorizontal?_.paddingHorizontal:14+(Array.isArray(T)?T[0]:T)),(zot(h)||"ignore"==h)&&(h=null!=_.shadowColor&&"ignore"!=h?_.shadowColor:"rgba(0,0,0,.3)"),(zot(g)||"ignore"==g)&&(g=null!=_.shadowBlur&&"ignore"!=g?_.shadowBlur:1),this.zimLabel_constructor(e,s,c,u,d,null,null,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,_),this.type="Tip",a&&(r=-r,i=-i);var W=this;W.align=t,W.valign=o,this.background.sha(h,3,5,g),this.show=function(e,o){zot(e)&&(e=null!=_.delay?_.delay:0),zot(o)&&(o=null!=_.time?_.time:2e3);var t="zim Tip(): Please pass in a reference to a container with bounds set as parameter to Tip";if(zot(l)){if(!zimDefaultFrame)return zog(t),W;l=zimDefaultFrame.stage}else{if(!l.getBounds)return zog(t),W;if(zot(l.stage))return zog("zim display - Waiter(): The container must have a stage property"),W}function n(){if(l.boundsToGlobal)var e=l.boundsToGlobal();else e=l.getBounds();var t=new Container(e.x,e.y,e.width,e.height);t.zimTemp=!0,t.loc(0,0,l.stage),"center"!=W.align&&"middle"!=W.align&&"center"!=W.valign&&"middle"!=W.valign||W.center(t),W.pos("center"==W.align||"middle"==W.align?null:r,"center"==W.valign||"middle"==W.valign?null:i,"right"==W.align,"bottom"==W.valign,t),a&&("right"==W.align?W.x+=W.width:"left"==W.align&&(W.x-=W.width),"bottom"==W.valign?W.y+=W.height:"top"==W.valign&&(W.y-=W.height)),W.addTo(t.stage),t.zimTemp&&t.removeFrom&&(t.removeFrom(),t=null),t=W.stage,W.timeoutID&&W.timeoutID.clear(),W.timeoutID=kt.timeout(o,function(){W.hide(),t.stage.update()}),W.upID&&t.stage.off("stagemouseup",W.upID),W.upID=t.stage.on("stagemouseup",function(){W.hide(),t.stage.update()}),t.stage.update()}return 0<e?W.showID=kt.timeout(e,n):n(),W},this.hide=function(){return this.removeFrom(),this.timeoutID&&this.timeoutID.clear(),this.upID&&l.stage.off("stagemouseup",this.downID),W},!(this.clear=function(){W.showID&&W.showID.clear(),W.hide()})!==L&&Oe(this,_),this.clone=function(){return W.cloneProps(new kt.Tip(e,t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,this.group,X))}},kt.extend(kt.Tip,kt.Label,"clone","zimLabel",!1),kt.Panel=function(e,t,o,l,s,n,c,u,r,i,a,d,h,g,p,f,m,z,v,y){var b;if(b=zob(kt.Panel,arguments,"width, height, titleBar, titleBarColor, titleBarBackgroundColor, titleBarHeight, backgroundColor, borderColor, borderWidth, corner, arrow, align, shadowColor, shadowBlur, draggable, boundary, extraButton, style, group, inherit",this))return b;z_d("57.7"),this.group=v;var w=!1===z?{}:kt.getStyle("Panel",this.group,y);zot(e)&&(e=null!=w.width?w.width:250),zot(t)&&(t=null!=w.height?w.height:300),this.zimContainer_constructor(e,t,null,null,!1),this.type="Panel",zot(o)&&(o=null!=w.titleBar?w.titleBar:"PANEL"),zot(l)&&(l=null!=w.titleBarColor?w.titleBarColor:"#fff"),zot(s)&&(s=null!=w.titleBarBackgroundColor?w.titleBarBackgroundColor:"#555"),zot(n)&&(n=null!=w.titleBarHeight?w.titleBarHeight:30),zot(c)&&(c=null!=w.backgroundColor?w.backgroundColor:"#eee"),zot(u)&&(u=null!=w.borderColor?w.borderColor:"#888"),zot(r)&&(r=null!=w.borderWidth?w.borderWidth:null),u<0||r<0?u=r=null:null!=u&&null==r&&(r=1),zot(i)&&(i=null!=w.corner?w.corner:5),zot(d)&&(d=null!=w.align?w.align:"left"),zot(h)&&(h=null!=w.shadowColor?w.shadowColor:"rgba(0,0,0,.3)"),zot(g)&&(g=null!=w.shadowBlur?w.shadowBlur:14),zot(p)&&(p=null!=w.draggable&&w.draggable),zot(f)&&(f=null!=w.boundary?w.boundary:null),zot(a)&&(a=null!=w.arrow?w.arrow:kt.vee(o)),Array.isArray(i)||(i=[i,i,i,i]);var x=this;this.background=new kt.Rectangle(e,t,c,u,r,i).addTo(this);-1!=h&&0<g&&(this.background.shadow=new createjs.Shadow(h,3,3,g));var C=o,k=kt.Pick.choose(C),T=kt.Pick.choose(l),A=kt.Pick.choose(s);kt.Pick.choose(c),kt.Pick.choose(u);"string"==typeof k&&(k=new kt.Label({text:k,color:T,size:null!=w.size?w.size:20,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group}));var P=x.titleBarLabel=k;zot(A)&&(A="rgba(0,0,0,.2)"),x.titleBar=o=new kt.Container(e,n,null,null,!1).loc(0,0,x);var B=x.titleBar.backing=new kt.Rectangle(e+r,n,A,null,null,[.95*i[0],.95*i[1],0,0],!0,!1).center(o);function I(){"right"==d?P.center(o).pos(Math.max(i[0]/2,10),null,!0):"center"==d||"middle"==d?P.center(o):P.center(o).loc(Math.max(i[0]/2,10))}if(I(),x.label=k,x.text=k.text,this.nextPanel=function(e,t){var o=zot(e)||zot(C.array)?kt.Pick.choose(C):C.array[e],n=zot(e)||zot(l.array)?kt.Pick.choose(l):l.array[e],r=zot(e)||zot(s.array)?kt.Pick.choose(s):s.array[e],i=zot(e)||zot(c.array)?kt.Pick.choose(c):c.array[e],a=zot(e)||zot(u.array)?kt.Pick.choose(u):u.array[e];"string"==typeof o&&(o=new kt.Label({text:o,color:n,size:null!=w.size?w.size:20,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),x.label=o,x.text=o.text,P.removeFrom(),P=x.titleBarLabel=o,I(),B.color=r,x.background.color=i,x.background.borderColor=a,t&&x.dispatchEvent("change"),!OPTIMIZE&&x.stage&&x.stage.update()},p&&(o.cursor="pointer",o.on("mousedown",function(){x.drag({rect:f,currentTarget:!0})}),o.on("pressup",function(){x.noDrag()})),0<a){var S=x.arrow=new kt.Shape(-20,-20,40,40,null,!1);S.graphics.f(l).p("AiJieIETCeIkTCfg"),S.centerReg(o).scaleTo(o,null,70).alp(.8).hov(1).expand(),"right"==d?S.pos(Math.max(i[1]/2,10)):S.pos(Math.max(i[1]/2,10),null,!0),S.cursor="pointer",S.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){x.nextPanel(),x.dispatchEvent("change")})}if(!zot(m)){m=x.extraButton=new kt.Button({label:"R",width:50,height:50,group:"PanelExtra"}).scaleTo(o,null,70).centerReg(o).expand();"left"==d?m.pos(0<a?S.x-S.width-15:Math.max(i[1]/2,10)):m.pos(0<a&&"center"!=d?S.x+S.width:Math.max(i[1]/2,10))}x.overlay=new kt.Rectangle(e,t).alp(.7);this._enabled=!0,Object.defineProperty(x,"enabled",{get:function(){return x._enabled},set:function(e){Se(x,e),e?x.overlay.removeFrom():x.overlay.addTo(x),!OPTIMIZE&&x.stage&&x.stage.update()}}),!1!==z&&Oe(this,w),this.clone=function(){return x.cloneProps(new kt.Toggle(e,t,o?o.clone():"",l,s,n,c,u,r,i,a,d,h,g,p,f,m,z,this.group,y))}},kt.extend(kt.Panel,kt.Container,"clone","zimContainer",!1),kt.Pane=function(a,l,n,r,i,s,c,u,d,h,g,p,f,m,z,v,y,e,b,w,x,C,k,T,A,t,P){var o;if(o=zob(kt.Pane,arguments,"width, height, label, backgroundColor, color, draggable, resets, modal, corner, backdropColor, shadowColor, shadowBlur, center, displayClose, backdropClose, backing, fadeTime, container, titleBar, titleBarColor, titleBarBackgroundColor, titleBarHeight, close, closeColor, style, group, inherit",this))return o;z_d("58"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Pane";var B="zim display - Pane(): Please pass in a reference to a container with bounds set as first parameter";if(zot(e)){if(!zimDefaultFrame)return void zog(B);e=zimDefaultFrame.stage}else{if(!e.getBounds)return void zog(B);if(zot(e.getStage))return void zog("zim display - Pane(): The container must have a stage property")}this.group=t;var I=!1===A?{}:kt.getStyle(this.type,this.group,P);zot(a)&&(a=null!=I.width?I.width:200),zot(l)&&(l=null!=I.height?I.height:200),zot(n)&&(n=null!=I.label?I.label:null),"string"!=typeof n&&"number"!=typeof n||(n=new kt.Label({text:n,size:null!=I.size?I.size:40,align:null!=I.align?I.align:"center",valign:null!=I.valign?I.valign:"center",color:null!=I.color?I.color:i,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),zot(r)&&(r=null!=I.backgroundColor?I.backgroundColor:"white"),zot(s)&&(s=null!=I.draggable&&I.draggable),zot(c)&&(c=null==I.resets||I.resets),zot(u)&&(u=null==I.modal||I.modal),zot(d)&&(d=null!=I.corner?I.corner:20),zot(b)&&(b=null!=I.titleBar?I.titleBar:null),zot(w)&&(w=null!=I.titleBarColor?I.titleBarColor:null),zot(x)&&(x=null!=I.titleBarBackgroundColor?I.titleBarBackgroundColor:null),zot(C)&&(C=null!=I.titleBarHeight?I.titleBarHeight:null),zot(h)&&(h=null!=I.backdropColor?I.backdropColor:"rgba(0,0,0,.2)"),zot(g)&&(g=null!=I.shadowColor?I.shadowColor:"rgba(0,0,0,.3)"),zot(p)&&(p=null!=I.shadowBlur?I.shadowBlur:20),zot(f)&&(f=null==I.center||I.center),zot(m)&&(m=null==I.displayClose||I.displayClose),s&&(m=!1),zot(z)&&(z=null==I.backdropClose||I.backdropClose),zot(y)&&(y=null!=I.fadeTime?I.fadeTime:0),zot(k)&&(k=null!=I.close&&I.close),zot(T)&&(T=null!=I.closeColor?I.closeColor:"#555");var S=this.backdrop=new kt.Shape({style:!1});S.type="CreateJS_Shape";var E=S.graphics;E.f(h),E.drawRect(-5e3,-5e3,1e4,1e4),this.setBounds(-a/2,-l/2,a,l);var M=this;M.container=e,S.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",z?X:function(e){e.stopImmediatePropagation()});var O,j,D,L,Y=new kt.Dictionary(!0);function X(e){_(),M.container.stage.update(),M.dispatchEvent("close"),e.stopImmediatePropagation()}if(S.on("mousedown",function(e){e.stopImmediatePropagation()}),u&&this.addChild(S),zot(v))O=this.backing=this.display=new kt.Rectangle({width:a,height:l,color:r,corner:d,style:!1});else{if("Pattern"==v.type){var R=v;O=new kt.Rectangle(a,l,r,null,null,d,null,!1),R.centerReg(O),R.setMask(O.shape)}else O=v;M.display=M.backing=O}(m&&(O.cursor="pointer",O.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",X)),-1!=g&&0<p&&(O.shadow=new createjs.Shadow(g,8,8,p)),O.on("click",function(e){e.stopImmediatePropagation()}),this.resetX,this.resetY,s)&&(O.cursor="pointer",O.on("mousedown",function(e){isNaN(M.resetX)&&(M.resetX=M.x),isNaN(M.resetY)&&(M.resetY=M.y),j=e.stageX-M.x,D=e.stageY-M.y,O.cursor="pointer"}),O.on("pressmove",function(e){var t,o,n,r=(t=e.stageX-j,o=e.stageY-D,t=Math.max(a/2,Math.min(M.container.getBounds().width-a/2,t)),o=Math.max(l/2,Math.min(M.container.getBounds().height-l/2,o)),{x:t,y:o});M.x=r.x,M.y=r.y;for(var i=0;i<M.numChildren;i++)"TextArea"!=(n=M.getChildAt(i)).type&&"Loader"!=n.type&&"Tag"!=n.type||n.resize();M.container.stage.update()}),this.on("pressup",function(e){O.cursor="pointer",M.container.stage.update()}));if(O.centerReg(this),n&&(this.addChild(n),kt.center(n,this),this.label=n,this.text=n.text,n.mouseEnabled=!1),!zot(b)){"string"==typeof b&&(b=new kt.Label(b,null,null,w)),titleBarLabel=M.titleBarLabel=b,zot(C)&&(C=1.5*titleBarLabel.height),zot(w)&&(w="black"),zot(x)&&(x="rgba(0,0,0,.2)"),M.titleBar=b=new kt.Container(a,C,null,null,!1).centerReg(M).mov(0,-l/2+C/2),b.mouseEnabled=!1,b.mouseChildren=!1;M.titleBar.backing=new kt.Rectangle(a,C,x,null,null,[.95*d,.95*d,0,0],null,!1).addTo(b);titleBarLabel.center(b).pos({x:Math.max(d/2,10),reg:!0})}k&&((k=M.close=new kt.Shape(-40,-40,80,80,null,!1)).graphics.f(T).p("AmJEVIEUkTIkXkWIB4h5IEWEYIETkTIB4B3IkTESIEQERIh4B4IkRkRIkSEVg"),b?k.addTo(M).scaleTo(b,null,50).mov(a/2-Math.max(d/2,10)-k.width/2,-l/2+C/2).expand(40):k.addTo(M).sca(.3).mov(a/2-k.width-3,-l/2+k.height).expand(40),k.cursor="pointer",k.expand(),k.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",X));function _(){function e(){var e;M.container.removeChild(M);for(var t=0;t<M.numChildren;t++)if("TextArea"==(e=M.getChildAt(t)).type||"Loader"==e.type||"Tag"==e.type){var o={obj:e,depth:M.getChildIndex(e)};Y.add(e,o)}for(t=M.numChildren-1;0<=t;t--)"TextArea"!=(e=M.getChildAt(t)).type&&"Loader"!=e.type&&"Tag"!=e.type||M.removeChild(e);if(kt.OPTIMIZE||!zns&&OPTIMIZE||M.container.stage.update(),c&&(isNaN(M.resetX)||(M.x=M.resetX),isNaN(M.resetY)||(M.y=M.resetY)),M.zimAccessibility){var n=M.zimAccessibility;n.resize(M),L?L.focus():M.zimTabTag.nextSibling.focus(),setTimeout(function(){n.talk("Pane has been closed.")},50)}}0<y?M.animate({obj:{alpha:0},time:y,call:e}):e()}Object.defineProperty(M,"text",{get:function(){return" "==n.text?"":n.text},set:function(e){n.text=e}}),this._enabled=!0,Object.defineProperty(M,"enabled",{get:function(){return M._enabled},set:function(e){Se(M,e)}}),this.hide=function(){return _(),M.toggled=!1,M},this.show=function(){f&&isNaN(M.resetX)&&(M.x=M.container.getBounds().width/2,M.y=M.container.getBounds().height/2),M.container.addChild(M);for(var e=0;e<Y.length;e++)M.addChildAt(Y.values[e].obj,Y.values[e].depth);if(0<y?(M.alpha=0,M.animate({alpha:1},y)):M.container.stage&&M.container.stage.update(),M.zimAccessibility){var t=M.zimAccessibility;setTimeout(function(){t.activatedObject&&(L=t.activatedObject.zimTabTag)},50),t.resize(M),t.tabIndex=M.zimTabIndex}return M.toggled=!0,M},!(this.toggle=function(e){return!0===e?M.show():!1===e?M.hide():M.container.contains(M)?M.hide():M.show(),M})!==A&&Oe(this,I),this.clone=function(){var e=n.x,t=n.y,o=M.cloneProps(new kt.Pane(a,l,n.clone(),r,i,s,c,u,d,h,g,p,f,m,z,zot(v)?v.clone():null,y,M.container,b,w,x,C,k,T,A,this.group,P));return o.label.x=e,o.label.y=t,o}},kt.extend(kt.Pane,kt.Container,"clone","zimContainer",!1),kt.Window=function(u,d,o,e,h,n,g,p,f,m,t,r,i,z,v,a,l,s,y,c,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D){var L;if(L=zob(kt.Window,arguments,"width, height, backgroundColor, borderColor, borderWidth, padding, corner, swipe, scrollBarActive, scrollBarDrag, scrollBarColor, scrollBarAlpha, scrollBarFade, scrollBarH, scrollBarV, slide, slideDamp, slideSnap, interactive, shadowColor, shadowBlur, paddingHorizontal, paddingVertical, scrollWheel, damp, titleBar, titleBarColor, titleBarBackgroundColor, titleBarHeight, draggable, boundary, close, closeColor, style, group, inherit",this))return L;z_d("58.1"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Window",this.group=j;var Y=!1===O?{}:kt.getStyle(this.type,this.group,D);zot(u)&&(u=null!=Y.width?Y.width:300),zot(d)&&(d=null!=Y.height?Y.height:200),zot(o)&&(o=null!=Y.backgroundColor?Y.backgroundColor:"#333");var X=e,R=h;zot(e)&&(e=null!=Y.borderColor?Y.borderColor:"#999"),zot(h)&&(h=null!=Y.borderWidth?Y.borderWidth:1),zot(n)&&(n=null!=Y.padding?Y.padding:0),zot(g)&&(g=null!=Y.corner?Y.corner:0),zot(p)&&(p=null==Y.swipe||Y.swipe),zot(f)&&(f=null==Y.scrollBarActive||Y.scrollBarActive),zot(m)&&(m=null!=Y.scrollBarDrag&&Y.scrollBarDrag),zot(t)&&(t=null!=Y.scrollBarColor?Y.scrollBarColor:e),zot(r)&&(r=null!=Y.scrollBarAlpha?Y.scrollBarAlpha:.3),zot(i)&&(i=null==Y.scrollBarFade||Y.scrollBarFade),zot(z)&&(z=null==Y.scrollBarH||Y.scrollBarH),zot(v)&&(v=null==Y.scrollBarV||Y.scrollBarV),m&&(i=null!=Y.scrollBarFade&&Y.scrollBarFade),zot(a)&&(a=null==Y.slide||Y.slide),zot(l)&&(l=null!=Y.slideDamp?Y.slideDamp:.6),zot(s)&&(s=null!=Y.slideSnap?Y.slideSnap:"vertical"),zot(y)&&(y=null==Y.interactive||Y.interactive),zot(c)&&(c=null!=Y.shadowColor?Y.shadowColor:"rgba(0,0,0,.3)"),zot(b)&&(b=null!=Y.shadowBlur?Y.shadowBlur:20),zot(x)&&(x=null!=Y.paddingVertical?Y.paddingVertical:n),zot(w)&&(w=null!=Y.paddingHorizontal?Y.paddingHorizontal:n),zot(C)&&(C=null==Y.scrollWheel||Y.scrollWheel),zot(T)&&(T=null!=Y.titleBar?Y.titleBar:null),zot(A)&&(A=null!=Y.titleBarColor?Y.titleBarColor:null),zot(P)&&(P=null!=Y.titleBarBackgroundColor?Y.titleBarBackgroundColor:null),zot(B)&&(B=null!=Y.titleBarHeight?Y.titleBarHeight:null),zot(I)&&(I=null!=Y.draggable?Y.draggable:null),zot(S)&&(S=null!=Y.boundary?Y.boundary:null),zot(E)&&(E=null!=Y.close?Y.close:null),zot(M)&&(M=null!=Y.closeColor?Y.closeColor:null),!1===T&&(T=null),zot(T)||(zot(B)&&(B=30),d-=B);var _=this;this.scrollX=this.scrollY=this.scrollXMax=this.scrollYMax=0;var W=this.backing=new kt.Shape({style:!1});this.addChild(W);var F=new createjs.Shape;F.type="WindowBacking";var H=F.graphics;this.addChild(F);var V=this.content=new kt.Container({style:!1});if(this.addChild(V),V.mask=F,!y)var N=new createjs.Shape;if(0<h){var G=new createjs.Shape;this.addChild(G)}var q=T?0:g;function U(){_.setBounds(0,0,u,d),W.graphics.c().f(o).rc(0,0,u,d,q,q,g,g),-1!=c&&0<b&&(W.shadow=new createjs.Shadow(c,4,4,b)),0<h&&(g?G.graphics.c().s(e).ss(h,"square","miter").rc(0,0,u,d,q,q,g,g):G.graphics.c().s(e).ss(h,"square","miter").dr(0,0,u,d))}U();var K,Z,Q,J,$,ee,te,oe,ne,re=this.scrollBar={};if(re.color=t,re.size=6,re.minSize=2*re.size,re.spacing=3.5+h/2,re.margin=0,re.corner=re.size/2,re.showTime=500,re.fadeTime=3e3,f){var ie=re.horizontal=new kt.Shape({style:!1}),ae=ie.graphics;ie.alpha=r,this.addChild(ie),m&&ie.drag({localBounds:!0});var le=re.vertical=new kt.Shape({style:!1}),se=le.graphics;le.alpha=r,this.addChild(le),m&&le.drag({localBounds:!0})}if(this.update=function(){f&&(ae.clear(),se.clear()),$=f?re.size+2*re.spacing:0,ee=V.getBounds()?V.getBounds().width:0,te=V.getBounds()?V.getBounds().height:0,Q=z&&u-w<ee&&(f||!0===p||"auto"==p||"horizontal"==p),J=v&&d-x<te&&(f||!0===p||"auto"==p||"vertical"==p),_.scrollXMax=ee+2*w-u+(J?$+re.margin:0),_.scrollYMax=te+2*x-d+(Q?$+re.margin:0),H.clear();var e=h/2,t=h/2,o=u-(J&&f?re.size+2*re.spacing:0)-(J?0:h),n=d-(Q&&f?re.size+2*re.spacing:0)-(Q?0:h);H.f("rgba(0,0,0,0)").rc(e,t,o,n,q,q,J&&f?0:g,Q&&f?0:g),F.setBounds(_.getBounds().x,_.getBounds().y,_.getBounds().width,_.getBounds().height),kt.expand(F,0),y||(N.graphics.c().f("red").dr(e,t,o,n),V.hitArea=N);var r=Math.max(g,Math.min(re.corner,re.spacing)),i=r+h/2,a=r+(J?$:0)+h/2,l=r+h/2,s=r+(Q?$:0)+h/2;if(Q&&f&&(scrollBarLength=Math.max(re.minSize,(u-i-a)*(u-i-a)/(ee+w+re.margin)),ae.f(re.color).rr(0,0,scrollBarLength,re.size,re.corner),ie.x=i,ie.y=d-re.size-re.spacing,K=new kt.Proportion(-_.scrollXMax,0,i,u-scrollBarLength-a,-1),m)){ie.setBounds(0,0,scrollBarLength,re.size);var c=new createjs.Rectangle(i,ie.y,u-scrollBarLength-i-a,0);ie.dragBoundary(c),ie.proportion=new kt.Proportion(c.x,c.x+c.width,0,-_.scrollXMax),ie.off("pressmove",oe),oe=ie.on("pressmove",function(){_.dispatchEvent("scrolling"),V.x=ie.proportion.convert(ie.x)})}if(J&&f&&(scrollBarLength=Math.max(re.minSize,(d-l-s)*(d-l-s)/(te+x+re.margin)),se.f(re.color).rr(0,0,re.size,scrollBarLength,re.corner),le.x=u-re.size-re.spacing,le.y=l,Z=new kt.Proportion(-_.scrollYMax,0,l,d-scrollBarLength-s,-1),m)){le.setBounds(0,0,re.size,scrollBarLength);c=new createjs.Rectangle(le.x,l,0,d-scrollBarLength-l-s);le.dragBoundary(c),le.proportion=new kt.Proportion(c.y,c.y+c.height,0,-_.scrollYMax),le.off("pressmove",ne),ne=le.on("pressmove",function(){_.dispatchEvent("scrolling"),Be=V.y=le.proportion.convert(le.y)})}fe(),clearTimeout(_.dTimeout),_.dTimeout=setTimeout(function(){ce()},300)},this.resize=function(e,t){return zot(e)&&(e=u),zot(t)&&(t=d),u=e,d=t,U(),_.update(),Be=V.y,k&&Se.immediate(Be),_},!zot(T)){zot(I)&&(I=!0),"string"==typeof T&&(T=new kt.Label({text:T,color:A,size:null!=Y.size?Y.size:20,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),titleBarLabel=_.titleBarLabel=T,zot(P)&&(P="rgba(0,0,0,.2)"),_.titleBar=T=new kt.Container(u,B,null,null,!1).centerReg(_).mov(0,-d/2-B/2);_.titleBar.backing=new kt.Rectangle(u+h,B,P,null,null,[.95*g,.95*g,0,0],!0,!1).center(T);titleBarLabel.center(T).pos({x:Math.max(g/2,Math.max(10,n)),reg:!0}),_.regX=0,_.regY=-B,_.setBounds(0,-B,u,d+B),I?(T.cursor="pointer",T.on("mousedown",function(){_.drag({rect:S,currentTarget:!0})}),T.on("pressup",function(){_.noDrag()})):T.on("mousedown",function(){})}E&&(zot(M)&&(M="#555"),(E=_.close=new kt.Shape(-40,-40,80,80,null,!1)).graphics.f(M).p("AmJEVIEUkTIkXkWIB4h5IEWEYIETkTIB4B3IkTESIEQERIh4B4IkRkRIkSEVg"),T?E.centerReg(_).scaleTo(T,null,50).pos({x:u-Math.max(g/2,Math.max(10,n))-E.width/2,y:B/2,reg:!0}).expand(40):E.sca(.3).pos(Math.max(g/2,Math.max(10,n))/2,E.height/2,!0,!1,_).expand(40),E.cursor="pointer",E.expand(),E.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){_.removeFrom(),_.dispatchEvent("close")}));function ce(){kt.dragBoundary(V,new createjs.Rectangle(0,0,Q?-_.scrollXMax:0,J?-_.scrollYMax:0))}this.add=function(e,t){if(Me(e),e.getBounds())return t&&_.removeAll(),V.addChild(e),0==e.x&&(e.x=w),0==e.y&&(e.y=x),_.update(),_;zog("SwipeBox.add() - please add content with bounds set")},this.remove=function(e){return V.removeChild(e),_.update(),_};var ue,de,he,ge=!(this.removeAll=function(){return V.removeAllChildren(),_.update(),_});function pe(){Be=V.y,k&&Se.immediate(Be),f&&fe()}function fe(){_.dispatchEvent("scrolling"),N&&(N.x=-V.x,N.y=-V.y),Q&&f&&(ie.x=K.convert(V.x)),J&&f&&(le.y=Z.convert(V.y))}function me(e){kt.Ticker.remove(pe),ge=!1,Q&&i&&kt.animate(ie,{alpha:0},re.fadeTime),J&&i&&kt.animate(le,{alpha:0},re.fadeTime)}if(p&&V.on("mousedown",function(){ge||kt.Ticker.add(pe,V.stage),ge=!0,Q&&f&&i&&kt.animate(ie,{alpha:r},re.showTime),J&&f&&i&&kt.animate(le,{alpha:r},re.showTime)}),this.on("added",function(){if(Me(_),!p)return;kt.drag({obj:V,currentTarget:!0,localBounds:!0,slide:a,slideDamp:l,slideSnap:!((!z||!0!==p&&"auto"!=p&&"horizontal"!=p)&&(!v||!0!==p&&"auto"!=p&&"vertical"!=p))&&s}),V.getBounds()&&0<V.getBounds().width&&setTimeout(function(){ce()},300)},null,!0),this.cancelCurrentDrag=function(){_.content.noDrag(),kt.drag({obj:V,currentTarget:!0,localBounds:!0,slide:a,slideDamp:l,slideSnap:!((!z||!0!==p&&"auto"!=p&&"horizontal"!=p)&&(!v||!0!==p&&"auto"!=p&&"vertical"!=p))&&s}),V.getBounds()&&0<V.getBounds().width&&setTimeout(function(){ce()},300)},y&&this.added(function(e){e.on("stagemousemove",function(e){_.windowMouseX=e.stageX,_.windowMouseY=e.stageY})}),a?V.on("slidestop",me):V.on("mousedown",function(){V.stage.on("stagemouseup",me,null,!0)}),y){var ze,ve,ye;V.on("mousedown",function(e){ze=e.stageX,ve=Date.now()}),V.on("click",function(e){Date.now()-ve<600&&Math.abs(e.stageX-ze)<5&&(_.contentMouse=V.globalToLocal(e.stageX,e.stageY),_.dispatchEvent("select"))}),V.on("mouseover",function(){ye=Date.now(),kt.Ticker.add(Pe,V.stage)}),V.on("mouseout",function(){Ae||(_.dispatchEvent("hoverout"),Ae=!0);kt.Ticker.remove(Pe)});var be=0,we=0,xe=0,Ce=0,ke=300,Te=2,Ae=!1;function Pe(){if(!V.stage)return Ae||(_.dispatchEvent("hoverout"),Ae=!0),void kt.Ticker.remove(Pe);Math.abs(be-_.windowMouseX)>Te||Math.abs(we-_.windowMouseY)>Te?(Ae||(_.dispatchEvent("hoverout"),Ae=!0),ye=Date.now(),be=_.windowMouseX,we=_.windowMouseY):Date.now()-ye>ke&&((Math.abs(xe-_.windowMouseX)>Te||Math.abs(Ce-_.windowMouseY)>Te)&&(_.contentMouse=V.globalToLocal(_.windowMouseX,_.windowMouseY),_.dispatchEvent("hoverover"),xe=_.windowMouseX,Ce=_.windowMouseY,Ae=!1),ye=Date.now())}}var Be=_.scrollY;if(C){function Ie(e){if(J&&_.stage&&_.hitTestPoint(_.stage.mouseX,_.stage.mouseY)&&_.contains(_.stage.getObjectUnderPoint(_.stage.mouseX,_.stage.mouseY))){zot(e)&&(e=event);var t=e.detail?-19*e.detail:e.wheelDelta;zot(t)&&(t=-19*e.deltaY),Be+=t,Be=Math.max(-_.scrollYMax,Math.min(0,Be)),k||(_.scrollY=Be,V.stage.update())}}ue=window.addEventListener("mousewheel",Ie),de=window.addEventListener("wheel",Ie),he=window.addEventListener("DOMMouseScroll",Ie)}var Se,Ee=!1;function Me(e){k&&!Ee&&e.stage&&(Ee=!0,Se=new kt.Damp(_.scrollY,k),kt.Ticker.add(function(){ge||zot(Be)||(_.scrollY=Se.convert(Be))},e.stage))}Object.defineProperty(_,"scrollX",{get:function(){return V.x},set:function(e){V.x=e,V.zimDragImmediate&&V.zimDragImmediate(V.x,V.y),fe()}}),Object.defineProperty(_,"scrollY",{get:function(){return V.y},set:function(e){V.y=e,V.zimDragImmediate&&V.zimDragImmediate(V.x,V.y),fe()}}),!1!==O&&Oe(this,Y),this.clone=function(e){zot(e)&&(e=!0);var t=_.cloneProps(new kt.Window(u,d,o,X,R,n,g,p,f,m,re.color,r,i,z,v,a,l,s,y,c,b,w,x,T,A,P,B,I,S,E,M,O,j,D));return e&&(_.content.cloneChildren(t.content),t.update()),t},this.dispose=function(){return C&&(window.removeEventListener("mousewheel",ue),window.removeEventListener("wheel",de),window.removeEventListener("DOMMouseScroll",he)),kt.Ticker.remove(Pe),kt.Ticker.remove(pe),this.zimContainer_dispose(),!0}},kt.extend(kt.Window,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Layer=function(e,t,o,s,c,u,n,r,d,h,i,a,g,l,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B){var I;if(I=zob(kt.Layer,arguments,"width, height, titleBar, titleBarContainer, backgroundColor, rollBackgroundColor, selectedBackgroundColor, selectedRollBackgroundColor, color, rollColor, selectedColor, selectedRollColor, borderWidth, borderColor, dashed, transformObject, titleBarWidth, titleBarHeight, titleBarX, titleBarY, titleBarDraggable, close, closeColor, closeBackgroundColor, closeIndicatorColor, anchor, style, group, inherit",this))return I;z_d("58.5"),this.group=P;var S=!1===A?{}:kt.getStyle("Layer",this.group,B);zot(e)&&(e=null!=S.width?S.width:500),zot(t)&&(t=null!=S.height?S.height:500),this.zimContainer_constructor(0,0,e,t,!1),this.type="Layer";var E=this;E.distX=40,E.distY=0,zot(o)&&(o=null!=S.titleBar?S.titleBar:"LAYER");var M=o,O=o,j=!0;zot(c)&&(c=null!=S.backgroundColor?S.backgroundColor:"#eee"),zot(u)&&(u=null!=S.rollBackgroundColor?S.rollBackgroundColor:"#fff"),zot(n)&&(n=null!=S.selectedBackgroundColor?S.selectedBackgroundColor:"#666"),zot(d)&&(d=null!=S.color?S.color:"#666"),zot(h)&&(h=null!=S.rollColor?S.rollColor:"#666"),zot(i)&&(i=null!=S.selectedColor?S.selectedColor:"#ddd"),zot(g)&&(g=null!=S.borderWidth?S.borderWidth:1),zot(l)&&(l=null!=S.borderColor?S.borderColor:c),(l<0||g<0)&&(l=g=null),zot(p)&&(p=null==S.dashed||S.dashed),zot(f)&&(f=null!=S.titleBar?S.titleBar:null),zot(m)&&(m=null!=S.titleBarWidth?S.titleBarWidth:100);var D=m;if(zot(z)&&(z=null!=S.titleBarHeight?S.titleBarHeight:40),zot(v)&&(v=null!=S.titleBarX?S.titleBarX:null),zot(y)&&(y=null!=S.titleBarY?S.titleBarY:null),zot(b)&&(b=null==S.titleBarDraggable||S.titleBarDraggable),zot(w)&&(w=null==S.close||S.close),zot(x)&&(x=null!=S.closeColor?S.closeColor:n),zot(C)&&(C=null!=S.closeBackgroundColor?S.closeBackgroundColor:n),zot(k)&&(k=null!=S.closeIndicatorColor?S.closeIndicatorColor:i),zot(T)&&(T=null==S.anchor||S.anchor),b||(T=!1),E.anchor=T,w&&(m+=30),f=kt.merge({borderColor:n},f,{events:!0,visible:!1,ghostColor:l,ghostWidth:g,ghostDashed:p,ghostHidden:!0}),zot(s)&&(s=null!=S.titleBarContainer?S.titleBarContainer:null),zot(s)){if(!zimDefaultFrame)return void zog("zim Layer(): Please pass in a reference to a container with bounds set.");s=zimDefaultFrame.stage}var L;E.active=!1,E.turnOff=function(e,t){E.active=!1,w&&(E.checkBox.visible=!1),E.transformControls.remove(),E.mouseChildren=!0,E.button.backgroundColor=c,E.button.rollBackgroundColor=u,E.button.color=d,E.button.rollColor=d,E.transformControls.allowToggleOff(),E.resizeChildren&&E.resizeChildren()},E.turnOn=function(){E.active=!0,w&&(E.checkBox.visible=!0,E.checkBox.checked=!0),E.button.backgroundColor=n,E.button.rollBackgroundColor=n,E.button.color=i,E.button.rollColor=i,E.mouseChildren=!1,E.transformControls.add(),E.transformControls.allowToggleOn()},E.titleBarPos=function(e,t){return E.titleBar.pos?(E.titleBar.pos(e,t,arguments[2],arguments[3],arguments[4],arguments[5],arguments[6],arguments[7],arguments[8],arguments[9]),L.update()):(E.distX=e,E.distY=t),j=!1,E};var Y=E.visible;E.visible=!1,this.added(function(l){E.transform(f),0<=g&&E.transformControls.hideGhost(),kt.timeout(50,function(){E.visible=Y,0<=g&&kt.timeout(100,function(){E.transformControls.showGhost(),L.update()}),L=l;var r=E.titleBar=new kt.Container(m,z).reg(0,z).loc(E,null,s).mov(E.distX,E.distY);function t(e){if(j&&b){var t=s.localToLocal(r.x-E.distX,r.y-E.distY,E.parent),o=E.localToLocal(E.regX,E.regY,E.parent),n=E.localToLocal(0,0,E.parent);E.x=t.x+(o.x-n.x),E.y=t.y+(o.y-n.y),E.transformControls.resize(e),i(E)}}function i(e){e.loop(function(e){"Layer"==e.type&&(E.titleBarDraggable&&e.move(),e.transformControls.ghost&&e.transformControls.resize(),i(e))})}function o(){return 0==r.x||(r.y==r.height||(r.x==s.width-r.width||(r.y==s.height||void 0)))}if(b&&r.drag({all:!0,boundary:new kt.Boundary(0,z,s.width-m,s.height-z),localBounds:!0}),40==E.distX&&0==E.distY||r.pos(E.distX,E.distY),w&&(E.checkBox=new kt.CheckBox({borderColor:x,backgroundColor:C,indicatorColor:k,size:20,startChecked:!0}).center(r).pos(0,null,!0).change(function(){E.turnOff(!0,!0)}),E.checkBox.visible=!1),r.mouseChildren=!0,(r.layer=E).resetTitleBar=function(){E.distX=40,E.distY=0,j=!0,E.move(!0),L.update()},"string"!=typeof O&&"number"!=typeof O||(O=new kt.Label({text:O,color:d,rollColor:h,size:null!=S.size?S.size:18,group:this.group})),E.label=O,E.label.center(r),E.button=new kt.Button({shadowBlur:-1,width:D,height:z-1,label:E.label,color:d,rollColor:h,backgroundColor:c,rollBackgroundColor:u,corner:null!=S.corner?S.corner:0,inherit:S}).addTo(r),E.button.on("mousedown",function(){!0,s.loop(function(e){e&&e!=r&&e.layer&&e.layer.turnOff&&e.layer.active&&e.layer.turnOff(!0,!0)}),E.active||E.turnOn(),r.top()}),E.button.on("pressmove",function(){t()}),E.button.on("pressup",function(){t(!0);var e=E.localToLocal(0,0,s);if(E.distX=r.x-e.x,E.distY=r.y-e.y,r.top(),!1,!o()&&b){e=E.localToGlobal(0,0);E.button.hitTestPoint(e.x,e.y)&&E.resetTitleBar()}}),E.button.on("dblclick",function(){b&&E.resetTitleBar()}),E.turnOff(),E.on("transformed",function(e){"move"!=e.transformType&&"size"!=e.transformType&&"stretch"!=e.transformType&&"rotate"!=e.transformType||(b&&E.move(),i(E))}),E.move=function(e){!e&&!j&&E.anchor&&o()||(r.loc(E.localToLocal(0,0,s)).mov(E.distX,E.distY),r.x<0&&(j=!1,r.x=0),r.y<r.height&&(j=!1,r.y=r.height),r.x>s.width-r.width&&(j=!1,r.x=s.width-r.width),r.y>s.height&&(j=!1,r.y=s.height),E.anchor||(j=!0))},E.on("transformhide",function(){E.turnOff(!0,!0),s.loop(function(e){e&&e!=r&&e.layer&&e.layer.turnOff&&e.layer.active&&e.layer.turnOff()})}),E.resizeChildren=function(e){E.transformControls.resize(e),E.loop(function(e){e.transformControls&&(e.transformControls.visible&&e.transformControls.hide(),"Layer"==e.type?e.resizeChildren():e.transformControls.resize())})},E.resize=function(e){return E.move(),E.resizeChildren(e),E},E.toggled=!1,E.toggle=function(e){return zot(e)?E.toggled=!E.toggled:E.toggled=e,E.toggled?(s.loop(function(e){e&&e!=r&&e.layer&&e.layer.turnOff&&e.layer.active&&e.layer.turnOff()}),E.turnOn()):(r.top(),E.turnOff(),s.loop(function(e){e&&e!=r&&e.layer&&e.layer.turnOff&&e.layer.active&&e.layer.turnOff()})),E.stage&&E.stage.update(),E},Object.defineProperty(E,"titleBarDraggable",{get:function(){return b},set:function(e){(b=e)?r.drag({all:!0,boundary:kt.Boundary(0,40,s.width-m,s.height-z),localBounds:!0}):r.noDrag()}}),L.on("stagemouseup",function(){E.transformControls.visible&&r.top()}),!zot(v)||!zot(y)){j=!1;var e=zot(v)?r.x:v,n=zot(y)?r.y-z:y;E.titleBarStartX=v,E.titleBarStartY=y,E.titleBarPos(e,n);var a=E.parent.localToLocal(E.x,E.y,s);E.distX=r.x-a.x,E.distY=r.y-a.y}})}),!1!==A&&Oe(this,S),this.clone=function(){return E.cloneProps(new kt.Layer(e,t,M,s,c,u,n,r,d,h,i,a,g,l,p,f,D,z,v,y,b,w,x,C,k,T,A,this.group,B))},this.dispose=function(){return E.transformControls.remove(),E.transformControls.disable(),this.zimContainer_dispose(),!0}},kt.extend(kt.Layer,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Waiter=function(i,a,e,t,o,n,r,l,s,c,u){var d;if(d=zob(kt.Waiter,arguments,"container, speed, foregroundColor, backgroundColor, corner, shadowColor, shadowBlur, fadeTime, style, group, inherit",this))return d;z_d("59"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Waiter",this.group=c;var h=!1===s?{}:kt.getStyle(this.type,this.group,u);zot(a)&&(a=null!=h.speed?h.speed:600),zot(e)&&(e=null!=h.foregroundColor?h.foregroundColor:"white"),zot(t)&&(t=null!=h.backgroundColor?h.backgroundColor:"orange"),zot(o)&&(o=null!=h.corner?h.corner:16),zot(n)&&(n=null!=h.shadowColor?h.shadowColor:"rgba(0,0,0,.3)"),zot(r)&&(r=null!=h.shadowBlur?h.shadowBlur:14),zot(l)&&(l=null!=h.fadeTime?h.fadeTime:0);this.setBounds(-52,-20,104,40);var g=this,p=this.display=new kt.Shape({style:!1});this.addChild(p),p.setBounds(0,0,104,40),p.regX=52,p.regY=20;var f=p.graphics;f.f(t);var m=o;Array.isArray(m)||(m=[o,o,o,o]),f.rc(0,0,104,40,m[0],m[1],m[2],m[3]),-1!=n&&0<r&&(p.shadow=new createjs.Shadow(n,3,3,r)),p.on("click",function(e){e.stopImmediatePropagation()});var z,v,y=new kt.Container({style:!1});this.addChild(y);for(var b=0;b<3;b++)(z=new createjs.Shape).graphics.f(e).dc(0,0,12),z.x=32*(b-1),y.addChild(z),z.cache(-12,-12,24,24),z.alpha=0;this.hide=function(){function e(){g.parent&&g.parent.removeChild(g);var e=g.stage;if(e&&e.update(),g.zimAccessibility){var t=g.zimAccessibility;t.resize(g),v?v.focus():g.zimTabTag.nextSibling.focus(),setTimeout(function(){t.talk("Waiter has finished.")},50)}}return 0<l?g.animate({obj:{alpha:0},time:l,call:e}):e(),g.toggled=!1,g};var w=[];this.show=function(){var e,t="zim display - Waiter(): Please pass in a reference to a container with bounds set as first parameter to Waiter";if(zot(i)){if(!zimDefaultFrame)return void zog(t);i=zimDefaultFrame.stage}else{if(!i.getBounds)return void zog(t);if(zot(i.stage))return void zog("zim display - Waiter(): The container must have a stage property")}for(var o=0,n=0;n<y.numChildren;n++)y&&w.push(setTimeout(function(){e=y.getChildAt(o),createjs.Tween.get(e,{loop:!0}).to({alpha:1},a/3/2).wait(a/3).to({alpha:0},a/3).wait(a-a/3-a/3/2),o++},n*a/3));if(g.ticker=createjs.Ticker.on("tick",function(){i.stage.update()}),g.x=i.getBounds().width/2,g.y=i.getBounds().height/2,i.addChild(g),0<l&&(g.alpha=0,g.animate({alpha:1},l)),g.zimAccessibility){var r=g.zimAccessibility;setTimeout(function(){r.activatedObject&&(v=r.activatedObject.zimTabTag)},50),r.resize(g),r.talk(g.zimTabTag.getAttribute("aria-label"))}return g.toggled=!0,g},!(g.toggle=function(e){return!0===e?g.show():!1===e?g.hide():g.parent?g.hide():g.show(),g})!==s&&Oe(this,h),this.clone=function(){return g.cloneProps(new kt.Waiter(i,a,e,t,o,n,r,l,s,this.group,u))},this.dispose=function(){g.ticker&&createjs.Ticker.off("tick",g.ticker),createjs.Tween.removeTweens(g);for(var e=0;e<y.numChildren;e++){var t=y.getChildAt(e);clearInterval(w[e]),createjs.Tween.removeTweens(t)}return this.zimContainer_dispose(),!0}},kt.extend(kt.Waiter,kt.Container,["clone","dispose"],"zimContainer",!1),kt.ProgressBar=function(t,o,n,r,i,a,l,e,s,c,u,d,h,g,p,f,m,z,v,y,b){var w;if(w=zob(kt.ProgressBar,arguments,"barType, foregroundColor, backgroundColor, borderColor, borderWidth, padding, label, color, labelPosition, percentage, corner, shadowColor, shadowBlur, backing, delay, fastClose, container, autoHide, style, group, inherit",this))return w;z_d("59.5"),this.zimContainer_constructor(null,null,null,null,!1),this.type="ProgressBar",this.group=y;var x=!1===v?{}:kt.getStyle(this.type,this.group,b);zot(o)&&(o=null!=x.foregroundColor?x.foregroundColor:"#acd241"),zot(n)&&(n=null!=x.backgroundColor?x.backgroundColor:"#444"),zot(r)&&(r=null!=x.borderColor?x.borderColor:n),zot(i)&&(i=null!=x.borderWidth?x.borderWidth:null),zot(s)&&(s=null!=x.labelPosition?x.labelPosition:"bottom"),zot(t)&&(t=null!=x.barType?x.barType:"circle"),zot(a)&&(a=null!=x.padding?x.padding:"circle"==t?2:-.5),zot(u)&&(u=null!=x.corner?x.corner:15),zot(d)&&(d=null!=x.shadowColor?x.shadowColor:"rgba(0,0,0,.3)"),zot(h)&&(h=null!=x.shadowBlur?x.shadowBlur:14),zot(g)&&(g=null!=x.backing?x.backing:null),zot(f)&&(f=null==x.fastClose||x.fastClose),r<0||i<0?r=i=null:null!=r&&null==i&&(i="circle"==t?10:2),zot(p)&&(p=null!=x.delay?x.delay:100),zot(z)&&(z=null==x.autoHide||x.autoHide),zot(l)&&(l=null!=x.label?x.label:null),zot(e)&&(e=null!=x.color?x.color:o),"string"!=typeof l&&"number"!=typeof l||(l=new kt.Label({text:l,color:e,backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group}));l&&l.text,!zot(c)&&zot(l)&&(l=new kt.Label("")),this.label=l;var C,k=30,T=this,A=0;if(T.visible=!1,setTimeout(function(){T.visible=!0,T.stage&&T.stage.update()},p),"circle"==t)var P=20,B=(g=this.backing=new kt.Circle(P,"rgba(0,0,0,0)",n,i,null,null,!1).addTo(this),this.bar=new kt.Shape({style:!1}).addTo(T).pos({x:g.x,y:g.y,reg:!0}).rot(-90));else{P=200;if(-1!=d&&0<h)new kt.Rectangle(P-2,k-2,n,null,null,u,null,!1).addTo(this).shadow=new createjs.Shadow(d,3,3,h);g=M(g);var I=u;Array.isArray(I)||(I=[u,u,u,u]);var S=1.2*(a+i/2),E=(B=this.bar=new kt.Rectangle(P-1.8*(a+i/2),k-1.8*(a+i/2),o,null,null,[I[0]-S,I[1]-S,I[2]-S,I[3]-S],null,!1).center(this),this.mask=new kt.Rectangle(P-1.8*(a+i/2),k-1.8*(a+i/2),null,null,null,null,null,!1).center(this).alp(0).sca(0,1));B.setMask(E)}function M(e){if(T.backing){var t=T.getChildIndex(T.backing);T.removeChild(T.backing)}else t=T.numChildren;if(T.border&&T.removeChild(T.border),zot(e)||"Pattern"!=e.type)e=T.backing=zot(e)?new kt.Rectangle(P,k,n,r,i,u,null,!1).addTo(T,t):g.addTo(T,t);else{var o=e;((e=T.backing=new kt.Rectangle(P,k,n,null,null,u,null,!1).addTo(T,t)).pattern=o).center(e);e.getBounds();if(o.setMask(e.shape),i)T.border=new kt.Rectangle(P,k,"rgba(0,0,0,0)",r,i,u,null,!1).addTo(T,t+1)}return e}function O(e){"circle"==t?B.graphics.c().mt(0,0).s(o).ss(i-2*a+.5).a(0,0,P,0,360*e/100*Math.PI/180):(E.sca(e/100,1),B.setMask(E)),zot(c)||(l.text=l.startText+" "+Math.min(Math.round(e),100)+"%"),z&&f&&100<=Math.round(e)&&(T.timeOut=setTimeout(function(){T.hide()},200)),T.stage&&T.stage.update()}T.setBacking=function(e){M(e),T.stage&&T.stage.update()},g.on("click",function(e){e.stopImmediatePropagation()}),zot(l)||(l.scaleX=l.scaleY=.8,l.startText=l.text,zot(c)||(l.text=l.startText+" 0%"),l.center(T),"above"==s?l.y-=60:l.y+=60,l.alpha=.8),this.hide=function(){var e=T.stage;if(T.parent&&T.parent.removeChild(T),"Pattern"==T.backing.type&&T.backing.pauseInterval&&T.backing.pauseInterval(),e&&e.update(),T.zimAccessibility){var t=T.zimAccessibility;t.resize(T),C?C.focus():T.zimTabTag.nextSibling.focus(),setTimeout(function(){t.talk("Progress Bar has finished.")},50)}return T.toggled=!1,T},this.show=function(){var e="zim display - ProgressBar(): Please pass in a reference to a container with bounds set as first parameter of the ProgressBar";if(zot(m)){if(!zimDefaultFrame)return void zog(e);m=zimDefaultFrame.stage}else{if(!m.getBounds)return void zog(e);if(zot(m.stage))return void zog("zim display - Waiter(): The container must have a stage property")}if(T.timeOut&&clearTimeout(T.timeOut),O(0),T.zimActiveLoader&&T.zimActiveLoader.on("progress",function(e){O(A=100*e.progress)}),T.center(m),"Pattern"==T.backing.type&&T.backing.pauseInterval&&T.backing.pauseInterval(!1),T.zimAccessibility){var t=T.zimAccessibility;setTimeout(function(){t.activatedObject&&(C=t.activatedObject.zimTabTag)},50),t.resize(T),t.talk(T.zimTabTag.getAttribute("aria-label"))}return T.toggled=!0,T},T.toggle=function(e){return!0===e?T.show():!1===e?T.hide():T.parent?T.hide():T.show(),T},Object.defineProperty(T,"percent",{get:function(){return A},set:function(e){O(A=e)}}),!1!==v&&Oe(this,x),this.clone=function(){return T.cloneProps(new kt.ProgressBar(t,o,n,r,i,a,l,e,s,c,u,d,h,g,p,f,m,z,v,this.group,b))},this.dispose=function(){return"Pattern"==T.backing.type&&T.backing.clearInterval&&T.backing.clearInterval(),this.zimContainer_dispose(),!0}},kt.extend(kt.ProgressBar,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Indicator=function(e,t,n,r,i,o,a,l,s,c,u,d,h,g,p,f,m,z,v){var y;if(y=zob(kt.Indicator,arguments,"width, height, num, foregroundColor, backgroundColor, borderColor, borderWidth, backdropColor, corner, indicatorType, fill, scale, lightScale, press, shadowColor, shadowBlur, style, group, inherit",this))return y;z_d("60"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Indicator",this.group=z;var b=!1===m?{}:kt.getStyle(this.type,this.group,v);zot(e)&&(e=null!=b.width?b.width:300),zot(t)&&(t=null!=b.height?b.height:50),zot(n)&&(n=null!=b.num?b.num:6),zot(r)&&(r=null!=b.foregroundColor?b.foregroundColor:"#f58e25"),zot(i)&&(i=null!=b.backgroundColor?b.backgroundColor:"#666"),i<0&&(i=null!=b.backgroundColor?b.backgroundColor:"rgba(0,0,0,.01)"),zot(o)&&(o=null!=b.borderColor?b.borderColor:null),zot(a)&&(a=null!=b.borderWidth?b.borderWidth:null),o<0||a<0?o=a=null:null!=o&&null==a&&(a=1),zot(l)&&(l=null!=b.backdropColor?b.backdropColor:-1),zot(s)&&(s=null!=b.corner?b.corner:0),zot(c)&&(c=null!=b.indicatorType?b.indicatorType:"dot"),zot(u)&&(u=null!=b.fill&&b.fill),zot(d)&&(d=null!=b.scale?b.scale:1),zot(h)&&(h=null!=b.lightScale?b.lightScale:1),zot(g)&&(g=null!=b.press&&b.press),zot(p)&&(p=null!=b.shadowColor?b.shadowColor:"rgba(0,0,0,.3)"),zot(f)&&(f=null!=b.shadowBlur?b.shadowBlur:5);var w,x=(zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",C=this;this.lights=[];new kt.Container({style:!1});if(-1!=l){var k=C.backdrop=new kt.Rectangle(e,t,l,o,a,s,null,!1);this.addChild(k)}var T,A=this.lightsContainer=new kt.Container({style:!1});this.addChild(A);var P=.5*t,B=e/(n+1),I=new createjs.Shape;"square"==c||"box"==c?I.graphics.f("black").dr(-B/2/h+P/2,-t/2+P/2,B/h,t):I.graphics.f("black").dr(-B/2/h,-t/2,B/h,t);for(var S=0;S<n;S++)"square"==c||"box"==c?((T=new kt.Rectangle(P,P,i,o,a,null,null,!1)).regX=T.width/2,T.regY=T.height/2):T=new kt.Circle(P/2,i,o,a,null,null,!1),this.lights.push(T),T.znum=S,T.scaleX=T.scaleY=h,T.hitArea=I,T.x=B+B*S,T.y=t/2,A.addChild(T);if(A.setBounds(0,0,e,t),A.regX=A.x=e/2,A.regY=A.y=t/2,this.addChild(A),-1!=p&&0<f&&(A.shadow=new createjs.Shadow(p,2,2,f)),g){A.cursor="pointer";A.on(x,function(e){w!=e.target.znum&&(E(w=e.target.znum),C.dispatchEvent("change"))})}function E(e){var t;n<=e&&(e=-1);for(var o=0;o<n;o++)t=u&&o<e?r:i,o==e&&(t=r),A.getChildAt(o).color=t;C.zimAccessibility&&C.zimAccessibility.changeTitle(C),kt.OPTIMIZE||!zns&&OPTIMIZE||!C.stage||C.stage.update()}A.scaleX=A.scaleY=d,Object.defineProperty(this,"selectedIndex",{get:function(){return w},set:function(e){w=Math.floor(e),E(w=kt.constrain(w,-1,n-1))}}),Object.defineProperty(this,"num",{get:function(){return n},set:function(e){zon&&zog("num is read only")}}),this._enabled=!0,Object.defineProperty(C,"enabled",{get:function(){return C._enabled},set:function(e){Se(C,e)}}),!1!==m&&Oe(this,b),this.clone=function(){return C.cloneProps(new kt.Indicator(e,t,n,r,i,o,a,l,s,c,u,d,h,g,p,f,m,this.group,v))}},kt.extend(kt.Indicator,kt.Container,"clone","zimContainer",!1),kt.List=function(n,r,e,t,i,o,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H,V,N,G,q,U,K,Z,Q,J,$,ee,te,oe,ne,re,ie){var ae;if(ae=zob(kt.List,arguments,"width, height, list, viewNum, vertical, currentSelected, align, valign, labelAlign, labelValign, labelIndent, labelIndentHorizontal, labelIndentVertical, indent, spacing, backgroundColor, rollBackgroundColor, selectedBackgroundColor, selectedRollBackgroundColor, backdropColor, color, selectedColor, rollColor, selectedRollColor, borderColor, borderWidth, padding, corner, swipe, scrollBarActive, scrollBarDrag, scrollBarColor, scrollBarAlpha, scrollBarFade, scrollBarH, scrollBarV, scrollBarOverlay, slide, slideDamp, slideSnap, shadowColor, shadowBlur, paddingHorizontal, paddingVertical, scrollWheel, damp, titleBar, titleBarColor, titleBarBackgroundColor, titleBarHeight, draggable, boundary, close, closeColor, excludeCustomTap, organizer, clone, style, group, inherit",this))return ae;z_d("60.5"),this.group=re;var le=!1===ne?{}:kt.getStyle("List",this.group,ie);zot(n)&&(n=null!=le.width?le.width:300),zot(r)&&(r=null!=le.height?le.height:zot(te)?200:200+te.height),zot(e)&&(e=e=null!=le.list?le.list:["Option 1","Option 2","Option 3","Option 4","Option 5","Option 6","Option 7","Option 8","Option 9","Option 10"]),0==e.length&&(e=["%-&"]),this.originalList=e,zot(t)&&(t=null!=le.viewNum?le.viewNum:5),zot(i)&&(i=null==le.vertical||le.vertical),zot(o)&&(o=null==le.currentSelected||le.currentSelected);var se=!zot(a)||!zot(s);zot(a)&&(a=null!=le.align?le.align:"center"),zot(l)&&(l=null!=le.valign?le.valign:"center"),zot(s)&&(s=null!=le.labelAlign?le.labelAlign:a),zot(c)&&(c=null!=le.labelValign?le.labelValign:l),zot(g)&&(g=null!=le.indent?le.indent:10),zot(u)&&(u=null!=le.labelIndent?le.labelIndent:g),zot(d)&&(d=null!=le.labelIndentHorizontal?le.labelIndentHorizontal:u),zot(h)&&(h=null!=le.labelIndentVertical?le.labelIndentVertical:u),zot(p)&&(p=null!=le.spacing?le.spacing:2),zot(y)&&(y=null!=le.backdropColor?le.backdropColor:"#333"),zot(f)&&(f=null!=le.backgroundColor?le.backgroundColor:"#777"),zot(m)&&(m=null!=le.rollBackgroundColor?le.rollBackgroundColor:"#555"),zot(z)&&(z=null!=le.selectedBackgroundColor?le.selectedBackgroundColor:"#444"),zot(v)&&(v=null!=le.selectedRollBackgroundColor?le.selectedRollBackgroundColor:"#555"),zot(b)&&(b=null!=le.color?le.color:"white"),zot(x)&&(x=null!=le.rollColor?le.rollColor:b),zot(w)&&(w=null!=le.selectedColor?le.selectedColor:b),zot(C)&&(C=null!=le.selectedRollColor?le.selectedRollColor:x),zot(y)&&(y=null!=le.backdropColor?le.backdropColor:y);var ce=k,ue=T;zot(k)&&(k=null!=le.borderColor?le.borderColor:"#999"),zot(T)&&(T=null!=le.borderWidth?le.borderWidth:1),zot(A)&&(A=null!=le.padding?le.padding:p),zot(P)&&(P=null!=le.corner?le.corner:0),zot(B)&&(B=null==le.swipe||le.swipe),zot(I)&&(I=null==le.scrollBarActive||le.scrollBarActive),zot(S)&&(S=null==le.scrollBarDrag||le.scrollBarDrag),zot(E)&&(E=null!=le.scrollBarColor?le.scrollBarColor:k),zot(M)&&(M=null!=le.scrollBarAlpha?le.scrollBarAlpha:.3),zot(O)&&(O=null==le.scrollBarFade||le.scrollBarFade),zot(j)&&(j=null!=le.scrollBarH?le.scrollBarH:!i),zot(D)&&(D=null!=le.scrollBarV?le.scrollBarV:i),S&&(O=null!=le.scrollBarFade&&le.scrollBarFade),zot(L)&&(L=null==le.scrollBarOverlay||le.scrollBarOverlay),zot(Y)&&(Y=null==le.slide||le.slide),zot(X)&&(X=null!=le.slideDamp?le.slideDamp:.6),zot(R)&&(R=null!=le.slideSnap?le.slideSnap:i?"vertical":"horizontal"),zot(_)&&(_=null!=le.shadowColor?le.shadowColor:"rgba(0,0,0,.3)"),zot(W)&&(W=null!=le.shadowBlur?le.shadowBlur:20),zot(H)&&(H=null!=le.paddingVertical?le.paddingVertical:A),zot(F)&&(F=null!=le.paddingHorizontal?le.paddingHorizontal:A),zot(V)&&(V=null==le.scrollWheel||le.scrollWheel),zot(G)&&(G=null!=le.titleBar?le.titleBar:null),zot(q)&&(q=null!=le.titleBarColor?le.titleBarColor:null),zot(U)&&(U=null!=le.titleBarBackgroundColor?le.titleBarBackgroundColor:null),zot(K)&&(K=null!=le.titleBarHeight?le.titleBarHeight:35),zot(Z)&&(Z=null!=le.draggable?le.draggable:null),zot(Q)&&(Q=null!=le.boundary?le.boundary:null),zot(J)&&(J=null!=le.close?le.close:null),zot($)&&($=null!=le.closeColor?le.closeColor:null),zot(ee)&&(ee=null!=le.excludeCustomTap&&le.excludeCustomTap),zot(oe)&&(oe=null!=le.clone&&le.clone),!1===G&&(G=null),this.vertical=i;var de,he,ge,pe=this,fe=r;if(e.constructor=={}.constructor){var me=zot(e.shade)?zot(le.shade)?.2:le.shade:e.shade,ze=zot(e.dim)?zot(le.dim)?.1:le.dim:e.dim,ve=zot(e.shift)?zot(le.shift)?15:le.shift:e.shift,ye=zot(e.bloom)?!zot(le.bloom)&&le.bloom:e.bloom,be=zot(e.whither)?!zot(le.whither)&&le.whither:e.whither;!0===ye&&(ye=10),!0===be&&(be=10),!0===ve&&(ve=15),!0===me&&(me=.2),!0===ze&&(ze=.1);var we=zot(e.subStyles)?zot(le.subStyles)?{}:le.subStyles:e.subStyles;zot(e.menu)||(e=e.menu);var xe=new Hierarchy(e);e=xe.getLinearList(),se||(a=s="left")}if(this.align=a,this.valign=l,this.indent=g,zot(te)||(r-=te.height,te.list=pe,te.setButtons(),K+=te.height),this.zimWindow_constructor(n,r,y,k,T,A,P,B,I,S,E,M,O,j,D,Y,X,R,!0,_,W,F,H,V,N,G,q,U,K,Z,Q,J,$,ne,re,le),this.type="List",zot(G)||(this.titleBarLabel.pos(null,K-30,null,!0),zot(K)&&(K=30),r-=K),zot(te)||te.addTo(pe).loc(0,-te.height),pe.itemWidth=i?n-2*F-(I?L?0:6:0):(n-2*F)/t,pe.itemHeight=i?(r-2*H)/t:r-2*H-(I?L?0:6:0),he=kt.copy(e,oe),de=pe.tabs=new kt.Tabs({width:i?pe.itemWidth:pe.itemWidth*e.length,height:i?pe.itemHeight*e.length:pe.itemHeight,tabs:he,spacing:p,vertical:i,backgroundColor:f,rollBackgroundColor:m,selectedBackgroundColor:z,selectedRollBackgroundColor:v,color:b,rollColor:x,selectedColor:w,selectedRollColor:C,backdropColor:y,currentEnabled:!0,currentSelected:o,align:a,valign:l,labelAlign:s,labelValign:c,labelIndent:u,labelIndentHorizontal:d,labelIndentVertical:h,indent:g,useTap:!0,excludeCustomTap:ee,style:ne,group:re,inherit:le}).mov(i?0:F,i?H:0),pe.add(de),xe){var Ce=xe.getLinearIDs();function ke(e,t,o){e.listZID=t,e.label&&(me&&new Rectangle(ve*(o.level+1),e.height).alp(me).pos(0,0,"right"==pe.align,!1,e),ze&&new Rectangle(e.width,e.height).alp((o.level+1)*ze).addTo(e).bot().ord(1),ve&&"center"!=pe.align&&(e.label.x+=("right"==pe.align?-1:1)*ve*(o.level+1)));var n=xe.getData(t);n.obj=e,n.list&&!isEmpty(n.list)&&(e.accordion=new Label({text:"+",align:"center",color:convertColor(b,"rgba",.6)}).center(e).alp(.7).pos(15,null,"right"!=pe.align))}loop(Ce,function(e,t){pe.tabs.buttons[t].listZID=e}),loop(pe.tabs.buttons,function(e){var t=xe.getData(e.listZID);isEmpty(t.list)||(e.accordion=new Label({text:"+",align:"center",color:convertColor(b,"rgba",.6)}).center(e).alp(.7).pos(15,null,"right"!=pe.align))}),pe.tap(function(){if(pe.selected.accordion){var o=xe.getData(pe.selected.listZID);if(o.open){pe.selected.accordion&&(pe.selected.accordion.text="+"),o.open=!1;var n=xe.getNextSibling(pe.selected.listZID);if(zot(n))var t=pe.items.length-1;else t=loop(pe.items,function(e,t){if(e.listZID==n)return t-1});if(be){var r=0;pe.enabled=!1,interval(be,function(e){pe.removeAt(1,pe.selectedIndex+t-pe.selectedIndex-r),r++,e.total==e.count+1&&(pe.enabled=!0)},t-pe.selectedIndex,!0)}else pe.removeAt(t-pe.selectedIndex,pe.selectedIndex+1)}else{o.open=!0,pe.selected.accordion&&(pe.selected.accordion.text="-");var i=xe.getLinearList(o.list),a=xe.getLinearIDs(o.list);if(o.opened){if(Array.isArray(i))if(ye){r=0;pe.enabled=!1,interval(ye,function(e){pe.addAt(i[r],pe.selectedIndex+1+r),e.total==e.count+1&&(pe.enabled=!0),r++},i.length,!0)}else pe.addAt(i,pe.selectedIndex+1)}else{o.opened=!0;var l=we[o.level];if(zot(l)&&(l={}),Array.isArray(i))if(ye){var r=0;pe.enabled=!1,interval(ye,function(e){pe.addAt(i[r],pe.selectedIndex+1+r,{backgroundColor:l.backgroundColor,color:l.color,rollBackgroundColor:l.rollBackgroundColor,rollColor:l.rollColor,selectedBackgroundColor:l.selectedBackgroundColor,selectedColor:l.selectedColor,selectedRollBackgroundColor:l.selectedRollBackgroundColor,selectedRollColor:l.selectedRollColor});var t=a[r];ke(pe.items[pe.selectedIndex+1+r],t,o),e.total==e.count+1&&(pe.enabled=!0),r++},i.length,!0)}else pe.addAt(i,pe.selectedIndex+1,{backgroundColor:l.backgroundColor,color:l.color,rollBackgroundColor:l.rollBackgroundColor,rollColor:l.rollColor,selectedBackgroundColor:l.selectedBackgroundColor,selectedColor:l.selectedColor,selectedRollBackgroundColor:l.selectedRollBackgroundColor,selectedRollColor:l.selectedRollColor}),loop(a,function(e,t){ke(pe.items[pe.selectedIndex+1+t],e,o)})}}}})}function Te(e){if(i){var t=-(pe.itemHeight+p)*e+r/2-pe.itemHeight/2;return(pe.itemHeight+p)*pe.length<r&&(t=0),0<t&&(t=0),(pe.itemHeight+p)*pe.length>r&&t<-pe.tabs.height+r-2*H&&(t=-pe.tabs.height+r-2*H),t}var o=-(pe.itemWidth+p)*e+n/2-pe.itemWidth/2;return(pe.itemWidth+p)*pe.length<n&&(o=0),0<o&&(o=0),(pe.itemWidth+p)*pe.length>n&&o<-pe.tabs.width+n-2*F&&(o=-pe.tabs.width+n-2*F),o}de.tap(function(e){e.target.selectedIndex!=pe.selectedIndex&&(pe.selectedIndex=de.selectedIndex,pe.dispatchEvent("change"),e.preventDefault())}),this.getItemIndex=function(e){return pe.items.indexOf(e)},this.animateTo=function(e,t){zot(e)&&(e=0),zot(t)&&(t=50);var o=Te(pe.selectedIndex=e);if(i){var n=Math.abs(pe.scrollY-o)/pe.itemHeight;pe.animate({scrollY:o},n*t),pe.scrollY=o}else{n=Math.abs(pe.scrollX-o)/pe.itemWidth;pe.animate({scrollX:o},n*t),pe.scrollX=o}return pe},this.addAt=function(e,t,o,n){return pe.tabs.addAt(copy(e,n),t,o),pe.content.x=0,pe.content.y=0,pe.update(),pe},this.removeAt=function(e,t){pe.tabs.removeAt(e,t);var o=de.getBounds();return de.setBounds(0,0,i?o.width:o.width+2*p+4,i?o.height+2*p+4:o.height),pe.content.x=0,pe.content.y=0,pe.update(),pe},"%-&"==e[0]&&1==e.length&&pe.removeAt(1,0),this.clear=function(){return pe.tabs.removeAt(pe.length,0),pe.content.x=0,pe.content.y=0,pe.update(),pe},Object.defineProperty(pe,"items",{get:function(){return pe.tabs.buttons},set:function(e){zon&&zog("List() - items is read only - use addAt() and removeAt() to change")}}),Object.defineProperty(pe,"list",{get:function(){return pe.tabs.buttons},set:function(e){zon&&zog("List() - list is read only - use addAt() and removeAt() to change")}}),Object.defineProperty(pe,"length",{get:function(){return pe.tabs.buttons.length},set:function(e){zon&&zog("List() - length is read only")}}),Object.defineProperty(pe,"selectedIndex",{get:function(){return ge},set:function(e){de.selectedIndex=e,pe.label=de.label,pe.selected=de.selected,ge=e,kt.OPTIMIZE||!zns&&OPTIMIZE||!pe.stage||pe.stage.update()}}),o&&(pe.selectedIndex=0),Object.defineProperty(pe,"selectedIndexPlusPosition",{get:function(){return ge},set:function(e){pe.selectedIndex=e,ge=e,i?pe.scrollY=Te(e):pe.scrollX=Te(e),kt.OPTIMIZE||!zns&&OPTIMIZE||!pe.stage||pe.stage.update()}}),Object.defineProperty(pe,"text",{get:function(){if(pe.label)return pe.label.text},set:function(e){pe.label&&(pe.label.text=e)}}),Object.defineProperty(pe,"itemDown",{get:function(){return pe.tabs.buttonDown},set:function(e){}}),Object.defineProperty(pe,"itemsText",{get:function(){for(var e=[],t=0;t<pe.tabs.buttons.length;t++){var o=pe.tabs.buttons[t].label;o&&!zot(o.text)?e.push(o.text):e.push(null)}return e},set:function(e){zon&&zog("List() - itemsText is read only")}}),o&&(pe.selectedIndex=0),this._enabled=!0,Object.defineProperty(pe,"enabled",{get:function(){return pe._enabled},set:function(e){Se(pe,e)}}),this.last=function(){return this.selectedIndexPlusPosition=this.length-1,this},!(this.first=function(){return this.selectedIndexPlusPosition=0,this})!==ne&&Oe(this,le),this.clone=function(){return pe.cloneProps(new kt.List(n,fe,kt.copy(pe.originalList,!0),t,i,o,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,ce,ue,A,kt.copy(P),B,I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H,V,N,G,q,U,K,Z,Q,J,$,ee,te,oe,ne,this.group,ie))}},kt.extend(kt.List,kt.Window,"clone","zimWindow",!1),kt.Stepper=function(n,e,o,t,r,l,i,s,a,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j){var D;if(D=zob(kt.Stepper,arguments,"list, width, backgroundColor, borderColor, borderWidth, label, color, vertical, arrows, corner, shadowColor, shadowBlur, continuous, display, press, hold, holdDelay, holdSpeed, draggable, dragSensitivity, dragRange, stepperType, min, max, step, step2, arrows2, arrows2Scale, keyEnabled, keyArrows, rightForward, downForward, style, group, inherit",this))return D;z_d("61"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Stepper",this.group=O;var L=!1===M?{}:kt.getStyle(this.type,this.group,j);zot(n)&&(n=null!=L.list?L.list:[0,1,2,3,4,5,6,7,8,9]),zot(e)&&(e=null!=L.width?L.width:200),zot(o)&&(o=null!=L.backgroundColor?L.backgroundColor:"white"),zot(t)&&(t=null!=L.borderColor?L.borderColor:null),zot(r)&&(r=null!=L.borderWidth?L.borderWidth:null),t<0||r<0?t=r=null:null!=t&&null==r&&(r=1),zot(i)&&(i=null!=L.color?L.color:"#555"),zot(l)&&(l=null!=L.label?L.label:""),"string"!=typeof l&&"number"!=typeof l||(l=new kt.Label({text:l,size:null!=L.size?2*L.size:64,color:i,align:null!=L.align?L.align:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",padding:"ignore",backgroundColor:"ignore",group:this.group})),zot(s)&&(s=null!=L.vertical&&L.vertical),zot(a)&&(a=null==L.arrows||L.arrows),zot(c)&&(c=null!=L.corner?L.corner:16),zot(u)&&(u=null!=L.shadowColor?L.shadowColor:"rgba(0,0,0,.3)"),zot(d)&&(d=null!=L.shadowBlur?L.shadowBlur:14),zot(h)&&(h=null!=L.continuous&&L.continuous),zot(g)&&(g=null==L.display||L.display),zot(p)&&(p=null==L.press||L.press),zot(f)&&(f=null==L.hold||L.hold),zot(m)&&(m=null!=L.holdDelay?L.holdDelay:400),zot(z)&&(z=null!=L.holdSpeed?L.holdSpeed:200),zot(v)&&(v=null==L.draggable||L.draggable),(zot(y)||y<=0)&&(y=null!=L.dragSensitivity?L.dragSensitivity:.1),zot(b)&&(b=null!=L.dragRange?L.dragRange:200),zot(w)&&(w=null!=L.stepperType?L.stepperType:"list"),zot(x)&&(x=null!=L.min?L.min:0),zot(C)&&(C=null!=L.max?L.max:100),zot(k)&&(k=null!=L.step?L.step:1),zot(T)&&(T=null!=L.step2?L.step2:k),zot(A)&&T!=k&&"number"==w&&(A=null==L.arrows2||L.arrows2),zot(P)&&(P=null!=L.arrows2Scale?L.arrows2Scale:.5),zot(B)&&(B=null==L.keyEnabled||L.keyEnabled),zot(I)&&(I=null==L.keyArrows||L.keyArrows),zot(S)&&(S=null==L.rightForward||L.rightForward),zot(E)&&(E=null!=L.downForward?L.downForward:"number"!=w);var Y,X,R,_,W=this,F=100,H=k,V=1;if("number"==w){if(x=Number(x),C=Number(C),NaN==x&&(x=0),NaN==C&&(C=100),C<x){V=-1;var N=C;C=x,x=N,X=C}else X=x;this.min=x,this.max=C,x<0&&0<C&&(X=0),k=Math.abs(k),R=Math.max(U(k),U(T))}else if("letter"==w){n="ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(""),"string"!=typeof x&&(x="A"),"string"!=typeof C&&(C="Z"),x=x.substr(0,1).toUpperCase(),C=C.substr(0,1).toUpperCase();var G=n.indexOf(x);G<0&&(x="A",G=0);var q=n.indexOf(C);q<0&&(C="Z",q=n.length),q<G&&(n.reverse(),G=n.length-1-G,q=n.length-1-q),n=n.splice(G,q-G+1)}else w="list";function U(e){var t=String(e).split(".")[1];return t=t?t.length:0}var K=0,Z=0;v&&this.on("mousedown",function(e){W.zimAccessibility&&W.zimAccessibility.aria||(this.stage.mouseMoveOutside=!0,K=e.rawX,Z=e.rawY,_=this.stage.on("stagemousemove",function(e){K=e.rawX,Z=e.rawY}))},null,!0),(this.label=l).mouseChildren=!1;l.mouseEnabled=!1;var Q,J,$,ee,te,oe,ne,re,ie,ae,le,se,ce,ue=!1;if(a||A){var de=new createjs.Shape;de.graphics.ss(t).s(r).f("rgba(255,255,255,.11)").r(0,0,150,150),de.regX=75,de.regY=87.5}if(a&&(ee=this.containerPrev=new kt.Container({style:!1}),this.addChild(ee),ee.hitArea=de,te=this.arrowPrev=new kt.Triangle(F,80,80,o,null,null,null,null,null,!1),-1!=u&&0<d&&(ee.shadow=new createjs.Shadow(u,3,3,d)),ee.addChild(te),ee.cursor="pointer",ee.on("mousedown",function(e){if(!W.zimAccessibility||!W.zimAccessibility.aria){H=k;var t=s?E?1:-1:S?-1:1;ze(t),fe(t,null,null,e.stageX,e.stageY)}}),f&&ee.on("pressup",me),ee.y=s?(ee.rotation=180,ee.x=e/2,g?ee.height+25+F+ee.height/2+25:2*ee.height):(ee.rotation=-90,ee.x=ee.height/2,ee.width/2)),g){var he=this.textBox=new kt.Shape({style:!1});he.cursor="pointer",this.addChild(he),he.setBounds(0,0,e,F),null!=t&&he.graphics.s(t).ss(r);var ge,pe=c;Array.isArray(pe)||(pe=[c,c,c,c]),he.graphics.f(o).rc(0,0,e,F,pe[0],pe[1],pe[2],pe[3]),-1!=u&&0<d&&(he.shadow=new createjs.Shadow(u,3,3,d)),a&&(s?a&&(he.y=te.height+25):a&&(he.x=te.height+25)),this.addChild(l),0<n.length&&(Y=0,l.text=n[Y]),l.x=50+he.x+he.getBounds().width/2,l.y=he.y+(he.getBounds().height-l.getBounds().height)/2,he.on("mousedown",function(e){W.zimAccessibility&&W.zimAccessibility.aria||(ge=W.currentValue,p&&ze(1),fe(1,!0,null,e.stageX,e.stageY),"number"==w&&(clearTimeout($),ue=!0,$=setTimeout(function(){ue=!1},200)))}),he.on("pressup",function(){W.zimAccessibility&&W.zimAccessibility.aria||ue&&(ye(X=Math.round(X),X),W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue)})}else 0<n.length&&(Y=0);function fe(r,i,a,e,t){if(f){se=e,holdY=t,0==se&&(se=1),0==holdY&&(holdY=1),v||(y=1),ce=new kt.Proportion(0,b,z,z*y);var l=z;Q=setTimeout(function(){!0,function n(){J=setTimeout(function(){var e=r;if(v){var t=Math.abs(K-se),o=Math.abs(Z-holdY);s?(i||a||(t=0),a&&(o=0)):(i||a||(o=0),a&&(t=0)),(10<=t||10<=o)&&(l=o<t?(H=s?T:k,e=0<K-se?1:-1,ce.convert(Math.abs(se-K))):(H=s?k:T,e=0<Z-holdY?1:-1,"number"!=w&&E||(e*=-1),ce.convert(Math.abs(holdY-Z))))}ze(e),n()},l)}()},m)}}function me(){W.zimAccessibility&&W.zimAccessibility.aria||(!1,clearTimeout(Q),clearTimeout(J))}function ze(e){var t;if("number"==w){var o=X;X+=H*e*V,X=kt.decimals(X,R),h?X>W.max?X=W.min:X<W.min&&(X=W.max):(X>W.max?(X=1==k?W.max:o,g&&(he.cursor="default")):g&&(he.cursor="pointer"),X<W.min&&(X=1==k?W.min:o))}else{if(t=Y+e,h)t>n.length-1&&(t=0),t<0&&(t=n.length-1);else{if(t>n.length-1)return void(g&&(he.cursor="default"));if(g&&(he.cursor="pointer"),t<0)return}Y=t}ye("number"==w?X:n[Y],"number"==w?X:Y),W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue}function ve(){W.keyFocus=!0;var e=document.activeElement;e&&e.blur()}function ye(e,t){Y=t,g&&("number"==w&&0!=e&&0<R&&(e=kt.decimals(e,R,!0)),l.text=e,l.x=he.x+he.getBounds().width/2,l.y=he.y+(he.getBounds().height-l.getBounds().height)/2),a&&(ee.alpha=1,te.color=o,ee.cursor="pointer",oe.alpha=1,ne.color=o,oe.cursor="pointer",h||("number"==w?(Y==W.min&&(0<V?be():we()),Y==W.max&&(0<V?we():be())):(0==Y&&(s?we():be()),Y==n.length-1&&(s?be():we())))),!oe||kt.OPTIMIZE||!zns&&OPTIMIZE||!oe.stage?!l||kt.OPTIMIZE||!zns&&OPTIMIZE||!l.stage||l.stage.update():oe.stage.update(),W.zimAccessibility&&W.zimAccessibility.changeTitle(W,null,!0)}function be(){a&&(ee.alpha=.8,te.color="#aaa",ee.cursor="default")}function we(){a&&(oe.alpha=.8,ne.color="#aaa",oe.cursor="default")}a&&(oe=this.containerNext=new kt.Container({style:!1}),this.addChild(oe),oe.hitArea=de.clone(),ne=this.arrowNext=new kt.Triangle(F,80,80,o,null,null,null,null,null,!1),-1!=u&&0<d&&(oe.shadow=new createjs.Shadow(u,3,3,d)),oe.addChild(ne),oe.cursor="pointer",oe.on("mousedown",function(e){if(!W.zimAccessibility||!W.zimAccessibility.aria){H=k;var t=s?E?-1:1:S?1:-1;ze(t),fe(t,null,null,e.stageX,e.stageY)}}),f&&oe.on("pressup",me),oe.y=s?(oe.rotation=0,oe.x=e/2,oe.getBounds().height/2):(oe.rotation=90,oe.x=g?he.x+he.getBounds().width+oe.getBounds().height/2+25:ee.x+ee.getBounds().width,oe.getBounds().width/2)),f&&g&&he.on("pressup",me),A&&((re=this.prev2=new kt.Container({style:!1})).hitArea=de.clone(),ie=this.arrowPrev2=new kt.Triangle(F,80,80,"rgba(0,0,0,.2)",o,2,null,null,null,!1),re.addChild(ie),re.cursor="pointer",re.sca(P),re.alpha=.5,re.on("mousedown",function(e){if(!W.zimAccessibility||!W.zimAccessibility.aria){H=T;var t=s?S?-1:1:E?1:-1;ze(t),fe(t,null,!0,e.stageX,e.stageY)}}),f&&re.on("pressup",me),(ae=this.next2=new kt.Container({style:!1})).hitArea=de.clone(),le=this.arrowNext2=new kt.Triangle(F,80,80,"rgba(0,0,0,.2)",o,2,null,null,null,!1),ae.addChild(le),ae.cursor="pointer",ae.sca(P),ae.alpha=.5,ae.on("mousedown",function(e){if(!W.zimAccessibility||!W.zimAccessibility.aria){H=T;var t=s?S?1:-1:E?-1:1;ze(t),fe(t,null,!0,e.stageX,e.stageY)}}),f&&ae.on("pressup",me),s?(re.y=this.height/2,re.x=-re.width/2-25*Math.max(.2,Math.min(1,P)),re.rotation=270,ae.y=this.height/2,ae.x=this.width+ae.width/2+25*Math.max(.2,Math.min(1,P)),ae.rotation=90):(ae.x=this.width/2,ae.y=-ae.height/2-25*Math.max(.2,Math.min(1,P)),ae.rotation=0,re.x=this.width/2,re.y=this.height+re.height/2+25*Math.max(.2,Math.min(1,P)),re.rotation=180),this.addChild(re,ae)),Object.defineProperty(this,"stepperArray",{get:function(){if("number"==w){n=[];for(var e=W.min;e<=W.max;e+=Math.min(k,T))n.push(kt.decimals(e,R,null,!1))}return n},set:function(e){n=e,W.selectedIndex=W.selectedIndex}}),Object.defineProperty(this,"min",{get:function(){return x},set:function(e){"number"==w?(W.currentValue<e&&(W.currentValue=e),x=e,W.selectedIndex=W.selectedIndex):x=e}}),Object.defineProperty(this,"max",{get:function(){return C},set:function(e){"number"==w?(W.currentValue>e&&(W.currentValue=e),C=e,W.selectedIndex=W.selectedIndex):C=e}}),ye("number"==w?X:n[Y],"number"==w?X:Y),Object.defineProperty(this,"selectedIndex",{get:function(){return"number"==w?W.stepperArray.indexOf(W.currentValue):Y},set:function(e){zot(e)||("number"==w?(Y=Math.min(W.stepperArray.length-1,Math.max(0,e)),ye(X=W.stepperArray[Y],X)):(e=Math.min(n.length-1,Math.max(0,e)),ye(n[Y=e],Y)))}}),Object.defineProperty(this,"currentValue",{get:function(){return"number"==w?X:n[Y]},set:function(e){if(!zot(e))if("number"==w){if(e=Number(e),W.max>W.min){if(e>W.max||e<W.min)return}else if(e<W.max||e>W.min)return;if(newIndex=W.stepperArray.indexOf(e),newIndex<0)return;Y=newIndex,ye(X=W.stepperArray[Y],X)}else{if(!(-1<n.indexOf(e)))return;if((e=n.indexOf(e))==W.selectedIndex)return;ye(n[Y=e],Y)}}}),Object.defineProperty(this,"currentValueEvent",{get:function(){return W.currentValue},set:function(e){String(e)!=String(W.currentValue)&&(W.currentValue=e,W.dispatchEvent("change"))}}),Object.defineProperty(this,"continuous",{get:function(){return h},set:function(e){h=e,"number"==w?ye(X,X):ye(n[W.selectedIndex],W.selectedIndex)}}),this._enabled=!0,Object.defineProperty(W,"enabled",{get:function(){return W._enabled},set:function(e){Se(W,e),e?("number"==w?ye(X,X):ye(n[W.selectedIndex],W.selectedIndex),window.addEventListener("keydown",W.keyDownEvent)):(be(),we(),window.removeEventListener("keydown",W.keyDownEvent),g&&(l.mouseChildren=!1),g&&(l.mouseEnabled=!1)),!oe||kt.OPTIMIZE||!zns&&OPTIMIZE||!oe.stage?!l||kt.OPTIMIZE||!zns&&OPTIMIZE||!l.stage||l.stage.update():oe.stage.update()}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==W},set:function(e){kt.KEYFOCUS=W}}),kt.KEYFOCUS||ve(),this.on("mousedown",function(){ve()});var xe=!1,Ce=!1,ke=!1;this.on("mousedown",function(){W.zimAccessibility&&W.zimAccessibility.aria||(W.focus=!0,ke=Ce=!(xe=!0))}),this.keyDownEvent=function(e){if(W.stage&&(W.zimAccessibility&&W.focus||!W.zimAccessibility&&W.keyFocus)){e||(e=event);var t,o=e.keyCode;if(I&&37<=o&&o<=40){var n=E?40:38,r=S?39:37,i=E?38:40,a=S?37:39;o==n||o==r?(H=s&&o==n||!s&&o==r?k:T,ze(1)):o!=i&&o!=a||(H=s&&o==i||!s&&o==a?k:T,ze(-1))}if(B)if("number"==w)!e.shiftKey&&48<=o&&o<=57?t=o-48:96<=o&&o<=105?t=o-96:190==o?Ce=!0:173==o||189==o?(W.currentValue=-1*W.currentValue,W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue,ke=!ke):46==o&&(Ce=!(xe=!0)),xe&&!zot(t)?(Ce&&(t/=10),ke&&(t*=-1),W.currentValue=t,xe=!1,W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue):zot(t)||(Ce&&(t=String(t/10).substr(1)),W.currentValue=Number(Math.floor(Number(l.text))+String(t)),W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue);else W.currentValue=String.fromCharCode(e.keyCode),W.currentValue!=ge&&W.dispatchEvent("change"),ge=W.currentValue}},window.addEventListener("keydown",this.keyDownEvent),this.next=function(){ze(1)},!(this.prev=function(){ze(-1)})!==M&&Oe(this,L),this.clone=function(){return W.cloneProps(new kt.Stepper(n,e,o,t,r,l.clone(),i,s,a,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,this.group,j))},this.dispose=function(){return window.removeEventListener("keydown",W.keyDownEvent),W.stage&&W.stage.off(_),this.zimContainer_dispose(),!0}},kt.zut=function(e){if(zot(e)||!e.key)return!0;kt.async("https://zimjs.com/gamdata.php?id="+e.key+"&player="+e.player+"&score="+e.score+"&reverse="+e.info.reverse+"&total="+e.info.total+"&allowZero="+e.info.allowZero,e.info.type)},kt.extend(kt.Stepper,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Slider=function(a,l,t,s,e,o,n,c,r,i,u,d,h,g,p,f,m,z){var v;if(v=zob(kt.Slider,arguments,"min, max, step, button, barLength, barWidth, barColor, vertical, useTicks, inside, keyArrows, keyArrowsStep, keyArrowsH, keyArrowsV, damp, style, group, inherit",this))return v;z_d("62"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Slider",this.group=m;var y=!1===f?{}:kt.getStyle(this.type,this.group,z);if(zot(a)&&(a=null!=y.min?y.min:0),zot(l)&&(l=null!=y.max?y.max:10),l-a!=0){zot(t)&&(t=null!=y.step?y.step:0),zot(e)&&(e=null!=y.barLength?y.barLength:300),zot(o)&&(o=null!=y.barWidth?y.barWidth:3),zot(n)&&(n=null!=y.barColor?y.barColor:"#666"),zot(c)&&(c=null!=y.vertical&&y.vertical),zot(r)&&(r=null!=y.useTicks&&y.useTicks),zot(i)&&(i=null!=y.inside&&y.inside),zot(u)&&(u=null==y.keyArrows||y.keyArrows),zot(h)&&(h=null==y.keyArrowsH||y.keyArrowsH),zot(g)&&(g=null==y.keyArrowsV||y.keyArrowsV),zot(d)&&(d=null!=y.keyArrowsStep?y.keyArrowsStep:(l-a)/100),zot(p)&&(p=null!=y.damp&&y.damp);var b,w,x=!(!zot(y.backing)&&"Pattern"!=y.backing.type);if(zot(s)){var C=30,k=40;c&&(C=50,k=40),s=null!=y.button?y.button:new kt.Button({width:null!=y.width?y.width:C,height:null!=y.height?y.height:k,label:"",backgroundColor:null!=y.backgroundColor?y.backgroundColor:"#fff",rollBackgroundColor:null!=y.rollBackgroundColor?y.rollBackgroundColor:"#ddd",borderColor:null!=y.borderColor?y.borderColor:x?"#666":null,borderWidth:null!=y.borderWidth?y.borderWidth:x?1:null,corner:null!=y.corner?y.corner:0,backing:null!=y.backing?y.backing:null,rollBacking:null!=y.rollBacking?y.rollBacking:null,hitPadding:30,style:!1})}s.rollPersist=!0,c?(b=s.width,i?(w=e,this.setBounds(0,0,b,w)):(w=e+s.height,this.setBounds(-s.width/2,-s.height/2,b,w))):(w=Math.max(s.height,o),i?(b=e,this.setBounds(0,0,b,w)):(b=e+s.width,this.setBounds(-s.width/2,-s.height/2,b,w)));var T,A,P,B,I,S,E,M,O,j=this,D=a,L=0;if(this.button=s,this.cursor="pointer",r&&0!=t){B=this.ticks=new kt.Shape({style:!1}),this.addChild(B),(I=B.graphics).ss(1).s(n);var Y=Math.round((l-a)/t),X=(l-a)/Y;if(X!=t&&zon&&zog("zim.Slider() : non-divisible step ("+t+") adjusted"),t=X,i)var R=(e-(c?s.height:s.width))/Math.abs(Y);else R=e/Math.abs(Y)}if(c){var _=i?s.height/2:0;if((T=this.bar=new kt.Rectangle(o,e,n,null,null,null,null,!1)).expand(20,0),T.centerReg(this),s.centerReg(this),P=T.getBounds(),A=new createjs.Rectangle(T.x,P.y+_,0,P.height-2*_),r&&0!=t){for(var W=0;W<=Math.abs(Y);W++)I.mt(0,_+R*W).lt(20,_+R*W);B.x=T.x+15}}else{_=i?s.width/2:0;if((T=this.bar=new kt.Rectangle(e,o,n,null,null,null,null,!1)).expand(0,20),T.centerReg(this),s.centerReg(this),P=T.getBounds(),A=new createjs.Rectangle(P.x+_,T.y,P.width-2*_,0),r&&0!=t){for(W=0;W<=Math.abs(Y);W++)I.mt(_+R*W,0).lt(_+R*W,-20);B.y=T.y-10}}s.x=A.x,s.y=A.y,s.on("mousedown",function(e){j.focus=!0;var t=j.globalToLocal(e.stageX,e.stageY);S=t.x-s.x,E=t.y-s.y,j.stage&&(j.stage.mouseMoveOutside=!0)}),s.on("pressmove",function(e){q(e)}),T.on("mousedown",function(e){E=S=0,j.zimAccessibility&&j.zimAccessibility.aria||q(e)}),p&&(M=a,O=new kt.Damp(M,p),j.ticker=kt.Ticker.add(function(){M=O.convert(D)})),Object.defineProperty(this,"currentValue",{get:function(){return p?M:D},set:function(e){zot(e)||(a<l?(e<a&&(e=a),l<e&&(e=l)):(a<e&&(e=a),e<l&&(e=l)),D=e=G(e),O&&O.immediate(D),L=c?(s.y=(e-l)/(a-l)*A.height+_,s.y):(s.x=(e-a)/(l-a)*A.width+_,s.x),K(),kt.OPTIMIZE||!zns&&OPTIMIZE||!j.stage||j.stage.update())}}),Object.defineProperty(this,"currentValueEvent",{get:function(){return p?M:D},set:function(e){e!=j.currentValue&&(j.currentValue=e,j.dispatchEvent("change"))}}),Object.defineProperty(this,"min",{get:function(){return a},set:function(e){zon&&zog("min is read only")}}),Object.defineProperty(this,"max",{get:function(){return l},set:function(e){zon&&zog("max is read only")}}),Object.defineProperty(this,"step",{get:function(){return t},set:function(e){zon&&zog("step is read only")}}),Object.defineProperty(this,"keyArrowsH",{get:function(){return h},set:function(e){h=e}}),Object.defineProperty(this,"keyArrowsV",{get:function(){return g},set:function(e){g=e}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==j},set:function(e){kt.KEYFOCUS=j}}),u&&!kt.KEYFOCUS&&Z(),this.on("mousedown",function(){u&&Z()});var F=!1,H=!1,V=!1,N=!1;this.keyDownEvent=function(e){j.stage&&(j.zimAccessibility&&j.focus||!j.zimAccessibility&&j.keyFocus)&&(37==e.keyCode&&h?F=!0:40==e.keyCode&&g?H=!0:39==e.keyCode&&h?V=!0:38==e.keyCode&&g&&(N=!0),null==j.keyInterval&&(F||H||V||N)&&(Q(),j.keyTimeout=setTimeout(function(){null==j.keyInterval&&(F||H||V||N)&&(j.keyInterval=setInterval(Q,40))},140)))},window.addEventListener("keydown",this.keyDownEvent),j.keyUpEvent=function(e){37==e.keyCode?F=!1:40==e.keyCode?H=!1:39==e.keyCode?V=!1:38==e.keyCode&&(N=!1),null==j.keyInterval||F||H||V||N||(clearInterval(j.keyInterval),j.keyInterval=null)},window.addEventListener("keyup",this.keyUpEvent),this._enabled=!0,Object.defineProperty(j,"enabled",{get:function(){return j._enabled},set:function(e){Se(j,e),e?(window.addEventListener("keydown",j.keyDownEvent),window.addEventListener("keyup",j.keyUpEvent)):(window.removeEventListener("keydown",j.keyDownEvent),window.removeEventListener("keyup",j.keyUpEvent))}}),!1!==f&&Oe(this,y),this.clone=function(){return j.cloneProps(new kt.Slider(a,l,t,s.clone(),e,o,n,c,r,i,u,d,h,g,p,f,this.group,z))},this.dispose=function(){return window.removeEventListener("keydown",j.keyDownEvent),window.removeEventListener("keyup",j.keyUpEvent),this.zimContainer_dispose(),!0}}else zog("ZIM Slider range must not be 0");function G(e){return 0==t?e:Math.round(e/t)*t}function q(e){var t,o,n,r=j.globalToLocal(e.stageX,e.stageY),i=(t=r.x-S,o=r.y-E,n=A,t=Math.max(n.x,Math.min(n.x+n.width,t)),o=Math.max(n.y,Math.min(n.y+n.height,o)),{x:t,y:o});L=c?(s.x=i.x,D=G((i.y-A.y)/A.height*(a-l)),s.y=A.y+D*A.height/(a-l),D+=l,s.y!=L&&j.dispatchEvent("change"),s.y):(D=G((i.x-A.x)/A.width*(l-a)),s.x=A.x+D*A.width/(l-a),D+=a,s.y=i.y,s.x!=L&&j.dispatchEvent("change"),s.x),K(),kt.OPTIMIZE||!zns&&OPTIMIZE||!j.stage||j.stage.update()}function U(e){return 0<e?1:-1}function K(){j.zimAccessibility&&j.zimAccessibility.changeTitle(j,null,!0)}function Z(){j.keyFocus=!0;var e=document.activeElement;e&&e.blur()}function Q(){(F||H)&&(j.currentValueEvent-=0<t?t*U(l-a):d*U(l-a)),(V||N)&&(j.currentValueEvent+=0<t?t*U(l-a):d*U(l-a))}},kt.extend(kt.Slider,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Dial=function(n,r,i,e,t,o,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k){var T;if(T=zob(kt.Dial,arguments,"min, max, step, width, backgroundColor, indicatorColor, indicatorScale, indicatorType, innerCircle, innerScale, useTicks, innerTicks, tickColor, limit, keyArrows, keyArrowsStep, keyArrowsH, keyArrowsV, continuous, continuousMin, continuousMax, damp, style, group, inherit",this))return T;z_d("63"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Dial",this.group=C;var A=!1===x?{}:kt.getStyle(this.type,this.group,k);if(zot(n)&&(n=null!=A.min?A.min:0),zot(r)&&(r=null!=A.max?A.max:10),r-n!=0){zot(i)&&(i=null!=A.step?A.step:1),zot(e)&&(e=null!=A.width?A.width:100),zot(t)&&(t=null!=A.backgroundColor?A.backgroundColor:"#666"),zot(o)&&(o=null!=A.indicatorColor?A.indicatorColor:"#222"),zot(a)&&(a=null!=A.indicatorScale?A.indicatorScale:1),zot(l)&&(l=null!=A.indicatorType?A.indicatorType:"arrow"),zot(s)&&(s=null==A.innerCircle||A.innerCircle),zot(c)&&(c=null!=A.innerScale?A.innerScale:.5),zot(u)&&(u=null==A.useTicks||A.useTicks),zot(d)&&(d=null!=A.innerTicks&&A.innerTicksinnerTicks),zot(h)&&(h=null!=A.tickColor?A.tickColor:o),zot(g)&&(g=null==A.limit||A.limit),zot(p)&&(p=null==A.keyArrows||A.keyArrows),zot(f)&&(f=null!=A.keyArrowsStep?A.keyArrowsStep:(r-n)/100),zot(m)&&(m=null==A.keyArrowsH||A.keyArrowsH),zot(z)&&(z=null==A.keyArrowsV||A.keyArrowsV),zot(v)&&(v=null!=A.continuous&&A.continuous),v&&(g=null!=A.limit&&A.limit),zot(w)&&(w=null!=A.damp&&A.damp),0==g&&(w=null);var P=this;this.cursor="pointer";var B=e/2,I=n,S=0,E=this.backing=new kt.Circle(B,t,null,null,null,null,!1);if(this.addChild(E),s){var M=d?"rgba(0,0,0,.2)":"rgba(0,0,0,.1)";"black"!=t&&"#000"!=t&&"#000000"!=t&&"#111"!=t&&"#111111"!=t||(M="#222");var O=this.inner=new kt.Circle(B*c,M,null,null,null,null,!1);if(this.addChild(O),!d){var j=this.inner2=new kt.Circle(B*(c-.1),"rgba(0,0,0,.1)",null,null,null,null,!1);this.addChild(j)}}var D,L,Y,X,R=Math.abs(r-n)/i;if(u&&0!=i){var _=this.ticks=new kt.Container({style:!1});this.addChild(_);for(var W=0;W<(v?R:R+1);W++){var F;(F=new kt.Rectangle(1,.2*B,h,null,null,null,null,!1)).regY=B*(d?c-.05:1.28),F.regX=.5,F.rotation=360/(v?R:R+1)*W,_.addChild(F)}}if(this.setBounds(-B,-B,e,e),"dot"==l||"circle"==l){var H=this.indicator=new kt.Container({style:!1}),V=this.indicatorShape=new kt.Circle(.19*B,o,null,null,null,null,!1);H.addChild(V),kt.sca(H,a),H.regY=B-H.getBounds().width*a/2-.07*B}else if("line"==l||"rectangle"==l){H=this.indicator=new kt.Container({style:!1}),V=this.indicatorShape=new kt.Rectangle(.1*B,.3*B,o,null,null,null,null,!1);H.addChild(V),kt.sca(H,a),H.regY=B-H.getBounds().width*a/2-.07*B,H.regX=.05*B}else{H=this.indicator=new kt.Container({style:!1}),V=this.indicatorShape=new kt.Triangle(.4*B,.4*B,.4*B,o,null,null,null,null,!1);H.addChild(V),kt.sca(H,a),H.regY=B-H.getBounds().height*a*(d?.85:.75),d&&(V.rotation=180)}H.regY/=a,this.addChild(H);var N,G,q=0;if(v)var U=0,K=0,Z=0,Q=!1,J=!1,$=!0;else n;this.on("mousedown",function(e){if(!P.zimAccessibility||!P.zimAccessibility.aria){D=H.rotation;var t=P.parent.globalToLocal(e.stageX,e.stageY),o=t.x-P.x,n=P.y-t.y;L=180*Math.atan2(o,n)/Math.PI;var r=(new Date).getTime();Y=P.on("pressmove",function(e){if(Q){var t=P.parent.globalToLocal(e.stageX,e.stageY),o=t.x-P.x,n=P.y-t.y;L=180*Math.atan2(o,n)/Math.PI,D=H.rotation}o=(t=P.parent.globalToLocal(e.stageX,e.stageY)).x-P.x,n=P.y-t.y;var r=180*Math.atan2(o,n)/Math.PI,i=D+r-L;i=(i+36e5)%360,g&&180<Math.abs(i-q)||(le(i),q=i)}),X=this.on("pressup",function(e){(new Date).getTime()-r<200&&(t=P.parent.globalToLocal(e.stageX,e.stageY),o=t.x-P.x,n=P.y-t.y,le(180*Math.atan2(o,n)/Math.PI));D=H.rotation,P.off("pressmove",Y),P.off("pressup",X)})}}),w&&(N=n,G=new kt.Damp(N,w),P.ticker=kt.Ticker.add(function(){N=G.convert(I)})),Object.defineProperty(this,"currentValue",{get:function(){return w?N:I},set:function(e){zot(e)||(v?(Q=!1,zot(y)||zot(b)?zot(y)?zot(b)||b<e&&(e=b,Q=!0):e<y&&(e=y,Q=!0):y<b?(e<y&&(e=y,Q=!0),b<e&&(e=b,Q=!0)):(y<e&&(e=y,Q=!0),e<b&&(e=b,Q=!0)),$&&(J=!0,Z=360*Math.floor(e/(r-n)))):n<r?(e<n&&(e=g?n:r),r<e&&(e=g?r:n)):(n<e&&(e=g?n:r),e<r&&(e=g?r:n)),e=re(I=e),w&&w.immediate(I),H.rotation=360*(e-n)/(r-n+(v?0:ie(r-n)*i)),H.rotation=(H.rotation+36e5)%360,S=e-n,q=H.rotation,ae(),kt.OPTIMIZE||!zns&&OPTIMIZE||!P.stage||P.stage.update())}}),Object.defineProperty(this,"currentValueEvent",{get:function(){return w?N:I},set:function(e){e!=P.currentValue&&(P.currentValue=e,P.dispatchEvent("change"))}}),Object.defineProperty(this,"min",{get:function(){return n},set:function(e){v?n=e:zon&&zog("min is read only")}}),Object.defineProperty(this,"max",{get:function(){return r},set:function(e){v?r=e:zon&&zog("max is read only")}}),Object.defineProperty(this,"continuous",{get:function(){return v},set:function(e){zon&&zog("continuous is read only")}}),Object.defineProperty(this,"continuousMin",{get:function(){return y},set:function(e){y=e,P.currentValue<y&&(P.currentValue=y)}}),Object.defineProperty(this,"continuousMax",{get:function(){return b},set:function(e){b=e,P.currentValue>b&&(P.currentValue=b)}}),Object.defineProperty(this,"step",{get:function(){return i},set:function(e){zon&&zog("step is read only")}}),Object.defineProperty(this,"keyArrowsH",{get:function(){return m},set:function(e){m=e}}),Object.defineProperty(this,"keyArrowsV",{get:function(){return z},set:function(e){z=e}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==P},set:function(e){kt.KEYFOCUS=P}}),p&&!kt.KEYFOCUS&&se(),this.on("mousedown",function(){p&&se()});var ee=!1,te=!1,oe=!1,ne=!1;this.keyDownEvent=function(e){P.stage&&(P.zimAccessibility&&P.focus||!P.zimAccessibility&&P.keyFocus)&&(37==e.keyCode&&m?ee=!0:40==e.keyCode&&z?te=!0:39==e.keyCode&&m?oe=!0:38==e.keyCode&&z&&(ne=!0),null==P.keyInterval&&(ee||te||oe||ne)&&(ce(),P.keyTimeout=setTimeout(function(){null==P.keyInterval&&(ee||te||oe||ne)&&(P.keyInterval=setInterval(ce,40))},140)))},window.addEventListener("keydown",this.keyDownEvent),P.keyUpEvent=function(e){37==e.keyCode?ee=!1:40==e.keyCode?te=!1:39==e.keyCode?oe=!1:38==e.keyCode&&(ne=!1),null==P.keyInterval||ee||te||oe||ne||(clearInterval(P.keyInterval),P.keyInterval=null)},window.addEventListener("keyup",this.keyUpEvent),this._enabled=!0,Object.defineProperty(P,"enabled",{get:function(){return P._enabled},set:function(e){Se(P,e),e?(P.keyDownEvent=window.addEventListener("keydown",P.keyDownEvent),P.keyUpEvent=window.addEventListener("keyup",P.keyUpEvent)):(window.removeEventListener("keydown",P.keyDownEvent),window.removeEventListener("keyup",P.keyUpEvent))}}),!1!==x&&Oe(this,A),this.clone=function(){return P.cloneProps(new kt.Dial(n,r,i,e,t,o,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,this.group,k))},this.dispose=function(){return window.removeEventListener("keydown",P.keyDownEvent),window.removeEventListener("keyup",P.keyUpEvent),this.zimContainer_dispose(),!0}}else zog("ZIM Dial range must not be 0");function re(e){return 0==i?e:Math.round(e/i)*i}function ie(e){return 0<e?1:-1}function ae(){P.zimAccessibility&&P.zimAccessibility.changeTitle(P,null,!0)}function le(e){if(v){J&&(J=!1),U+180<e?Z-=360:e<U-180&&(Z+=360),K=Z+e,$=!1;var t=P.currentValue;return P.currentValue=re(K*(r-n)/360),t!=P.currentValue&&P.dispatchEvent("change"),U=e,$=!0}var o;e<0&&(e+=360),e%=360,0!=i?(o=re((e=Math.min(e,360-360/(R+1)))/(360-360/(R+1))*(r-n)),H.rotation=o*(360-360/(R+1))/(r-n)):o=(H.rotation=e)/360*(r-n),o!=S&&(I=(S=o)+n,P.dispatchEvent("change"),kt.OPTIMIZE||!zns&&OPTIMIZE||!P.stage||P.stage.update()),ae()}function se(){P.keyFocus=!0;var e=document.activeElement;e&&e.blur()}function ce(){(ee||te)&&(P.currentValueEvent-=0<i?i*ie(r-n):f*ie(r-n)),(oe||ne)&&(P.currentValueEvent+=0<i?i*ie(r-n):f*ie(r-n))}},kt.extend(kt.Dial,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Tabs=function(i,a,o,l,s,c,u,d,g,p,f,m,r,z,v,y,n,b,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H,V,N,e,G){var t;if(t=zob(kt.Tabs,arguments,"width, height, tabs, backgroundColor, rollBackgroundColor, selectedBackgroundColor, selectedRollBackgroundColor, color, rollColor, selectedColor, selectedRollColor, vertical, spacing, currentEnabled, currentSelected, corner, base, keyEnabled, gradient, gloss, backing, rollBacking, wait, waitTime, waitBackgroundColor, rollWaitBackgroundColor, waitColor, rollWaitColor, waitModal, waitEnabled, backdropColor, align, valign, labelAlign, labelValign, labelIndent, labelIndentHorizontal, labelIndentVertical, indent, useTap, excludeCustomTap, style, group, inherit",this))return t;z_d("65");var q=!1===N?{}:kt.getStyle("Tabs",this.group,G);zot(m)&&(m=null!=q.vertical&&q.vertical);var U=!zot(i);if(zot(i)&&(i=null!=q.width?q.width:m?60:240),zot(a)&&(a=null!=q.height?q.height:m?240:60),this.zimContainer_constructor(null,null,null,null,!0),this.type="Tabs",this.group=e,(zot(o)||o.length<=0)&&(o=null!=q.tabs?q.tabs:[1,2,3,4]),zot(l)&&(l=null!=q.backgroundColor?q.backgroundColor:"#777"),zot(s)&&(s=null!=q.rollBackgroundColor?q.rollBackgroundColor:"#555"),zot(c)&&(c=null!=q.selectedBackgroundColor?q.selectedBackgroundColor:"#333"),zot(u)&&(u=null!=q.selectedRollBackgroundColor?q.selectedRollBackgroundColor:s),zot(d)&&(d=null!=q.color?q.color:"white"),zot(g)&&(g=null!=q.rollColor?q.rollColor:d),zot(p)&&(p=null!=q.selectedColor?q.selectedColor:d),zot(f)&&(f=null!=q.selectedRollColor?q.selectedRollColor:g),zot(k)&&(k=null!=q.backing?q.backing:null),zot(T)&&(T=null!=q.rollBacking?q.rollBacking:null),zot(D)&&(D=null!=q.align?q.align:"center"),zot(L)&&(L=null!=q.valign?q.valign:"center"),zot(Y)&&(Y=null!=q.labelAlign?q.labelAlign:D),zot(X)&&(X=null!=q.labelValign?q.labelValign:L),zot(F)&&(F=null!=q.indent?q.indent:10),zot(R)&&(R=null!=q.labelIndent?q.labelIndent:F),zot(_)&&(_=null!=q.labelIndentHorizontal?q.labelIndentHorizontal:R),zot(W)&&(W=null!=q.labelIndentVertical?q.labelIndentVertical:R),zot(z)&&(z=null!=q.currentEnabled&&q.currentEnabled),zot(v)&&(v=null==q.currentSelected||q.currentSelected),v||(z=!0),zot(r)&&(r=null!=q.spacing?q.spacing:1),zot(y)&&(y=null!=q.corner?q.corner:0),zot(x)&&(x=null!=q.gradient?q.gradient:null),zot(C)&&(C=null!=q.gloss?q.gloss:null),zot(n)&&(n=null!=q.base?q.base:0!=y||Array.isArray(y)?m?"left":"bottom":"none"),zot(b)&&(b=null==q.keyEnabled||q.keyEnabled),zot(H)&&(H=null!=q.useTap&&q.useTap),zot(V)&&(V=null!=q.excludeCustomTap&&q.excludeCustomTap),zot(j)&&(j=null!=q.backdropColor?q.backdropColor:null),"none"==n||0==y||Array.isArray(y))Array.isArray(y)||(y=[y,y,y,y]);else switch(n){case"bottom":y=[y,y,0,0];break;case"left":y=[0,y,y,0];break;case"top":y=[0,0,y,y];break;case"right":y=[y,0,0,y]}var K=this;this.keyEnabled=b;var Z,Q=0,J=[],$=[],ee=o.length,te=(i-r*(ee-1))/ee,oe=(a-r*(ee-1))/ee;if(!zot(j)){var ne=this.backdrop=new kt.Rectangle(i,a,j,null,null,null,null,!1);this.addChild(ne)}var re=!1;function ie(e){for(var t,o=0;o<e.length;o++){var n=e[o];n.constructor!=={}.constructor?t="string"==typeof n||"number"==typeof n||"Label"==n.type?(e[o]={type:"TabObject",label:String(null!=n)||"Label"==n.type?n:"1"},t&&"TabObject"!=t&&(re=!0),"TabObject"):(t&&"TabObject"==t&&(re=!0),"Other"):(t&&"TabObject"!=t&&(re=!0),t="TabObject",n.type="TabObject")}}ie(o);for(var ae,le,se=0,ce=0,ue=0;ue<o.length;ue++)ae=o[ue],m?U&&(ae.width=ae.width?ae.width:i):(zot(ae.width)&&ce++,se+=zot(ae.width)?te:ae.width);if(!m)if(i-r*(ee-1)<se)for(ue=0;ue<o.length;ue++)(ae=o[ue]).width=(i-r*(ee-1))/se*(zot(ae.width)?te:ae.width);else if(Math.round(se)<Math.round(i-r*(ee-1))&&0<ce)for(le=(ee*te-(se-ce*te))/ce,ue=0;ue<o.length;ue++)(ae=o[ue]).width=zot(ae.width)?le:ae.width;function de(e,t){for(ue=0;ue<e.length;ue++)""!=(ae=e[ue])&&"TabObject"==ae.type&&(zot(ae.label)&&(ae.label=" "),"string"!=typeof ae.label&&"number"!=typeof ae.label||(ae.label=new kt.Label({text:ae.label,size:null!=q.size?q.size:m?oe/2:a/2,font:null!=q.font?q.font:null,style:!1,inherit:t})))}de(o);var he=0;for(ue=0;ue<o.length;ue++)!(ae=o[ue]).width&&m&&ae.label.width>he&&(he=ae.label.width);var ge=0;function pe(e,t){var o=[],n=[];for(ue=0;ue<e.length;ue++){if("TabObject"==(ae=e[ue]).type){var r={color:zot(ae.color)?d:ae.color,rollColor:zot(ae.rollColor)?g:ae.rollColor,selectedColor:zot(ae.selectedColor)?p:ae.selectedColor,selectedRollColor:zot(ae.selectedRollColor)?f:ae.selectedRollColor,backgroundColor:zot(ae.backgroundColor)?l:ae.backgroundColor,rollBackgroundColor:zot(ae.rollBackgroundColor)?s:ae.rollBackgroundColor,selectedBackgroundColor:zot(ae.selectedBackgroundColor)?c:ae.selectedBackgroundColor,selectedRollBackgroundColor:zot(ae.selectedRollBackgroundColor)?u:ae.selectedRollBackgroundColor,wait:zot(ae.wait)?A:ae.wait};if(t)for(aStyle in t)zot(t[aStyle])||(r[aStyle]=t[aStyle]);(Z=new kt.Button({width:m?zot(ae.width)?U?i:he+oe/2+y[0]/2:ae.width:zot(ae.width)?te:ae.width,height:m?oe:a,label:ae.label,borderColor:null!=q.borderColor?q.borderColor:null,borderWidth:null!=q.borderWidth?q.borderWidth:null,backgroundColor:r.backgroundColor,rollBackgroundColor:r.rollBackgroundColor,corner:y,shadowColor:-1,gradient:x,gloss:C,backing:k?k.clone():null,rollBacking:T?T.clone():null,wait:r.wait,waitTime:zot(ae.waitTime)?P:ae.waitTime,waitBackgroundColor:zot(ae.waitBackgroundColor)?B:ae.waitBackgroundColor,rollWaitBackgroundColor:zot(ae.rollWaitBackgroundColor)?I:ae.rollWaitBackgroundColor,waitColor:zot(ae.waitColor)?S:ae.waitColor,rollWaitColor:zot(ae.rollWaitBackgroundColor)?E:ae.rollWaitColor,waitModal:zot(ae.waitModal)?M:ae.waitModal,waitEnabled:zot(ae.waitEnabled)?O:ae.waitEnabled,align:Y,valign:X,indentHorizontal:_,indentVertical:W,inherit:q})).tabInfo=r,Z.color=Z.tabInfo.color,Z.rollColor=Z.tabInfo.rollColor,Z.type="TabsButton"}else(Z=new kt.Container).tabInfo={},V&&(Z.excludeTap=!0),Z.tabInfo.color=zot(ae.color)?d:ae.color,Z.tabInfo.backgroundColor=zot(ae.backgroundColor)?l:ae.backgroundColor,new kt.Rectangle(Math.max(ae.width,m?U?i:he+oe/2+y[0]/2:te),Math.max(ae.height,m?oe:a),kt.faint).addTo(Z),ae.center(Z),"center"!=D&&"middle"!=D&&ae.pos(0,null,"right"==D),"center"!=L&&"middle"!=L&&ae.pos(null,0,null,"bottom"==L);Z.width>ge&&(ge=Z.width),H?Z.tap(function(e){ze(e.currentTarget.znum),K.dispatchEvent("change"),kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}):Z.zimTabEvent=Z.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(e){ze(e.currentTarget.znum),K.dispatchEvent("change"),kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}),Z.on("mousedown",function(e){K.buttonDown=e.currentTarget}),Z.on("pressup",function(){K.buttonDown=null}),n.push(ae.label),o.push(Z)}return[o,n]}var fe=pe(o);function me(){var e,t=0,o=0;for(ue=0;ue<$.length;ue++)(e=$[ue]).znum=ue,e.selectedIndex=ue,e.selectedIndex==Q&&v&&(e.backgroundColor=c,e.rollBackgroundColor=u,e.color=p),J[ue]&&(J[ue].znum=ue),K.addChild(e),m&&!U||(e.x=(i-e.width)/2,e.y=(a-e.height)/2),m?(e.y=o,o=e.y+e.height+r,"left"==D?e.x=("TabsButton"!=e.type||re?F:0)+(e.regX-e.getBounds().x)*e.scaleX:"right"==D&&(e.x=(U?i:ge)-e.width-("TabsButton"!=e.type||re?F:0))):(e.x=t,t=e.x+e.width+r,"top"==L?e.y=("TabsButton"!=e.type||re?F:0)+(e.regY-e.getBounds().y)*e.scaleY:"bottom"==L&&(e.y=a-e.height-("TabsButton"!=e.type||re?F:0))),0!=ue||z||(e.enabled=!1),e.enabled=!0;zot(j)||K.removeChild(ne),K.setBounds();var n=K.getBounds();if(n?(w=m&&U?i:n.width,h=m?n.height:a):w=h=0,K.setBounds(w,h),zot(j)||(ne.widthOnly=w,ne.heightOnly=h,K.addChildAt(ne,0)),m&&!U)for(ue=0;ue<=$.length;ue++)"center"!=D&&"middle"!=D||(e.x=(w-e.width)/2)}function ze(e){var t=$[Q];t&&v&&(t.tabInfo&&zot(t.tabInfo.wait)&&(t.tabInfo.backgroundColor&&(t.backgroundColor=t.tabInfo.backgroundColor),t.tabInfo.rollBackgroundColor&&(t.rollBackgroundColor=t.tabInfo.rollBackgroundColor),t.tabInfo.color&&t.label&&(t.color=t.tabInfo.color),t.tabInfo.rollColor&&t.label&&(t.rollColor=t.tabInfo.rollColor)),z||(t.enabled=!0)),(t=$[Q=e])&&(t.tabInfo&&zot(t.tabInfo.wait)&&v&&(t.tabInfo.selectedBackgroundColor&&(t.backgroundColor=t.tabInfo.selectedBackgroundColor),t.tabInfo.selectedRollBackgroundColor&&(t.rollBackgroundColor=t.tabInfo.selectedRollBackgroundColor),t.tabInfo.selectedColor&&t.label&&(t.color=t.tabInfo.selectedColor),t.tabInfo.selectedRollColor&&t.label&&(t.rollColor=t.tabInfo.selectedRollColor)),z||(t.enabled=!1))}function ve(){K.keyFocus=!0;var e=document.activeElement;e&&e.blur()}$=fe[0],J=fe[1],me(),this.addAt=function(e,t,o){zot(t)&&(t=$.length),t=kt.constrain(t,0,$.length),Array.isArray(e)||(e=[e]),ie(e),de(e,o);var n=pe(e,o),r=n[0],i=n[1];t<=Q&&(Q+=r.length);var a=[t,0].concat(r);return Array.prototype.splice.apply($,a),a=[t,0].concat(i),Array.prototype.splice.apply(J,a),me(),K},this.removeAt=function(e,t){if(0==$.length)return K;for(zot(e)&&(e=1),zot(t)&&(t=$.length-e),(t=kt.constrain(t,0,$.length-e))<=Q&&Q<=t+e&&(Q=-1),t+e<Q&&(Q-=e),ue=t;ue<t+e;ue++)$[ue].tabInfo&&($[ue].tabInfo.backgroundColor&&($[ue].backgroundColor=$[ue].tabInfo.backgroundColor),$[ue].tabInfo.color&&$[ue].label&&($[ue].color=$[ue].tabInfo.color)),H?$[ue].noTap():$[ue].off((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",$[ue].zimTabEvent),$[ue].removeFrom();return $.splice(t,e),J.splice(t,e),me(),K},window.addEventListener("keydown",function(e){if(K.keyEnabled&&K.keyFocus&&!K.zimAccessibility&&9==e.keyCode){var t=Q;e.shiftKey?ze(--t<0?o.length-1:t):ze(++t>o.length-1?0:t),K.dispatchEvent("change"),kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update(),e.preventDefault()}}),Object.defineProperty(this,"selected",{get:function(){return $[Q]},set:function(e){zon&&zog("selected is read only - try selectedIndex")}}),Object.defineProperty(this,"selectedIndex",{get:function(){return Q},set:function(e){ze(e),kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}),this.last=function(){return this.selectedIndex=this.buttons.length-1,this},this.first=function(){return this.selectedIndex=0,this},Object.defineProperty(this,"tabs",{get:function(){return Q},set:function(e){ze(Math.min(Math.max(e,0),o.length-1)),kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}),Object.defineProperty(this,"color",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.color:d},set:function(e){if(d=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.color=e),t==Q&&v||(K.buttons[t].color=d);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"rollColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.rollColor:g},set:function(e){if(g=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.rollColor=e),K.buttons[t].rollColor=g,t!=Q&&K.buttons[t].rolled&&(K.buttons[t].color=g);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"selectedColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.selectedColor:p},set:function(e){if(p=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.selectedColor=e),t==Q&&v&&(K.buttons[t].color=p);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"selectedRollColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.selectedRollColor:f},set:function(e){if(f=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.selectedRollColor=e),t==Q&&v&&K.buttons[t].rolled&&(K.buttons[t].color=f);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"backgroundColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.backgroundColor:l},set:function(e){if(l=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.backgroundColor=e),t==Q&&v||(K.buttons[t].backgroundColor=l);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"rollBackgroundColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.rollBackgroundColor:s},set:function(e){if(s=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.rollBackgroundColor=e),K.buttons[t].rollBackgroundColor=s,t!=Q&&K.buttons[t].rolled&&(K.buttons[t].backgroundColor=s);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"selectedBackgroundColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.selectedBackgroundColor:c},set:function(e){if(c=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.selectedBackgroundColor=e),t==Q&&v&&(K.buttons[t].backgroundColor=c);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"selectedRollBackgroundColor",{get:function(){return K.buttons[0].tabItems?K.buttons[0].tabItems.selectedRollBackgroundColor:u},set:function(e){if(u=e,K.buttons[0].tabInfo){for(var t=0;t<K.buttons.length;t++)K.buttons[t].tabInfo&&(K.buttons[t].tabInfo.selectedRollBackgroundColor=e),t==Q&&v&&K.buttons[t].rolled&&(K.buttons[t].backgroundColor=u);kt.OPTIMIZE||!zns&&OPTIMIZE||!K.stage||K.stage.update()}}}),Object.defineProperty(this,"label",{get:function(){return J[Q]},set:function(e){zon&&zog("selected is read only - try selectedIndex")}}),Object.defineProperty(this,"text",{get:function(){return null!=J[Q]?J[Q].text:void 0},set:function(e){zon&&zog("selected is read only - try selectedIndex")}}),Object.defineProperty(this,"buttons",{get:function(){return $},set:function(e){zon&&zog("buttons is read only")}}),Object.defineProperty(this,"labels",{get:function(){return J},set:function(e){zon&&zog("labels is read only")}}),this._enabled=!0,Object.defineProperty(K,"enabled",{get:function(){return K._enabled},set:function(e){Se(K,e)}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==K},set:function(e){kt.KEYFOCUS=K}}),b&&kt.KEYFOCUS&&ve(),this.on("mousedown",function(){b&&ve()}),K.width=i,!1!==N&&Oe(this,q),this.clone=function(){for(var e=kt.copy(o,!0),t=0;t<e.length;t++)e[t].label=e[t].label.clone();return K.cloneProps(new kt.Tabs(i,a,e,l,s,c,u,d,g,p,f,m,r,z,v,y,n,b,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H,V,N,this.group,G))}},kt.extend(kt.Tabs,kt.Container,"clone","zimContainer",!1),kt.Pad=function(e,r,t,o,n,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S){var E;if(E=zob(kt.Pad,arguments,"width, cols, rows, keys, backgroundColor, rollBackgroundColor, selectedBackgroundColor, selectedRollBackgroundColor, color, rollColor, selectedColor, selectedRollColor, spacing, currentEnabled, corner, labelColor, gradient, gloss, backing, rollBacking, wait, waitTime, waitBackgroundColor, rollWaitBackgroundColor, waitColor, rollWaitColor, waitModal, waitEnabled, style, group, inherit",this))return E;z_d("66"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Pad",this.group=I;var M=!1===B?{}:kt.getStyle(this.type,this.group,S);if(zot(e)&&(e=null!=M.width?M.width:150),zot(r)&&(r=null!=M.cols?M.cols:3),zot(t)&&(t=null!=M.rows?M.rows:r),zot(o))if(null!=M.keys)o=M.keys;else{o=[];for(var O=1;O<=t*r;O++)o.push(O)}zot(g)&&(g=null==M.currentEnabled||M.currentEnabled),zot(h)&&(h=null!=M.spacing?M.spacing:1);var j,D=this;this.cols=r,this.rows=t;var L,Y=e/r-h,X=[],R=0;this.labels=[],this.buttons=[];for(O=0;O<t;O++){for(var _=[],W=0;W<r;W++)_.push(null!=o[R]?o[R]:""),R++;var F=null!=M.corner?M.corner:p;F&&!Array.isArray(F)&&(F=[F,F,F,F]),L=X[O]=new kt.Tabs({width:e,height:Y,tabs:_,backgroundColor:null!=M.backgroundColor?M.backgroundColor:n,rollBackgroundColor:null!=M.rollBackgroundColor?M.rollBackgroundColor:i,selectedBackgroundColor:null!=M.selectedBackgroundColor?M.selectedBackgroundColor:a,color:null!=M.color?M.color:s,rollColor:null!=M.rollColor?M.rollColor:c,selectedColor:null!=M.selectedColor?M.selectedColor:u,spacing:null!=M.spacing?M.spacing:h,currentEnabled:null!=M.currentEnabled?M.currentEnabled:g,corner:F,backing:null!=M.backing?M.backing.clone():v,rollBacking:null!=M.rollBacking?M.rollBacking.clone():y,base:null,keyEnabled:!1,gradient:null!=M.gradient?M.gradient:m,gloss:null!=M.gloss?M.gloss:z,wait:null!=M.wait?M.wait:b,waitTime:null!=M.waitTime?M.waitTime:w,waitBackgroundColor:null!=M.waitBackgroundColor?M.waitBackgroundColor:x,rollWaitBackgroundColor:null!=M.rollWaitBackgroundColor?M.rollWaitBackgroundColor:C,waitColor:null!=M.waitColor?M.waitColor:k,rollWaitColor:null!=M.rollWaitColor?M.rollWaitColor:T,waitModal:null!=M.waitModal?M.waitModal:A,waitEnabled:null!=M.waitEnabled?M.waitEnabled:P,group:I,style:!1}),this.labels=this.labels.concat(L.labels),this.buttons=this.buttons.concat(L.buttons),this.addChild(L),L.selectedIndex=-1,L.y=(Y+h)*O,L.znum=O,L.on("change",H)}function H(e){var t=e.target;D.selected=t.selected,D.text=t.text,D.label=t.label;for(var o=t.selectedIndex,n=0;n<X.length;n++)X[n].selectedIndex=-1;t.selectedIndex=o,j=t.znum*r+o,D.dispatchEvent("change"),kt.OPTIMIZE||!zns&&OPTIMIZE||!D.stage||D.stage.update()}this.tabs=X,Object.defineProperty(this,"selectedIndex",{get:function(){return j},set:function(e){j=e;for(var t=0;t<X.length;t++)X[t].selectedIndex=-1;var o=Math.floor(j/r);0<=o&&o<D.tabs.length&&(D.tabs[o].selectedIndex=j%r)}}),this._enabled=!0,Object.defineProperty(D,"enabled",{get:function(){return D._enabled},set:function(e){Se(D,e)}}),!1!==B&&Oe(this,M),this.clone=function(){return D.cloneProps(new kt.Pad(e,r,t,o,n,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,this.group,S))}},kt.extend(kt.Pad,kt.Container,"clone","zimContainer",!1),kt.ColorPicker=function(e,o,n,r,i,t,a,l,s,c,u,d,h,g,p,f,m,z,v){var y;if(y=zob(kt.ColorPicker,arguments,"width, colors, cols, spacing, greyPicker, alphaPicker, startBackgroundColor, draggable, shadowColor, shadowBlur, buttonBar, circles, indicator, backgroundColor, keyArrows, container, style, group, inherit",this))return y;z_d("67"),this.zimContainer_constructor(null,null,null,null,!1),this.type="ColorPicker",this.group=z;var b=!1===m?{}:kt.getStyle(this.type,this.group,v);zot(e)&&(e=null!=b.width?b.width:500),zot(o)&&(o=null!=b.colors?b.colors:null),zot(o)&&(S=!0),zot(n)&&(n=null!=b.cols?b.cols:10),zot(r)&&(r=null!=b.spacing?b.spacing:2);var w=!S&&0<o.length&&o.length<=n;zot(t)&&(t=null!=b.alphaPicker?b.alphaPicker:!w),zot(i)&&(i=null!=b.greyPicker?b.greyPicker:!w),zot(s)&&(s=null!=b.shadowColor?b.shadowColor:"rgba(0,0,0,.3)"),zot(c)&&(c=null!=b.shadowBlur?b.shadowBlur:14),zot(u)&&(u=null!=b.buttonBar?b.buttonBar:!w),zot(l)&&(l=u?null==b.draggable||b.draggable:null!=b.draggable&&b.draggable),zot(d)&&(d=null!=b.circles&&b.circles),zot(h)&&(h=null!=b.indicator&&b.indicator,u||(h=null==b.indicator||b.indicator)),zot(g)&&(g=null!=b.backgroundColor?b.backgroundColor:"black"),zot(p)&&(p=null==b.keyArrows||b.keyArrows);var x=this;if(zot(f)){if(!zimDefaultFrame)return;f=zimDefaultFrame.stage}else{if(!f.getBounds)return;if(zot(f.getStage))return}x.container=f;var C="#e472c4",k="#50c4b7",T=1,A=1,P=new createjs.Shape;this.addChild(P),P.x+=r,P.y+=r;var B,I,S=!1,E=[];if(zot(o)){S=!0;var M=6,O=M*M*M;M=Math.ceil(Math.pow(O,.5)),I=(e-r)/18-r;var j=Math.floor(Math.pow(M*M,1/3));B=[];for(var D=0;D<6;D++)for(var L=0;L<6;L++)for(var Y=0;Y<6;Y++)B.push("#"+W(3*D)+W(3*L)+W(3*Y));for(o=[],D=0;D<B.length;D++)H=Math.floor(D/6),o[18*((F=D%6)+6*(j=18<=H?1:0))+(H-6*j*3)]=B[D];n=18,E=[k,C]}else I=(e-r)/n-r;var X,R=Math.ceil(o.length/n),_=String(o[o.length-1]);function W(e){return(e=Math.floor(e).toString(16))+""+e}zot(a)||(_=String(a)),S&&(X=k);var F,H,V,N,G=P.graphics,q=(j=0,null!=b.borderColor?b.borderColor:null),U=null!=b.borderWidth?b.borderWidth:null;for(!zot(q)&&zot(U)&&(U=1),U&&zot(q)&&(q="#333"),U&&G.s(q).ss(U),D=0;D<o.length;D++)H=D%n,F=Math.floor(D/n),V=H*(I+r),N=F*(I+r),d?G.f(o[D]).dc(V+I/2,N+I/2,I/2):G.f(o[D]).r(V,N,I,I);var K=N+I+r;x.colors=o;var Z=K;if(i){for(D=0;D<16;D++)E.push("#"+W(D)+W(D)+W(D));for(D=0;D<E.length;D++)H=Math.floor(D/n),V=(F=D%n)*(I+r),N=H*(I+r)+K,d?G.f(E[D]).dc(V+I/2,N+I/2,I/2):G.f(E[D]).r(V,N,I,I);K=N+I+r;var Q=n,J=Math.ceil(E.length/n)}if(x.greys=E,h){function $(e){zot(e)||e<0?h.visible=!1:(h.visible=!0,h.alpha="#000"==_||"#000000"==_||"black"==_?(h.color="#222",1):(h.color="black",.5),h.x=P.x+e%n*(I+r)+I/2,h.y=P.x+Math.floor(e/n)*(I+r)+I/2)}(h=this.indicator=d?new kt.Circle(I/2*.5,null,null,null,null,null,!1):new kt.Rectangle(.5*I,.5*I,null,null,null,null,null,!1)).alpha=.5,h.centerReg(),this.addChild(h),$(o.indexOf(_))}if(t){var ee=new kt.Container({style:!1});ee.setBounds(0,0,600,70),this.addChild(ee),ee.x=0,ee.y=K;var te=this.alphaBacking=new kt.Rectangle(580,50,"#222",null,null,0,null,!1);ee.addChild(te),kt.centerReg(te,ee);var oe=this.alphaBut=new kt.Button({width:20,height:30,backgroundColor:"darkorange",rollBackgroundColor:"orange",label:"",corner:0,hitPadding:20,style:!1}),ne=this.alphaSlider=new kt.Slider({min:0,max:1,step:.05,button:oe,barLength:330,barWidth:2,barColor:"#999",vertical:!1,useTicks:!1,inside:!1,style:!1});ne.currentValue=1,ee.addChild(ne),ne.x=40,ne.y=ee.height/2;var re=this.alphaText=new kt.Label({text:"Alpha: 1",size:30,color:"orange",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",backgroundColor:"ignore",rollColor:"orange",group:this.group});ee.addChild(re),re.x=ne.x+ne.bar.width+40,re.y=ee.height/2-re.height/2,ee.scaleX=ee.scaleY=e/600,ne.on("change",function(){re.text="Alpha: "+ke(ne.currentValue),de&&(de.alpha=A=ne.currentValue),u?x.dispatchEvent("set"):x.dispatchEvent("change"),x.stage&&x.stage.update()}),K+=ee.height-10}if(u){var ie=new kt.Container({style:!1});ie.setBounds(0,0,600,100),this.addChild(ie),ie.x=0,ie.y=K+10;var ae=this.swatchText=new kt.Label({align:"center",text:_.toUpperCase().substr(0,7),size:30,color:"orange",rollColor:"orange",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",backgroundColor:"ignore",group:this.group});if(ie.addChild(ae),kt.centerReg(ae),ae.x=90,ae.y=48,l){var le=this.grip=new kt.Shape({style:!1});ie.addChild(le),le.graphics.f("rgba(256,256,256,.25)").r(0,0,5,20).r(10,0,5,20).r(20,0,5,20).r(30,0,5,20),le.x=70,le.y=65,ae.y=40,le.mouseEnabled=!1}var se=this.closeBut=new kt.Button({width:90,height:90,label:"X",backgroundColor:"#222",rollBackgroundColor:"#444",corner:0,style:!1});ie.addChild(se),se.x=600-se.width-10,se.y=0,se.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){x.dispatchEvent("close")});var ce=this.okBut=new kt.Button({width:150,height:90,label:"OK",backgroundColor:"#222",rollBackgroundColor:"#444",corner:0,style:!1});ie.addChild(ce),ce.x=se.x-ce.width-10,ce.y=0,ce.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",me);var ue=this.swatchBacking=new kt.Shape({style:!1});ie.addChild(ue),(G=ue.graphics).f("black").r(.5,.5,50,89).f("#666").r(50,.5,50,89).f("white").r(100,.5,49.5,89),ue.x=ce.x-150-10,ue.y=0;var de=this.swatch=new kt.Rectangle(150,90,_,null,null,null,null,!1);ie.addChild(de),de.x=ue.x,de.y=0,de.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",me),de.cursor="pointer",ie.scaleX=ie.scaleY=e/600,K+=ie.height}else P.cursor="pointer";t||u||(K-=10-r);var he=K+10;this.setBounds(0,0,e,he);var ge,pe,fe=this.background=new kt.Rectangle(e,he,g,null,null,null,null,!1);function me(){if(_!=X||A!=T){if(S&&i){var e=[k=C,C=X];for(D=0;D<2;D++){var t=P.graphics;H=Math.floor(D/n),V=(F=D%n)*(I+r),N=H*(I+r)+Z,E[D]=e[D],t.f(fe.color).r(V-1,N-1,I+2,I+2).f(e[D]).r(V,N,I,I)}kt.OPTIMIZE||!zns&&OPTIMIZE||!x.stage||x.stage.update()}X=_,T=A,x.dispatchEvent("change")}else x.dispatchEvent("close")}(this.addChildAt(fe,0),-1!=s&&0<c&&(fe.shadow=new createjs.Shadow(s,8,8,c)),l)&&(fe.on("mousedown",function(e){ge=e.stageX-x.x,pe=e.stageY-x.y,fe.cursor="move"}),fe.on("pressmove",function(e){x.x=e.stageX-ge,x.y=e.stageY-pe,x.stage&&x.stage.update()}),fe.on("pressup",function(e){fe.cursor="default",x.stage&&x.stage.update()}));var ze,ve=n*(I+r),ye=R*(I+r);if(i)var be=Q*(I+r),we=J*(I+r);function xe(){x.keyFocus=!0;var e=document.activeElement;e&&e.blur()}function Ce(){x.zimAccessibility&&x.zimAccessibility.changeTitle(x,null,!0)}function ke(e){return Math.round(e*Math.pow(10,2))/Math.pow(10,2)}P.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(e){var t=kt.hitTestGrid(P,ve,ye,n,R,e.stageX,e.stageY,0,0,r,r);zot(t)||(_=o[t],u?(de.color=_,ae.text=String(o[t]).toUpperCase().substr(0,7),_!=X&&x.dispatchEvent("set")):me()),i&&(t=null,zot(t=kt.hitTestGrid(P,be,we,Q,J,e.stageX,e.stageY,0,ye,r,r))||(_=E[t],u?(de.color=_,ae.text=E[t].toUpperCase(),_!=X&&x.dispatchEvent("set")):me())),h&&$(o.indexOf(_)),u?x.stage&&x.stage.update():h&&x.stage&&x.stage.update(),Ce()}),Object.defineProperty(this,"selectedColor",{get:function(){return _},set:function(e){X=_=e,u&&(de.color=_,ae.text=_,x.stage&&x.stage.update()),h&&$(o.indexOf(_)),Ce()}}),Object.defineProperty(this,"currentValue",{get:function(){return _},set:function(e){x.selectedColor=e}}),Object.defineProperty(this,"currentValueEvent",{get:function(){return _},set:function(e){e!=x.selectedColor&&(x.selectedColor=e,x.dispatchEvent("change"))}}),Object.defineProperty(this,"selectedIndex",{get:function(){return o.indexOf(_)},set:function(e){X=_=o[e],u&&(de.color=_,ae.text=_,x.stage&&x.stage.update()),h&&$(o.indexOf(_)),Ce()}}),Object.defineProperty(this,"selectedAlpha",{get:function(){return t?ke(ne.currentValue):1},set:function(e){t&&(T=ne.currentValue=e,de&&(de.alpha=T),re&&(re.text="Alpha: "+ke(ne.currentValue)),x.stage&&x.stage.update())}}),Object.defineProperty(this,"colors",{get:function(){return i?o.concat(E):o},set:function(e){zon&&zog("Display - ColorPicker() colors is read only - make a new ColorPicker to change")}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==x},set:function(e){zns?kt.KEYFOCUS=x:KEYFOCUS=x}}),p&&kt.KEYFOCUS&&xe(),this.on("mousedown",function(){p&&xe()}),this.keyDownEvent=function(e){if(x.stage&&(x.zimAccessibility&&x.focus||!x.zimAccessibility&&x.keyFocus)){var t=x.selectedIndex;function o(){t<0&&(t=x.colors.length-1),t>x.colors.length-1&&(t=0),x.selectedIndex=t,x.dispatchEvent("change"),x.stage&&x.stage.update()}37==e.keyCode||40==e.keyCode?(t--,o()):38!=e.keyCode&&39!=e.keyCode||(t++,o())}},window.addEventListener("keydown",this.keyDownEvent),this.hide=function(){if(x.removeFrom(),x.toggled=!1,x.zimAccessibility){var e=x.zimAccessibility;e.resize(x),ze?ze.focus():x.zimTabTag.nextSibling.focus(),setTimeout(function(){e.talk("ColorPicker has been closed.")},50)}return x},this.show=function(){if(x.center(x.container),x.zimAccessibility){var e=x.zimAccessibility;setTimeout(function(){e.activatedObject&&(ze=e.activatedObject.zimTabTag)},50),e.resize(x),e.tabIndex=x.zimTabIndex}return x.toggled=!0,x},!(this.toggle=function(e){return!0===e?x.show():!1===e?x.hide():x.container.contains(x)?x.hide():x.show(),x})!==m&&Oe(this,b),this.clone=function(){return x.cloneProps(new kt.ColorPicker(e,S?null:o,n,r,i,t,a,l,s,c,u,d,h,g,p,f,m,this.group,v))},this.dispose=function(){return window.removeEventListener("keydown",x.keyDownEvent),ne&&ne.dispose(),this.zimContainer_dispose(),!0}},kt.extend(kt.ColorPicker,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Keyboard=function(n,f,m,r,i,a,l,t,z,v,y,o,b,s,c,u,d,h,g,p,w,x,C,e,k){var T;if(T=zob(kt.Keyboard,arguments,"labels, backgroundColor, color, shiftBackgroundColor, shiftHoldBackgroundColor, placeBackgroundColor, placeColor, cursorColor, shadeAlpha, borderColor, borderWidth, margin, corner, draggable, placeClose, shadowColor, shadowBlur, container, data, place, special, rtl, style, group, inherit",this))return T;z_d("67.2"),this.zimContainer_constructor(1e3,400,null,null,!1),this.type="Keyboard",this.group=e;var A=!1===C?{}:kt.getStyle(this.type,this.group,k);zot(n)&&(n=null!=A.labels?A.labels:[]),Array.isArray(n)||(n=[n]),zot(f)&&(f=null!=A.backgroundColor?A.backgroundColor:"#333"),zot(m)&&(m=null!=A.color?A.color:"white"),zot(r)&&(r=null!=A.shiftBackgroundColor?A.shiftBackgroundColor:"orange"),zot(i)&&(i=null!=A.shiftHoldBackgroundColor?A.shiftHoldBackgroundColor:"red"),zot(a)&&(a=null!=A.placeBackgroundColor?A.placeBackgroundColor:"#50c4b7"),zot(l)&&(l=null!=A.placeColor?A.placeColor:m),zot(t)&&(t=null!=A.cursorColor?A.cursorColor:"#50c4b7"),zot(z)&&(z=null!=A.shadeAlpha?A.shadeAlpha:.2),zot(v)&&(v=null!=A.borderColor?A.borderColor:"rgba(0,0,0,.1)"),zot(y)&&(y=null!=A.borderWidth?A.borderWidth:null),v<0||y<0?v=y=null:null!=v&&null==y&&(y=1),zot(o)&&(o=null!=A.margin?A.margin:5),zot(b)&&(b=null!=A.corner?A.corner:30),zot(s)&&(s=null!=A.draggable&&A.draggable),zot(c)&&(c=null==A.placeClose||A.placeClose),zot(u)&&(u=null!=A.shadowColor?A.shadowColor:"rgba(0,0,0,.2)"),zot(d)&&(d=null!=A.shadowBlur?A.shadowBlur:14),zot(g)&&(g=null!=A.data?A.data:[[["q","w","e","r","t","y","u","i","o","p"],["a","s","d","f","g","h","j","k","l"],["shift","z","x","c","v","b","n","m","backspace"],["?123"]],[["1","2","3","4","5","6","7","8","9","0"],["!","@","#","$","/","^","&","*","(",")"],["1/2","-","'",'"',":",";",",","?","backspace"],["ABC"]],[["+","x","%","=","<",">","{","}","[","]"],["€","£","Â¥","$","₩","~","`","¤","♡","☆"],["2/2","_","\\","|","《","》","¡","¿","backspace"],["ABC"]]]);var P=this;P.data=g,zot(p)&&(p=null==A.place||A.place),zot(x)&&(x=null!=A.rtl&&A.rtl);var B="zim display - Keyboard(): Please pass in a reference to a container with bounds set";if(zot(h)){if(!zimDefaultFrame)return void zog(B);h=zimDefaultFrame.stage}else{if(!h.getBounds)return void zog(B);if(zot(h.stage))return void zog("zim display - Keyboard(): The container must have a stage property")}-1!=u&&0<d&&(P.shadow=new createjs.Shadow(u,3,3,d));var I,S=zimDefaultFrame?zimDefaultFrame.stage:null;P.labels=n;var E=["@","",".","/","away"];zot(w)||E.splice(1,0,w);var M=kt.copy(g[0]);M[3]=M[3].concat(E);var O=kt.copy(g[1]);O[3]=O[3].concat(E);var j=kt.copy(g[2]);j[3]=j[3].concat(E);var D,L,Y,X,R,_,W,F,H,V,N,G,q=["Ä—","Ä“","Ä™","ê","é","ë","è"],U=["Å«","û","ú","ü","ù"],K=["Ä«","į","ì","Ã","ï","î"],Z=["Å","Å“","ø","õ","ô","ó","ö","ò"],Q=["Ä","ã","Ã¥","â","á","ä","à ","æ"],J=["ñ","Å„"],$=[],ee=95.5,te={def:"default",shift:"shift",number1:"number1",number2:"number2"},oe=te.def,ne=!1,re=0,ie=[];function ae(e){var t,o=!1;if(oe===te.def){for(X.color=e?i:r,t=0;t<$.length-6-(zot(w)?0:1);t++){0<(n=$[t]).label.text.length&&(1===n.name.length?(n.label.text=n.label.text.toUpperCase(),n.label.centerReg(n).mov(0,6)):n.label.centerReg(n))}e||(o=!0,kt.timeout(500,function(){o&&(ne=!0,X.color=i,D.updateCache(),P.stage.update())}),G=P.on("pressup",function(e){P.off("pressup",G),o=!1})),oe=te.shift}else{for(X.color=f,ne=!1,t=0;t<$.length-6;t++){var n;0<(n=$[t]).label.text.length&&(1===n.name.length?(n.label.text=n.label.text.toLowerCase(),n.label.centerReg(n).mov(0,3)):n.label.centerReg(n))}oe=te.def}D.updateCache(),P.stage.update()}function le(e){var t,o,n,r,i,a,l,s=0,c=0,u=!1,d=!1;zot(e)&&(e=te.def),e===te.def?t=M:e===te.number1?t=O:e===te.number2&&(t=j),D=new kt.Container(1e3,430,null,null,!1).addTo(P);for(var h=0;h<t.length;h++){(h<=1||e==te.def&&2==h&&"shift"!=t[2][0])&&(s=(ee/2+2.5)*(10-t[h].length));for(var g=0;g<t[h].length;g++){if(a=null,d=u=!1,"backspace"==t[h][g]?(a=F,d=i=!0):"shift"==t[h][g]?(i=!0,a=W):(3==h||e!=te.def&&2==h)&&0==g?d=i=!0:""==t[h][g]?u=!(i=!1):"away"==t[h][g]?(a=H,d=i=!0):i=!1,r=i?1.5*ee+2.5:u?(ee+5)*(zot(w)?4:3)-5:ee,n=new kt.Rectangle(r,ee,f,v,y,b,null,!1).cur().addTo(D),d&&n.addChild(new kt.Rectangle(r,ee,"black",null,null,b,null,!1).alp(z)),n.label=o=a?new kt.Label({text:"",backgroundColor:"ignore",font:null!=A.font?A.font:null,style:!1}):new kt.Label({lineWidth:10,lineHeight:25,font:null!=A.font?A.font:null,text:t[h][g],color:m,align:"center",style:!1}),a){var p=a.clone();p.scaleTo(n,70,70),p.centerReg(n)}l?(l=!1,s+=67.33):(o.centerReg(n).mov(0,isNaN(o.text)?3:7),n.x=s,n.y=c,n.name=t[h][g],2==h&&0==g&&e==te.number1&&(n.toggle="1/2"),2==h&&0==g&&e==te.number2&&(n.toggle="2/2"),3==h&&0==g&&e==te.def&&(n.toggle="?123"),3==h&&0==g&&e!=te.def&&(n.toggle="ABC"),n.toggle&&o.mov(0,3),$.push(n),"shift"==n.name&&(X=n),s=n.x+n.width+5)}c+=ee+5,s=0}D.cache(y?-y:0,y?-y:0,y?D.width+2*y:D.width,y?D.height+2*y:D.height)}function se(){P.mouseYAmount&&(P.y=P.parent.globalToLocal(0,P.mouseYAmount-N).y)}function ce(){S.off("pressmousemove",P.tickerMouseEvent),kt.Ticker.remove(se)}function ue(){if(R&&Y){for(var e=R.label.x+R.label.getBounds().x,t=0;t<re;t++)e+=R.widthArray[t];Y.heightOnly=R.getBounds().height*(R.backing&&zot(R.padding)?.9:1)-(R.paddingVertical&&R.background?2*R.paddingVertical:0),Y.center(R),Y.x=e}}function de(){if(_)return P;if(!R)return P;var e,t,o,n=c?["<",">","x"]:["<",">"];ie=[],o=R.localToLocal(0,0,P),_=new kt.Container({style:!1}).addTo(P).pos({x:o.x,y:o.y+R.height+15,reg:!0}).cur();for(var r=0;r<n.length;r++)e=new kt.Rectangle(ee,ee,a,v,y,b,null,!1),"x"==n[r]&&new kt.Rectangle(ee,ee,"black",null,null,b,null,!1).alp(z).addTo(e),(t=new kt.Label({lineWidth:10,lineHeight:25,text:n[r],backing:e,font:null!=A.font?A.font:null,color:l,align:"center",valign:"center",style:!1}).addTo(_).cache()).x=r*(ee+5),ie.push(t);o=R.localToLocal(0,0,P),_.x=o.x,_.y=o.y+R.height+15,_.on("click",function(e){0==ie.indexOf(e.target)?0<re&&re--:1==ie.indexOf(e.target)?re<R.text.length&&re++:he();ue()}),P.stage.update()}function he(){if(!_)return P;_.removeAllEventListeners(),P.removeChild(_),_=null}function ge(e){if(R){var t,o;if("del"===e)R&&(R.text=[R.text.slice(0,re-1),R.text.slice(re)].join("")),re--,fe();else{oe===te.shift&&(e=e.toUpperCase());var n=R.text;(t=R.clone().removeFrom()).text=e,o=t.label.getMeasuredWidth(),R.widthArray?R.widthArray.splice(re,0,o):R.widthArray=[R.breedte],re<R.text.length?R.text=[R.text.slice(0,re),e,R.text.slice(re)].join(""):R.text+=e,R&&R.label.getBounds().width<I?(re++,ue()):R.text=n}oe!==te.shift||ne||(P.removeChild(D),le(),oe=te.def),ue();var r=new createjs.Event("keydown");r.letter=e,P.dispatchEvent(r),P.stage.update()}}function pe(e){if(P.stage){var t,o=0,n=!1;(R=e.target).widthArrayCheck||fe(),I=R.label.lineWidth?R.label.lineWidth:1e4,t=R.label.globalToLocal(e.stageX,e.stageY);for(var r=0;r<R.widthArray.length;r++)if(o+=R.widthArray[r],t.x<o-R.widthArray[r]/2+R.label.getBounds().x){re=r,n=!0;break}n||(re=R.text.length),ue(),p&&!_&&0<R.text.length&&de(),_&&R&&(0<R.text.length?(t=R.localToLocal(0,0,P),_.x=t.x,_.y=t.y+R.height+15):he())}}function fe(){if(R){var e;R.widthArray=[];for(var t=0;t<R.text.length;t++)(e=R.clone().removeFrom()).text=R.text[t],R.widthArray.push(e.label.getMeasuredWidth());R.widthArrayCheck=!0,ue()}}function me(){for(var e=0;e<n.length;e++)n[e].clickEvent=n[e].on("click",pe)}function ze(){if(1<n.length)for(var e=0;e<n.length;e++)n[e].off("click",n[e].clickEvent)}function ve(){if(!Y&&(R=n[0],I=R&&R.label.lineWidth?R.label.lineWidth:1e4,R)){(Y=new kt.Rectangle(3,R.height-(R.paddingVertical&&R.background?2*R.paddingVertical:0),t,null,null,null,null,!1).center(R)).x=0,Y.visible=!1,Y.animate({obj:{alpha:0},rewind:!0,loop:!0,loopWait:750,time:250,id:"knipperTekst"});for(var e=0;e<n.length;e++)n[e].widthArray=[0];fe()}}function ye(){kt.stopAnimate("knipperTekst"),R&&R.removeChild(Y),R=Y=null}!function(){(W=new kt.Shape({style:!1})).graphics.f(m).p("AhIFoIAAjYIixAAID5n3ID6H3IixAAIAADYgAjHBxICeAAIAADYIBTAAIAAjYICeAAIjImSg"),W.setBounds(-25.5,-36,51,72),F=new kt.Container({style:!1});var e=new kt.Shape({style:!1});e.graphics.f(m).p("ACgC+IigigIifCgQgGAGgJAAQgJAAgGgGQgGgGgBgJQABgJAGgGICgigIigifQgGgGgBgJQABgJAGgGQAGgGAJAAQAIAAAHAGICfCgICgigQAGgGAJAAQAJAAAGAGQAGAGABAJQgBAJgGAGIigCfICgCgQAGAGABAJQgBAJgGAGQgGAGgJAAQgJAAgGgGg"),e.setTransform(82.6,32),e.addTo(F);var t=new kt.Shape({style:!1});t.graphics.f(m).s().p("AkhFAQgcAAgUgUIkHj6QgVgUAAgeQAAgdAVgVIEHj6QAUgTAcAAINKAAQAdAAAUAUQAUAUAAAdIAAH1QAAAdgUATQgUAVgdAAgAk0kOIkGD8QgIAHAAALQAAALAIAIIEGD7QAIAHALAAINKAAQALAAAIgIQAHgHAAgLIAAn1QAAgLgHgIQgIgIgLAAItKAAQgLAAgIAHg"),t.setTransform(62.2,32),t.addTo(F),F.setBounds(0,0,125,64),(H=new kt.Container({style:!1})).setBounds(0,0,147,86);for(var o,n=[{p:"Ai+heIF9AAIi/C9g",transform:[73.4,76]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[128.4,43.2]},{p:"AnNAzIAAhlIObAAIAABlg",transform:[73,43.2]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[18.8,43.2]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[128.2,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[114.5,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[100.8,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[87.1,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[73.4,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[59.7,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[46,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[32.3,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[18.6,29.5]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[128,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[114.3,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[100.6,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[86.9,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[73.2,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[59.5,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[45.8,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[32.1,15.8]},{p:"AgyAzIAAhlIBlAAIAABlg",transform:[18.4,15.8]},{p:"AphEnQgzAAgkgkQglglAAgzIAAlVQAAgzAlglQAkgkAzAAITDAAQAzAAAkAkQAlAlAAAzIAAFVQAAAzglAlQgkAkgzAAgAqjjtQgcAcAAAnIAAFVQAAAnAcAbQAbAcAnAAITDAAQAnAAAcgcQAbgbAAgnIAAlVQAAgngbgcQgcgcgnAAIzDAAQgnAAgbAcg",transform:[73.4,29.5]}],r=0;r<n.length;r++)(o=new kt.Shape({style:!1})).graphics.f(m).s().p(n[r].p),o.setTransform(n[r].transform[0],n[r].transform[1]),o.addTo(H)}(),le(oe),s&&function(){V=new kt.Rectangle(1.5*ee+2.5+2.5,ee,f,v,y,b,null,!1).addTo(P,0).cur();for(var e=0;e<4;e++)new kt.Rectangle(.4*V.width,4,m,null,null,null,null,!1).centerReg(V).alp(.2).y-=15*e-22;V.x=8.5*ee+40,V.y=-ee-5,V.name="drag"}(),this.on("mousedown",function(e){S=P.stage,L&&P.removeChild(L);_&&ie.indexOf(e.target)<0&&he();zot(e.target.name)||(s&&e.target===V?(P.tickerMouseEvent=S.on("stagemousemove",function(e){P.mouseYAmount=e.stageY}),kt.Ticker.add(se),P.on("pressup",ce),N=e.stageY-P.localToGlobal(0,0).y):zot(w)||e.target.name!==w?"shift"===e.target.name?ae():"?123"===e.target.toggle?(P.removeChild(D),le(te.number1)):"ABC"===e.target.toggle?(P.removeChild(D),oe=te.def,le(),ne&&ae(!0)):"1/2"===e.target.toggle?(P.removeChild(D),le(te.number2)):"2/2"===e.target.toggle?(P.removeChild(D),le(te.number1)):"away"===e.target.name?(P.hide(),P.dispatchEvent("close")):"e"===e.target.name||"u"===e.target.name||"i"===e.target.name||"o"===e.target.name||"a"===e.target.name||"n"===e.target.name?function(t){var a,l,s=!1,c=!1;switch(t){case"e":a=q;break;case"u":a=U;break;case"i":a=K;break;case"o":a=Z;break;case"a":a=Q;break;case"n":a=J}l=kt.timeout(500,function(){var e,t,o,n,r=0;if(l.clear(),!s){c=!0,(L=new kt.Container(1e3,ee,null,null,!1).addTo(P,0)).y=-ee-5;for(var i=0;i<a.length;i++)n=oe===te.shift?a[i].toUpperCase():a[i],e=new kt.Label({lineWidth:10,lineHeight:25,text:n,font:null!=A.font?A.font:null,color:m,align:"center",style:!1}),t=new kt.Rectangle(ee,ee,f,v,y,b,null,!1).addTo(L),o=new kt.Rectangle(ee,ee,"white",null,null,b,null,!1).alp(.2),t.addChild(o),e.center(t),t.name=a[i],t.x=r,r+=ee+5;P.stage.update()}});var o=P.on("pressup",function(e){s=!0,P.off("pressup",o),c||ge(t)})}(e.target.name):"return"===e.target.name?ge("\n"):"backspace"===e.target.name?function(){var t,o=!0;function n(){R&&0<R.text.length?(0<P.selectedIndex&&ge("del"),P.on("pressup",r)):ge("del")}function r(){o=!1,t.clear(),P.off("pressup",r)}n(),t=kt.timeout(300,function e(){(!R||R.text.length<1||0==P.currentIndex)&&(o=!1);o&&(n(),t=kt.timeout(200,e));R&&R.text.length<1&&r()}),P.stage.update()}():""===e.target.name?ge(" "):ge(e.target.name):P.dispatchEvent("special"),S.update())}),me(),ve(),Object.defineProperty(this,"selectedLabel",{get:function(){return R},set:function(e){pe({target:e}),P.hidePlace()}}),Object.defineProperty(this,"selectedIndex",{get:function(){return re},set:function(e){re=e,ue()}}),this.show=function(e){(P.addTo(h),zot(e))||pe({target:n[e]});return Y&&(Y.visible=!0),P.toggled=!0,P},this.hide=function(){return P.removeFrom(h),Y&&(Y.visible=!1),S.update(),P.toggled=!1,P},this.toggle=function(e){return!0===e?P.show():!1===e?P.hide():P.parent?P.hide():P.show(),P},this.showPlace=function(){return de(),P},this.hidePlace=function(){return he(),P},this.addLabels=function(e){Array.isArray(e)||(e=[e]);for(var t=e.length-1;0<=t;t--){0<=n.indexOf(e[t])||"Label"!=e[t].type?e.splice(t,1):e[t].widthArray=[0]}return ze(),n=n.concat(e),me(),ve(),Y&&(Y.visible=!0),P},this.removeLabels=function(e){Array.isArray(e)||(e=[e]),ze();for(var t=0;t<e.length;t++){var o=n.indexOf(e[t]);0<=o&&n.splice(o,1)}return me(),0==n.length?R&&ye():R&&-1==n.indexOf(R)&&(ye(),ve()),P};var be=new kt.Rectangle(this.width,this.height,kt.clear,null,null,null,null,!1).addTo(this).expand().bot();be.on("mousedown",function(){}),be.on("click",function(){}),this.resize=function(){return P.scaleTo(S,100-2*o/S.width*100,50-2*o/S.height*100),P.y=S.height-P.height-o,P.x=S.width/2-P.width/2,R&&_&&(point=R.localToLocal(0,0,P),_.x=point.x,_.y=point.y+R.height+15),P.stage&&P.stage.update(),P},this.resize(),P.selectedLabel&&(P.selectedIndex=P.selectedLabel.text.length),!1!==C&&Oe(this,A),this.clone=function(){var e=new kt.Keyboard(n,f,m,r,i,a,t,z,o,b,s,c,u,d,h,g,p,w,x,C,this.group,k);return P.cloneProps(e)}},kt.extend(kt.Keyboard,kt.Container,"clone","zimContainer",!1),kt.Organizer=function(e,t,r,o,i,a,l,s,n,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A){var P;if(P=zob(kt.Organizer,arguments,"width, list, useAdd, useRemove, usePosition, autoAdd, autoRemove, autoPosition, addForward, removeForward, backgroundColor, rollBackgroundColor, selectedBackgroundColor, selectedRollBackgroundColor, color, rollColor, selectedColor, selectedRollColor, spacing, corner, keyEnabled, gradient, gloss, backdropColor, style, group, inherit",this))return P;z_d("67.3"),this.group=T;var B=!1===k?{}:kt.getStyle("Organizer",this.group,A);zot(e)&&(e=null!=B.width?B.width:t&&t.vertical?t.width:300),zot(r)&&(r=null==B.useAdd||B.useAdd),zot(o)&&(o=null==B.useRemove||B.useRemove),zot(i)&&(i=null==B.usePosition||B.usePosition),zot(a)&&(a=null!=B.autoAdd?B.autoAdd:r),zot(l)&&(l=null!=B.autoRemove?B.autoRemove:o),zot(s)&&(s=null!=B.autoPosition?B.autoPosition:i),zot(n)&&(n=null==B.addForward||B.addForward),zot(c)&&(c=null==B.removeForward||B.removeForward),zot(u)&&(u=null!=B.backgroundColor?B.backgroundColor:"#777"),zot(d)&&(d=null!=B.rollBackgroundColor?B.rollBackgroundColor:"#555"),zot(h)&&(h=null!=B.selectedBackgroundColor?B.selectedBackgroundColor:"#333"),zot(p)&&(p=null!=B.color?B.color:"white"),zot(f)&&(f=null!=B.rollColor?B.rollColor:p),zot(m)&&(m=null!=B.selectedColor?B.selectedColor:p),zot(v)&&(v=null!=B.spacing?B.spacing:1),zot(y)&&(y=null!=B.corner?B.corner:0),zot(w)&&(w=null!=B.gradient?B.gradient:.2),zot(x)&&(x=null!=B.gloss?B.gloss:null),zot(C)&&(C=null!=B.backdropColor?B.backdropColor:null),Array.isArray(y)||(y=[y,y,y,y]);var I={width:50,height:50,label:"",shadowColor:-1,gradient:w,corner:y,backgroundColor:u,rollBackgroundColor:d},S=this.buttons=[],E=new kt.Shape;if(E.graphics.f(p).p("AAAA4Ih6B8Ig5g4IB8h8Ih7h6IA4g5IB6B8IB7h8IA5A5Ih8B6IB8B7Ig5A5g"),r&&S.push(new kt.Button({icon:E.sca(.55).rot(-45).reg(1),inherit:I})),i){var M=new kt.Shape;M.graphics.f(p).p("AiJieIETCeIkTCfg"),S.push(new kt.Button({icon:M.sca(.6).rot(t&&!t.vertical?180:-90).reg(-2),inherit:I})),S.push(new kt.Button({icon:M.clone().sca(.6).rot(t&&!t.vertical?0:90).reg(-2),inherit:I}));var O=new kt.Shape;O.graphics.f(p).p("AiFCLIAAkVIBXAAIAAEVgAgiAAICoiHIAAEQg"),S.push(new kt.Button({icon:O.sca(.62).rot(t&&!t.vertical?0:90).reg(0),inherit:I})),S.push(new kt.Button({icon:O.clone().sca(.62).rot(t&&!t.vertical?180:-90).reg(0),inherit:I}))}o&&S.push(new kt.Button({icon:E.clone().rot(0).sca(.55),inherit:I})),0==S.length&&(S=[""]),this.zimTabs_constructor(e,e/S.length,S,u,d,h,g,p,f,m,z,!1,v,!0,!1,y,null,!0,w,x,null,null,null,null,null,null,null,null,null,null,C);var j=this;j.list=t,j.type="Organizer";var D=!(j.setButtons=function(){i&&(j.buttons[1].icon.rotation=j.list&&!j.list.vertical?180:-90,j.buttons[2].icon.rotation=j.list&&!j.list.vertical?0:90,j.buttons[3].icon.rotation=j.list&&!j.list.vertical?0:90,j.buttons[4].icon.rotation=j.list&&!j.list.vertical?180:-90)}),L=t;j.change(function(e){(!D&&j.list||j.list&&j.list!=L)&&(j.list!=L&&L&&L.noChange(),j.list.change(function(e){j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex}),D=!0,L=j.list);var t=e.target.selectedIndex;r||t++,i||r&&!(0<t)||(t=5);var o=zot(j.list.selectedIndex)||j.list.selectedIndex<0;switch(o&&(j.currentValue=null),j.lastIndex=j.list.selectedIndex,t){case 0:if(a){var n=Math.max(0,j.list.selectedIndex);j.add(n)}j.orgType="add";break;case 1:if(o)break;if(s){n=j.list.selectedIndex;j.up(n)}j.orgType="up";break;case 2:if(o)break;if(s){n=j.list.selectedIndex;j.down(n)}j.orgType="down";break;case 3:if(o)break;if(s){n=j.list.selectedIndex;j.toTop(n)}j.orgType="top";break;case 4:if(o)break;if(s){n=j.list.selectedIndex;j.toBottom(n)}j.orgType="bottom";break;case 5:if(o)break;if(l){n=j.list.selectedIndex;j.remove(n)}j.orgType="remove"}}),this.add=function(e,t,o){if(zot(e)&&(e=j.lastIndex),zot(t)&&(t=""),n)e=Math.min(j.list.length,Math.max(0,j.list.selectedIndex)+1);else e=Math.max(0,j.list.selectedIndex);j.list.addAt(t,e,o),j.list.selectedIndexPlusPosition=e,j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex},this.up=function(e){zot(e)&&(e=j.lastIndex);var t=j.list.items[e];zot(t)||(j.list.removeAt(1,e),j.list.addAt(t,e-1),j.list.selectedIndexPlusPosition=Math.max(0,e-1),j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex)},this.down=function(e){zot(e)&&(e=j.lastIndex);var t=j.list.items[e];zot(t)||(j.list.removeAt(1,e),j.list.addAt(t,e+1),j.list.selectedIndexPlusPosition=Math.min(j.list.length-1,e+1),j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex)},this.toTop=function(e){zot(e)&&(e=j.lastIndex);var t=j.list.items[e];zot(t)||(j.list.removeAt(1,e),j.list.addAt(t,0),j.list.first(),j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex)},this.toBottom=function(e){zot(e)&&(e=j.lastIndex);var t=j.list.items[e];zot(t)||(j.list.removeAt(1,e),j.list.addAt(t,j.list.length),j.list.last(),j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex)},!(this.remove=function(e){zot(e)&&(e=j.lastIndex),j.removedItem=j.list.selected;e=Math.max(0,j.list.selectedIndex);if(j.list.removeAt(1,e),c)e=Math.max(0,j.list.selectedIndex);else e=Math.max(0,j.list.selectedIndex-1);j.list.selectedIndexPlusPosition=Math.min(j.list.length-1,e),j.orgItem=j.list.selected,j.orgIndex=j.list.selectedIndex})!==k&&Oe(this,B),this.clone=function(){return j.cloneProps(new kt.Organizer(e,t,r,o,i,a,l,s,n,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,j.group,A))}},kt.extend(kt.Organizer,kt.Tabs,"clone","zimTabs",!1),kt.Loader=function(t,o,n,r,i,a,l,s,e,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E){var M;if(M=zob(kt.Loader,arguments,"width, height, label, backgroundColor, rollBackgroundColor, color, rollColor, borderColor, borderRollColor, borderWidth, corner, shadowColor, shadowBlur, hitPadding, gradient, gloss, dashed, backing, rollBacking, rollPersist, icon, rollIcon, toggle, toggleBacking, rollToggleBacking, toggleIcon, rollToggleIcon, toggleEvent, frame, style, group, inherit",this))return M;z_d("67.5"),this.group=S;var O=!1===I?{}:kt.getStyle("Loader",this.group,E);if(zot(t)&&(t=null!=O.width?O.width:250),zot(o)&&(o=null!=O.height?O.height:70),zot(r)&&(r=null!=O.backgroundColor?O.backgroundColor:"rgba(0,0,0,.05)"),zot(i)&&(i=null!=O.rollBackgroundColor?O.rollBackgroundColor:"rgba(0,0,0,.1)"),zot(a)&&(a=null!=O.color?O.color:"rgba(0,0,0,.5)"),zot(l)&&(l=null!=O.rollColor?O.rollColor:a),zot(s)&&(s=null!=O.borderColor?O.borderColor:"rgba(0,0,0,.3)"),zot(c)&&(c=null!=O.borderWidth?O.borderWidth:1),zot(m)&&(m=null==O.dashed||O.dashed),zot(u)&&(u=null!=O.corner?O.corner:0),zot(n)&&(n=null!=O.label?O.label:new kt.Label({text:"UPLOAD PIC",color:a,rollColor:l,valign:"center",align:"center",backing:"ignore",shadowColor:"ignore",shadowBlur:"ignore",backgroundColor:"ignore",group:this.group})),zot(B)){if(!zimDefaultFrame)return void(zon&&zog("zim.Loader - please provide a reference to zim Frame"));B=zimDefaultFrame}this.zimButton_constructor(t,o,n,r,i,a,l,s,e,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,null,null,null,null,null,null,null,null,null,null,null,null,!1),this.type="Loader";var j=this,D=B.stage;n=j.label;var L=j.tag=document.createElement("input");document.body.appendChild(L),L.setAttribute("type","file"),L.setAttribute("multiple","multiple"),L.setAttribute("aria-hidden",!0),L.hidden=!0,L.style.cssText="border:thin solid grey; z-index:2; width:"+t+"px; height:"+o+"px; overflow:hidden; outline:none;position:absolute; left:0px; top:0px; display:none; cursor:pointer; opacity: 0; filter: alpha(opacity=0);",this.addEventListener("mousedown",function(){L.click()}),L.addEventListener("change",X);var Y=new createjs.DOMElement(L);function X(e){var n;n=e.dataTransfer&&e.dataTransfer.files&&0<e.dataTransfer.files.length?e.dataTransfer.files:e.target.files;for(var r,t,o,i=[],a=0;a<n.length;a++)t=n[a],o=void 0,(o=new FileReader).onload=function(e){var o=new Image;o.onload=function(){var e=new kt.Bitmap(o);if(i.push(e),1==i.length&&(r=e),i.length==n.length){var t=new createjs.Event("loaded");t.bitmaps=i,t.bitmap=r,t.lastBitmap=e,t.total=i.length,j.dispatchEvent(t),L.value=""}},o.src=e.target.result},o.readAsDataURL(t)}D.addChild(Y),Y.alpha=0,this.resize=function(){return j.stage?(L.setAttribute("aria-hidden",!1),L.hidden=!1,L.style.display="block",setTimeout(function(){var e=j.localToGlobal(0,0);Y.x=B.x+e.x*B.scale,Y.y=B.y+e.y*B.scale,kt.sca(Y,B.scale*j.scaleX,B.scale*j.scaleY),D.update()},50),j):(L.setAttribute("aria-hidden",!0),L.hidden=!0,void(L.style.display="none"))},this.resize(),j.on("added",function(){L.style.display="block",L.hidden=!1,L.style.display="block",j.resize()}),j.added(function e(){j.resize();setTimeout(function(){L.style.display="block",L.hidden=!1,L.style.display="block"},50);j.on("added",e,null,!0)}),j.on("removed",function(){L.style.display="none",L.hidden=!0,L.style.display="none"}),B.on("resize",j.resize),(new XMLHttpRequest).upload&&L.addEventListener("drop",function(e){L.removeEventListener("change",X),X(e),setInterval(function(){L.addEventListener("change",X)},100)}),!(this.save=function(e,t,o,n,r,i,a,l,s){var c;if(c=zob(j.save,arguments,"content, filename, x, y, width, height, cached, cachedBounds, type"))return c;if(zot(e)&&(e=B.stage),zot(s)&&(s="png"),zot(t))t="saved_"+String(kt.makeID("numbers",5))+"."+s;else{var u=t.split(".");if(1==u.length)t+="."+s;else{var d=["png","jpg","jpeg"],h=d.indexOf(u[u.length-1].toLowerCase());-1==h?t+="."+s:s=d[h]}}if(zot(o)&&(o=0),zot(n)&&(n=0),zot(r)&&(r=e.getBounds&&e.getBounds()?e.getBounds().width:B.width),zot(i)&&(i=e.getBounds&&e.getBounds()?e.getBounds().height:B.height),e.cache(o,n,r,i),/Edge\/(\d)+/.test(navigator.userAgent)){var g=window.open();g.document.write("<html><head><title>saved</title></head><body style='margin:0px;padding:0px;overflow:hidden'><img src="+e.cacheCanvas.toDataURL("image/"+s)+"></body></html>"),g.document.close()}else{var p=document.createElement("a");p.setAttribute("download",t),p.setAttribute("href",e.cacheCanvas.toDataURL("image/"+s)),document.body.appendChild(p),p.click(),document.body.removeChild(p)}return a?l&&e.cache(cashedBound.x,cashedBound.y,cashedBound.width,cashedBound.height):e.uncache(),j})!==I&&Oe(this,O),this.clone=function(){var e=new kt.Loader(t,o,zot(n)?null:n.clone(),r,i,a,l,s,c,u,d,h,g,p,f,zot(z)?null:z.clone(),zot(v)?null:v.clone(),y,zot(b)?null:b.clone(),zot(w)?null:w.clone(),x,zot(C)?null:C.clone(),zot(k)?null:k.clone(),zot(T)?null:T.clone(),zot(A)?null:A.clone(),P,B,I,this.group);return j.cloneProps(e)},this.dispose=function(){return document.body.removeChild(L),this.zimButton_dispose(),!0}},kt.extend(kt.Loader,kt.Button,["clone","dispose"],"zimButton",!1),kt.TextArea=function(t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,e,x){var C;if(C=zob(kt.TextArea,arguments,"width, height, size, padding, color, backgroundColor, borderColor, borderWidth, corner, shadowColor, shadowBlur, dashed, id, placeholder, readOnly, spellCheck, password, inputType, frame, expand, style, group, inherit",this))return C;z_d("67.6"),this.group=e;var k=!1===w?{}:kt.getStyle("TextArea",this.group,x);if(zot(t)&&(t=null!=k.width?k.width:250),zot(o)&&(o=null!=k.height?k.height:70),zot(n)&&(n=null!=k.size?k.size:20),zot(r)&&(r=null!=k.padding?k.padding:5),zot(i)&&(i=null!=k.color?k.color:"#666"),zot(a)&&(a=null!=k.backgroundColor?k.backgroundColor:"rgba(256,256,256,.1)"),zot(l)&&(l=null!=k.borderColor?k.borderColor:"rgba(0,0,0,.1)"),zot(s)&&(s=null!=k.borderWidth?k.borderWidth:null),l<0||s<0?l=s=null:null!=l&&null==s&&(s=1),zot(c)&&(c=null!=k.corner?k.corner:0),!zot(d)&&zot(u)&&(u=null!=k.shadowColor?k.shadowColor:"rgba(0,0,0,.3)"),!zot(u)&&zot(d)&&(d=null!=k.shadowBlur?k.shadowBlur:10),zot(z)&&(z=null!=k.password&&k.password),zot(v)&&(v=null!=k.inputType&&k.inputType),zot(b)&&(b=null!=k.expand?k.expand:20),!0===b&&(b=20),zot(y)){if(!zimDefaultFrame)return void(zon&&zog("zim.TextArea - please provide a reference to zim Frame"));y=zimDefaultFrame}this.zimContainer_constructor(t,o,null,null,!1),this.type="TextArea";var T=this,A=y.stage,P=this.background=new kt.Rectangle(t,o,a,l,s,c,h,!1).expand(b);-1!=u&&0<d&&(P.shadow=new createjs.Shadow(u,3,3,d)),T.addChild(P);var B=T.tag=v||z?document.createElement("input"):document.createElement("textarea");document.body.appendChild(B),zot(g)||(B.setAttribute("id",g),B.setAttribute("name",g)),z?B.setAttribute("type","password"):v&&B.setAttribute("type",v),f&&(B.readOnly=!0),m||(B.spellcheck=!1),zot(p)||B.setAttribute("placeholder",p),B.style.cssText="background-color:rgba(0,0,0,.01); color:"+i+"; resize:none; z-index:3; width:"+(t-2*r)+"px; height:"+(o-2*r)+"px; overflow:hidden; outline:none;font-size:"+n+"px; font-family:"+(null!=k.font?k.font:"arial")+"; border:none; position:absolute; left:0px; top:0px; display:none;",B.addEventListener("change",function(){T.dispatchEvent("change")}),B.addEventListener("input",function(){T.dispatchEvent("input")}),B.addEventListener("focus",function(){y.zil&&window.removeEventListener("keydown",y.zil[0]),T.dispatchEvent("focus")}),B.addEventListener("blur",function(){y.zil&&window.addEventListener("keydown",y.zil[0]),T.dispatchEvent("blur")});var I=new createjs.DOMElement(B);I.alpha=0,this.on("mousedown",function(){setTimeout(function(){B.focus()},100)}),this.setFocus=function(e){return zot(e)&&(e=!0),e?B.focus():B.blur(),T},this.resize=function(){return setTimeout(function(){var e=T.localToGlobal(r,r);I.x=y.x+e.x*y.scale,I.y=y.y+e.y*y.scale,kt.sca(I,y.scale*T.scaleX,y.scale*T.scaleY),I.alpha=1,T.stage&&A.update()},50),T},this.resize(),T.added(function e(){A.addChild(I);setTimeout(function(){B.style.display="block"},50);T.resize();T.on("added",e,null,!0)}),T.on("removed",function(){A.removeChild(I),B.style.display="none"}),y.on("resize",T.resize),Object.defineProperty(this,"currentValue",{get:function(){return B.value},set:function(e){B.value=e}}),Object.defineProperty(this,"text",{get:function(){return B.value},set:function(e){B.value=e}}),Object.defineProperty(this,"focus",{get:function(){return document.activeElement==B},set:function(e){T.setFocus(e)}}),Object.defineProperty(this,"readOnly",{get:function(){return B.readOnly},set:function(e){B.readOnly=e}}),"undefined"!=typeof KEYFOCUS&&(kt.KEYFOCUS=KEYFOCUS),Object.defineProperty(this,"keyFocus",{get:function(){return kt.KEYFOCUS==T},set:function(e){kt.KEYFOCUS=T}}),kt.KEYFOCUS||(T.keyFocus=!0),B.addEventListener("mousedown",function(){T.keyFocus=!0}),!1!==w&&Oe(this,k),this.clone=function(){var e=new kt.TextArea(t,o,n,r,i,a,l,s,c,u,d,h,g,p,f,m,z,v,y,b,w,this.group,x);return T.cloneProps(e)},this.dispose=function(){return document.body.removeChild(B),this.zimContainer_dispose(),!0}},kt.extend(kt.TextArea,kt.Container,["clone","dispose"],"zimContainer",!1),kt.Tag=function(t,o,n,r,i,a,l,s,c,u,e,d){var h;if(h=zob(kt.Tag,arguments,"width, height, id, frame, backgroundColor, padding, paddingHorizontal, paddingVertical, expand, style, group, inherit",this))return h;z_d("67.7"),this.group=e;var g=!1===u?{}:kt.getStyle("Tag",this.group,d);if(zot(t)&&(t=null!=g.width?g.width:250),zot(o)&&(o=null!=g.height?g.height:70),zot(n)&&(n=null!=g.id?g.id:"zimTag_"+kt.rand(1e4)),zot(r)){if(!zimDefaultFrame)return void(zon&&zog("zim.TextArea - please provide a reference to zim Frame"));r=zimDefaultFrame}zot(i)&&(i=null!=g.backgroundColor?g.backgroundColor:"rgba(0,0,0,0)"),zot(a)&&(a=null!=g.padding?g.padding:10),zot(l)&&(l=null!=g.paddingHorizontal?g.paddingHorizontal:a),zot(s)&&(s=null!=g.paddingVertical?g.paddingVertical:a),zot(c)&&(c=null!=g.expand?g.expand:20),!0===c&&(c=20),this.zimContainer_constructor(t,o,null,null,!1),this.type="Tag",this.tagID=n,this.id=n;var p=this,f=r.stage,m=(p.background=new kt.Rectangle(t+l,o+s,i).center(this).expand(c||0),p.tag=document.createElement("div"));document.body.appendChild(m),m.setAttribute("id",n),m.setAttribute("name",n),m.style.cssText="resize:none; z-index:3; width:"+t+"px; height:"+o+"px; overflow:hidden; outline:none;position:absolute; left:0px; top:0px; display:none;";var z=new createjs.DOMElement(m);z.alpha=0,this.resize=function(){return setTimeout(function(){var e=p.localToGlobal(0,0);z.x=r.x+e.x*r.scale,z.y=r.y+e.y*r.scale,kt.sca(z,r.scale*p.scaleX,r.scale*p.scaleY),z.alpha=1,p.stage&&f.update()},50),p},this.resize(),p.added(function e(){f.addChild(z);setTimeout(function(){m.style.display="block"},50);p.resize();p.on("added",e,null,!0)}),p.on("removed",function(){f.removeChild(z),m.style.display="none"}),r.on("resize",p.resize),this.add=function(e){return m.innerHTML+=e,p},Object.defineProperty(this,"innerHTML",{get:function(){return m.innerHTML},set:function(e){m.innerHTML=e}}),Object.defineProperty(this,"style",{get:function(){return m.style},set:function(e){m.style=e}}),!1!==u&&Oe(this,g),this.clone=function(){var e=new kt.Tag(t,o,n,r,i,a,l,s,c,u,this.group,d);return p.cloneProps(e)},this.dispose=function(){return document.body.removeChild(m),this.zimContainer_dispose(),!0}},kt.extend(kt.Tag,kt.Container,["clone","dispose"],"zimContainer",!1),kt.addTo=function(e,t,o,n){var r;if(r=zob(kt.addTo,arguments,"obj, container, index, localToLocal"))return r;if(z_d("47.5"),!zot(e)){if(zot(t)){if(!zimDefaultFrame)return void zog("zim methods - addTo(): please provide container");t=zimDefaultFrame.stage}if(zot(n)&&(n=!0),e.parent||(n=!1),n)var i=e.parent.localToLocal(e.x,e.y,t);return zot(o)||isNaN(o)?t.addChild(e):t.addChildAt(e,o),n&&(e.x=i.x,e.y=i.y),e}zog("zim methods - addTo(): please provide object")},kt.removeFrom=function(e,t){if(z_d("47.6"),!zot(e))return zot(t)?e.parent&&e.parent.removeChild(e):t.removeChild(e),e;zog("zim methods - removeFrom(): please provide object")},kt.added=function(e,t,o,n){if(z_d("47.7"),!zot(e)&&!zot(t)&&"function"==typeof t){if(zot(o)&&(o=100),!e.stage){var r=Date.now(),i=0,a=setInterval(function(){5<i?clearInterval(a):(i++,e.stage&&(t(e.stage,e),clearInterval(a),clearInterval(l)))},10),l=setInterval(function(){0<n&&r-Date.now()>n&&clearInterval(l),e.stage&&(t(e.stage,e),clearInterval(l))},o);return l}t(e.stage,e)}},kt.centerReg=function(e,t,o,n){var r;if(r=zob(kt.centerReg,arguments,"obj, container, index, add"))return r;if(z_d("48"),zot(e)||!e.getBounds||!e.getBounds())return zog("zim methods - centerReg(): please provide object with bounds set"),e;zot(n)&&(n=!0),zot(t)&&e.parent&&n&&(t=e.parent,zot(o)&&(o=e.parent.getChildIndex(e)),e.parent.removeChild(e)),zot(t)||t!=e.parent||(zot(o)&&(o=e.parent.getChildIndex(e)),e.parent.removeChild(e));var i=e.getBounds();return e.regX=i.x+i.width/2,e.regY=i.y+i.height/2,n?kt.center(e,t,o):e},kt.centerCheck=!1,kt.center=function(e,t,o,n){var r;if(r=zob(kt.center,arguments,"obj, container, index, add"))return r;if(kt.centerCheck||(z_d("48.1"),kt.centerCheck=!0),!zot(e)&&e.getBounds){if(zot(t)&&(e.parent?t=e.parent:zimDefaultFrame&&(t=zimDefaultFrame.stage)),!zot(t)&&t.getBounds){var i=e.getBounds(),a=t.getBounds();if(zot(n)&&(n=!0),n&&t.addChild&&(zot(o)||"number"==typeof o&&isNaN(o)?t.contains(e)||t.addChild(e):t.addChildAt(e,o)),zot(a))return e;if(zot(i))return e.x=t.getBounds().width/2,e.y=t.getBounds().height/2,e;var l=e.localToLocal(e.regX,e.regY,t),s=kt.boundsToGlobal(e),c=kt.boundsToGlobal(t,s,!0);if(e.x=a.x+a.width/2-c.width/2+(l.x-c.x),e.y=a.y+a.height/2-c.height/2+(l.y-c.y),!n&&t.getStage&&t.stage&&e.parent){var u=t.localToLocal(e.x,e.y,e.parent);e.x=u.x,e.y=u.y}return e}zog("zim.center(): please provide container with bounds")}else zog("zim.center(): please provide object with bounds")},kt.place=function(e,t){if(z_d("49"),!zot(e))return zot(t)&&(t="obj"),kt.drag({obj:e,currentTarget:!0,dragCursor:"crosshair"}),zog("place "+t+" - to get new position"),e.on("click",function(){zog(t+".x = "+Math.round(e.x)+"; "+t+".y = "+Math.round(e.y)+";"),zog(t+".loc("+Math.round(e.x)+", "+Math.round(e.y)+");")}),e},kt.placeReg=function(t,o){if(z_d("49.5"),!zot(t)){var e=t.stage;if(zot(e))return zog("zim.placeReg() - add object to stage before calling placeReg()"),t;zot(o)&&(o="obj");var n=t.parent.localToGlobal(t.x,t.y),r=new kt.Shape(-25,-25,50,50,null,!1).addTo(e).pos({x:n.x,y:n.y,reg:!0});return r.graphics.s("white").mt(-25,0).lt(25,0).mt(0,-25).lt(0,20),r.compositeOperation="difference",r.expand(0),kt.drag({obj:r}),zog("place cursor to get new registration point location"),e.on("stagemouseup",function(){var e=t.globalToLocal(r.x,r.y);zog(o+".regX = "+Math.round(e.x)+"; "+o+".regY = "+Math.round(e.y)+";"),zog(o+".reg("+Math.round(e.x)+", "+Math.round(e.y)+");")}),t}},kt.pos=function(m,e,t,o,n,r,i,a,l,s,c){var u;if(u=zob(kt.pos,arguments,"obj, x, y, right, bottom, container, index, add, reg, regX, regY"))return u;z_d("41.5");var d=kt.POSREG;if("undefined"!=typeof POSREG&&(d=POSREG),zot(l)&&(l=d),!zot(m)){if(zot(l)&&zot(s)&&(s=!1),zot(l)&&zot(c)&&(c=!1),!zot(l)&&zot(s)&&(s=l),!zot(l)&&zot(c)&&(c=l),!0!==o&&(o=!1),!0!==n&&(n=!1),zot(a)&&(a=!0),zot(r)||r.addChild||(r=null),m.getBounds||object.getBounds()||(s=c=!1),zot(r)&&(m.parent?r=m.parent:zimDefaultFrame&&(r=zimDefaultFrame.stage)),!m.parent&&zot(e)&&(e=0),!m.parent&&zot(t)&&(t=0),!zot(r)&&r.addChild&&a&&(zot(i)||"number"==typeof i&&isNaN(i)?r.contains(m)||r.addChild(m):r.addChildAt(m,i)),m.parent&&m.parent.getBounds){if(r=m.parent,zot(e)&&1==o&&(e=0),zot(t)&&1==n&&(t=0),zot(e)||(m.x=e),zot(t)||(m.y=t),zot(e)&&zot(t)&&!o&&!n)return m;var h=0,g=0;if(m.getBounds()){var p=function(){var e=m.getBounds(),t=e.x,o=e.y,n=e.width,r=e.height,i=m._props.matrix;i=m.getMatrix(i),(t||o)&&i.appendTransform(0,0,1,1,0,0,0,-t,-o);var a=n*i.a,l=n*i.b,s=r*i.c,c=r*i.d,u=i.tx,d=i.ty,h=u,g=u,p=d,f=d;(t=a+u)<h?h=t:g<t&&(g=t);(t=a+s+u)<h?h=t:g<t&&(g=t);(t=s+u)<h?h=t:g<t&&(g=t);(o=l+d)<p?p=o:f<o&&(f=o);(o=l+c+d)<p?p=o:f<o&&(f=o);(o=c+d)<p?p=o:f<o&&(f=o);return{x:h,y:p,width:g-h,height:f-p}}();if(!zot(e)){if(o)f=new kt.Point(p.x+p.width,p.y+p.height);else var f=new kt.Point(p.x,p.y);h=f.x-e}if(!zot(t)){if(n)f=new kt.Point(p.x+p.width,p.y+p.height);else var f=new kt.Point(p.x,p.y);g=f.y-t}var z=r.getBounds();zot(e)||(o?m.x=s?z.width+z.x-e:z.width+z.x-e-h:(m.x=s?e:e-h,m.x+=z.x)),zot(t)||(n?m.y=c?z.height+z.y-t:z.height+z.y-t-g:(m.y=c?t:t-g,m.y+=z.y))}}return m}},kt.loc=function(e,t,o,n,r,i,a,l){var s;if(s=zob(kt.loc,arguments,"obj, target, y, container, index, add, localToLocal, x"))return s;if(z_d("41.55"),!zot(e)){if("number"==typeof t&&(l=t,t=null),zot(t)||(zot(t.x)||(l=t.x),zot(t.y)||(o=t.y)),zot(l)&&zot(t)&&(l=e.x),zot(o)&&zot(t)&&(o=e.y),zot(i)&&(i=!0),zot(n)&&(e.parent?n=e.parent:zimDefaultFrame&&(n=zimDefaultFrame.stage)),i&&n&&(e.parent&&n==e.parent||(zot(r)||isNaN(r)?n.addChild(e):n.addChildAt(e,r))),zot(a)&&(a=!0),t&&t.parent&&e.parent&&a){var c=t.parent.localToLocal(l,o,e.parent);l=c.x,o=c.y}return e.x=l,e.y=o,e}},kt.mov=function(e,t,o){var n;return(n=zob(kt.mov,arguments,"obj, x, y"))?n:(z_d("41.6"),zot(e)?void 0:(zot(t)||(e.x+=t),zot(o)||(e.y+=o),e))},kt.sca=function(e,t,o){if(z_d("41.97"),!zot(e)&&!zot(e.scaleX))return zot(t)&&(t=e.scaleX),zot(o)&&(o=t),e.scaleX=t,e.scaleY=o,e},kt.alp=function(e,t){if(z_d("41.7"),!zot(e))return zot(t)||(e.alpha=e.hovOriginal=t),e},kt.hov=function(e,t,o){if(z_d("41.75"),!zot(e))return zot(t)&&(t=1),zot(o)&&(o="number"==typeof t?"alpha":"color"),e.hovMouseover&&(e.off(e.hovMouseover),e.off(e.hovMouseout)),-1==t?(e.off("mouseover",e.hovMouseover),e.off("mouseout",e.hovMouseout)):(e.hovOld=e[o],e.hovNew=t,e.hovMouseover=e.on("mouseover",function(){e[o]=e.hovNew,e.stage.update()}),e.cursor&&(e.cursor="pointer"),e.hovMouseout=e.on("mouseout",function(){e[o]=e.hovOld,e.stage.update()})),e},kt.rot=function(e,t,o,n){if(z_d("41.8"),!zot(e)){if(!zot(t))if(!e.parent||zot(o)&&zot(n))e.rotation=t;else{zot(o)&&(o=e.x),zot(n)&&(n=e.y);e.x,e.y;var r=e.parent.localToLocal(o,n,e),i=new Point(e.x,e.y);e.reg(r.x,r.y),e.rotation=t,e.x=o,e.y=n;var a=e.parent.localToLocal(i.x,i.y,e);e.reg(a.x,a.y),e.x=i.x,e.y=i.y}return e}},kt.siz=function(e,t,o,n){if(z_d("41.85"),!zot(e))return zot(n)&&(n=!1),zot(t)||zot(o)?zot(t)?zot(o)||(n?e.heightOnly=o:e.height=o):n?e.widthOnly=t:e.width=t:(e.widthOnly=t,e.heightOnly=o),e},kt.ske=function(e,t,o){if(z_d("41.9"),!zot(e))return zot(t)||(e.skewX=t),zot(o)||(e.skewY=o),e},kt.reg=function(e,t,o){if(z_d("41.95"),!zot(e))return zot(t)||(e.regX=t),zot(o)||(e.regY=o),e},kt.top=function(e){if(z_d("41.62"),!zot(e)&&e.parent)return e.parent.setChildIndex(e,e.parent.numChildren-1),e},kt.bot=function(e){if(z_d("41.63"),!zot(e)&&e.parent)return e.parent.setChildIndex(e,0),e},kt.ord=function(e,t){if(z_d("41.64"),!zot(e)&&e.parent)return zot(t)&&(t=0),e.parent.setChildIndex(e,e.parent.getChildIndex(e)+t),e},kt.cur=function(e,t){return z_d("41.1"),zot(e)?zog("zim methods - cur(): please provide object"):(zot(t)&&(t="pointer"),e.cursor=t),e},kt.sha=function(e,t,o,n,r){return z_d("41.2"),zot(e)?(zog("zim methods - sha(): please provide object"),e):(zot(t)&&(t="rgba(0,0,0,.3)"),t.blur?e.shadow=t:(zot(o)&&(o=e.width?.08*e.width:5),zot(n)&&(n=e.height?.08*e.height:5),zot(r)&&(r=e.width?.16*e.width:10),e.shadow=new createjs.Shadow(t,o,n,r)),e)},kt.dep=function(e,t){if(z_d("41.65"),!zot(e))return zot(t)&&(t=0),e.depth=t,e},kt.tap=function(r,i,a,l,e){if(z_d("47.8"),!zot(r)&&!zot(i)&&"function"==typeof i)return zot(a)&&(a=5),zot(l)&&(l=1e4),zot(e)&&(e=!1),r.cursor="pointer",r.zimClickDownEvent=r.on("mousedown",function(e){if("List"==e.currentTarget.type){if("WindowBacking"==e.target.type)return;if(e.currentTarget.globalToLocal(e.stageX,e.stageY).y<=0)return}var t=e.stageX,o=e.stageY,n=Date.now();r.zimClickUpEvent=r.on("pressup",function(e){if(Math.abs(t+o-e.stageX-e.stageY)<a&&Date.now()-n<l){if(r.excludeTap)return;i(e)}},null,!0)},null,e),r},kt.noTap=function(e){if(z_d("47.9"),!zot(e))return e.cursor&&(e.cursor="default"),e.off("mousedown",e.zimClickDownEvent),e.off("pressup",e.zimClickUpEvent),e},kt.change=function(e,t,o){if(z_d("47.85"),!zot(e)&&!zot(t)&&"function"==typeof t)return zot(o)&&(o=!1),e.zimChangeEvent=e.on("change",function(e){t(e)},null,o),e},kt.noChange=function(e){if(z_d("47.95"),!zot(e))return e.off("mousedown",e.zimChangeEvent),e},kt.drag=function(a,e,i,r,t,o,l,s,c,u,n,d,h,g,p,f,m){var z;if(z=zob(kt.drag,arguments,"obj, boundary, overCursor, dragCursor, all, swipe, localBounds, onTop, surround, slide, slideDamp, slideSnap, reg, removeTweens, startBounds, rect, currentTarget"))return z;if(z_d("31"),!zot(a)&&a.on){var v=kt.DRAGALL;"undefined"!=typeof DRAGALL&&(v=DRAGALL),zot(t)&&zot(m)&&(t=v),a.zimDown&&a.noDrag(),a.cursor=zot(i)?"pointer":i,zot(t)&&zot(m)?m=!1:zot(t)?zot(m)&&(m=!1):m=t,"Tag"!=a.type&&"TextArea"!=a.type&&"Loader"!=a.type||(m=!0),zot(o)&&(o=!1),zot(l)&&(l=!1),zot(s)&&(s=!0),zot(c)&&(c=!1),zot(u)&&(u=!1),zot(n)&&(n=.3),zot(d)&&(d=!0);if(!0!==d&&["horizontal","vertical","auto"].indexOf(d)<0&&(d=!1),zot(h)&&(h=!1),zot(g)&&(g=!0),zot(p)&&(p=!0),zot(e)&&!zot(f)&&(e=f),u)var y,b,w,x,C,k,T,A,P,B,I,S,E,M;kt.setSwipe(a,o),a.zimBoundary=e,a.zimLocalBounds=l;var O,j,D,L,Y,X,R=!1,_=!1;return a.zimAdded=a.on("added",W,null,!0),a.zimRemoved=a.on("removed",function(){a.zimDragTicker&&kt.Ticker.remove(a.zimDragTicker)},null,!0),a.parent&&W(),a.pointers={},a.zimDown=a.on("mousedown",function(e){if(a.stage){a.dragMouseX=Math.round(e.stageX),a.dragMouseY=Math.round(e.stageY);var t="id"+Math.abs(e.pointerID+1);if(a.pointers[t]=!0,X=m?e.currentTarget:e.target,!a.zimBoundary||X.getBounds()){if(R=!0,a.stage.mouseMoveOutside=!0,u||(a.zimDragTicker&&kt.Ticker.remove(a.zimDragTicker),a.zimDragTicker=kt.Ticker.add(function(){},a.stage)),g&&createjs.Tween.removeTweens(X),X.parent){if(s){var o=X.parent.numChildren-1;"Keyboard"==X.parent.getChildAt(o).type&&o--,X.parent.setChildIndex(X,o),X.ZIMoutlineShape&&X.outline()}var n=X.parent.globalToLocal(e.stageX,e.stageY);h&&(X.x=n.x,X.y=n.y),O=n.x-X.x,j=n.y-X.y,a.zimBoundary&&(l?(L=kt.boundsToGlobal(X.parent,a.zimBoundary),c&&(Y=a.zimBoundary)):(L=a.zimBoundary,c&&(Y=kt.boundsToGlobal(X.parent,a.zimBoundary,!0)))),a.cursor=zot(r)?"pointer":r,u&&(x=0,C=[n.x],k=[n.y],M=E=-1e4,a.zimDragMoving=!0),"Pen"==a.type&&(a.zimDragCheck=!0,_=!1)}}else zog("zim.drag() - drag object needs bounds set")}},!0),a.zimMove=a.on("pressmove",function(e){R&&(a.dragMouseX=Math.round(e.stageX),a.dragMouseY=Math.round(e.stageY),F(X,e.stageX,e.stageY),X.ZIMoutlineShape&&X.outline(),"Pen"==a.type&&!_&&a.drawing?_=!0:"Tag"!=a.type&&"TextArea"!=a.type&&"Loader"!=a.type||a.resize())},!0),a.zimPosition=F,a.zimUp=a.on("pressup",function(e){var t="id"+Math.abs(e.pointerID+1);if(delete a.pointers[t],R){if(a.cursor=zot(i)?"pointer":i,u){var o=X.parent.globalToLocal(e.stageX,e.stageY);R=!1,T=o.x,A=o.y,P=X.x,B=X.y,y.immediate(X.x),b.immediate(X.y)}else{var n=0;for(var r in a.pointers)n++;0==n&&kt.Ticker.remove(a.zimDragTicker),"Pen"==a.type&&(a.zimDragCheck=!1,_&&a.stopCheck())}a.stage&&a.stage.update()}},!0),a}function W(){j=O=0,a.zimBoundary&&(l?(L=kt.boundsToGlobal(a.parent,a.zimBoundary),c&&(Y=a.zimBoundary)):(L=a.zimBoundary,c&&(Y=kt.boundsToGlobal(a.parent,a.zimBoundary,!0)))),L&&p&&(D=a.parent.localToGlobal(a.x,a.y),F(a,D.x,D.y)),u&&setTimeout(function(){y=new kt.Damp(a.x,n),b=new kt.Damp(a.y,n),a.zimDragImmediate=function(e,t){B=t,T=I=A=S=0,zot(P=e)||y.immediate(e),zot(t)||b.immediate(t)},w=3,x=0,C=[],k=[],T=a.x,A=a.y,P=a.x,B=a.y,I=a.x,S=a.y,M=E=-1e4,a.zimDragMoving=!0,function(){var e=a.stage;function r(e,t,o,n,r){Math.abs(e.x-E)<.1&&Math.abs(e.y-M)<.1?(a.zimDragMoving=!1,e.x=n,e.y=r,e.dispatchEvent("slidestop"),"Pen"==a.type&&(a.zimDragCheck=!1,_&&a.stopCheck())):(E=t,M=o)}a.zimDragTicker=function(){if(X||(X=a),R){var e=X.parent.globalToLocal(a.dragMouseX,a.dragMouseY);x++,C.push(e.x),k.push(e.y),S=w<=x?(I=C.shift(),k.shift()):(I=C[0],k[0])}else{if(!a.zimDragMoving)return;var t=P+T-I,o=B+A-S;if(L){var n=H(X,t,o);t=n.x,o=n.y}if(d)X.x=y.convert(t),X.y=b.convert(o),r(X,X.x,X.y,t,o);else{var n=H(X,y.convert(t),b.convert(o));X.x=n.x,X.y=n.y,r(X,X.x,X.y,X.x,X.y)}}},kt.Ticker.add(a.zimDragTicker,e)}()},50),zot(a.zimMaskDynamic)||a.zimMaskApply()}function F(e,t,o){if(zot(e)&&(e=X||a),e.parent){if(zot(t)||zot(o)){var n=e.parent.localToGlobal(e.x,e.y);O=j=0,a.zimBoundary&&(l?(L=kt.boundsToGlobal(e.parent,a.zimBoundary),c&&(Y=e.zimBoundary)):(L=a.zimBoundary,c&&(Y=kt.boundsToGlobal(e.parent,a.zimBoundary,!0)))),t=n.x,o=n.y,u&&(P=e.x,B=e.y,X=e,y&&y.immediate(P),b&&b.immediate(B))}var r,i=e.parent.globalToLocal(t,o);e.y=u&&d?"vertical"==d?(r=H(e,i.x-O,i.y-j),e.x=r.x,i.y-j):"horizontal"==d?(r=H(e,i.x-O,i.y-j),e.x=i.x-O,r.y):(e.x=i.x-O,i.y-j):(r=H(e,i.x-O,i.y-j),e.x=r.x,r.y)}}function H(e,t,o){if(L)if(c){var n=e.getBounds().width,r=e.getBounds().height,i=e.getBounds().x,a=e.getBounds().y;n<Y.width?t=Y.x+(Y.width-n)/2+(e.regX-i):(t-(e.regX-i)>Y.x&&(t=Y.x+(e.regX-i)),t-(e.regX-i)+n<Y.x+Y.width&&(t=Y.x+Y.width+(e.regX-i)-n)),e.height<Y.height?o=Y.y+(Y.height-r)/2+(e.regY-a):(o-(e.regY-a)>Y.y&&(o=Y.y+(e.regY-a)),o-(e.regY-a)+r<Y.y+Y.height&&(o=Y.y+Y.height+(e.regY-a)-r))}else{var l=e.parent.localToGlobal(t,o);t=Math.max(L.x,Math.min(L.x+L.width,l.x)),o=Math.max(L.y,Math.min(L.y+L.height,l.y)),t=(l=e.parent.globalToLocal(t,o)).x,o=l.y}return{x:t,y:o}}},kt.noDrag=function(e){if(z_d("32"),!zot(e)&&e.on)return e.cursor="default",kt.setSwipe(e,!0),e.off("added",e.zimAdded),e.off("removed",e.zimRemoved),e.off("mousedown",e.zimDown),e.off("pressmove",e.zimMove),e.off("pressup",e.zimUp),kt.Ticker&&e.zimDragSlide&&kt.Ticker.remove(e.zimDragSlide),e.zimDragMoving=e.zimAdded=e.zimRemoved=e.zimDown=e.zimMove=e.zimUp=e.zimBoundary=e.zimDragSlide=null,e},kt.dragBoundary=function(e,t,o){if(z_d("33"),!zot(e)&&e.on&&!zot(t))return e.zimBoundary=t,e.zimDragMoving=!0,e.zimPosition&&e.zimPosition(),e},kt.dragRect=kt.dragBoundary,kt.transform=function(l,t,e,o,n,r,i,a,s,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P){var B;if(B=zob(kt.transform,arguments,"obj, move, stretchX, stretchY, scale, rotate, allowToggle, visible, onTop, showStretch, showRotate, showScale, showReg, showBorder, borderColor, borderWidth, dashed, customCursors, handleSize, regSize, snapDistance, snapRotation, cache, events, ghostColor, ghostWidth, ghostDashed, ghostHidden"))return B;if(z_d("33.5"),zot(l)||!l.getBounds)return zog("zim methods - transform(): please provide object with bounds set"),l;if(!l.getBounds())return zog("zim methods - transform(): please setBounds() on object"),l;if(!l.parent)return zog("zim methods - transform(): object should be on stage first"),l;zot(t)&&(t=!0),zot(e)&&(e=!0),zot(o)&&(o=!0),zot(n)&&(n=!0),zot(r)&&(r=!0);var I=kt.mobile();zot(i)&&(i=!0),zot(a)&&(a=!0),zot(s)&&(s=!0),zot(c)&&(c=!!I),zot(u)&&(u=!!I),zot(d)&&(d=!0),zot(h)&&(h=!0),zot(g)&&(g=!0),zot(p)&&(p="brown"),zot(f)&&(f=1),zot(k)&&(k=null),zot(T)&&(T=null),k<0||T<0?k=T=null:null!=k&&null==T&&(T=1),zot(A)&&(A=!0),zot(P)&&(P=!1),zot(z)&&(z=!I),zot(v)&&(v=kt.mobile()?20:10),zot(y)&&(y=16),zot(b)&&(b=10),zot(w)&&(w=5),zot(x)&&(x=!0),zot(C)&&(C=!1),l.mouseChildren=!1;var S,E=l.getConcatenatedMatrix().decompose();if(l.stage)S=l.stage;else{if(!zimDefaultFrame)return l;S=zimDefaultFrame.stage}if(!frame){if(!zimDefaultFrame)return l;frame=zimDefaultFrame}var M=l.getBounds(),O=new kt.Shape({style:!1}),j=new kt.Shape({style:!1}),D=new kt.Shape({style:!1});j.mouseEnabled=!1,D.controlType="reg";var L,Y,X,R,_,W,F,H=l.parent,V=O.graphics,N=j.graphics,G=D.graphics,q=new kt.Container({style:!1});q.type="TransformControls";var U,K,Z,Q,J,$=new kt.Container({style:!1}),ee=new kt.Container({style:!1}),te=new kt.Container({style:!1}),oe=new kt.Container({style:!1});if(zot(l.zimMaskDynamic)||l.zimMaskApply(),z){var ne=new kt.Container({style:!1}),re=new kt.Container({style:!1});function ie(e){e==ne&&new kt.Triangle(16,12,12,"white").addTo(e).mov(0,-13.5),new kt.Triangle(16,12,12,"white").addTo(e).mov(13.5).rot(90),e==ne&&new kt.Triangle(16,12,12,"white").addTo(e).mov(0,13.5).rot(180),new kt.Triangle(16,12,12,"white").addTo(e).mov(-13.5).rot(-90),e==ne&&new kt.Triangle(10,7,7,"black").addTo(e).mov(0,-13),new kt.Triangle(10,7,7,"black").addTo(e).mov(13).rot(90),e==ne&&new kt.Triangle(10,7,7,"black").addTo(e).mov(0,13).rot(180),new kt.Triangle(10,7,7,"black").addTo(e).mov(-13).rot(-90),x&&e.cache(-20,-20,40,40)}ie(ne),ie(re);var ae={"nw-resize":45,"ne-resize":-45,"n-resize":90,"e-resize":0}}function le(){var e=l;for(Z=K=1,J=Q=U=0;e.parent;)U+=e.rotation,K*=e.scaleX,Z*=e.scaleY,Q+=e.skewX,J+=e.skewY,e=e.parent}le();for(var se=U,ce=["nw-resize","ne-resize","nw-resize","ne-resize"],ue=[2,3,0,1],de=0;de<4;de++){var he=new kt.Rectangle(v,v,d?"#e472c4":"rgba(0,0,0,0)",d?"#333":"rgba(0,0,0,0)",2,null,null,!1);x&&he.cache(-1,-1,v+2,v+2),he.centerReg($),he.expand(0),he.rotation=U,W=z?"none":ce[de],he.drag({overCursor:W,dragCursor:W,onTop:!1}),he.controlType="corner",he.cu=ce[de]}for(de=0;de<ue.length;de++)$.getChildAt(de).op=$.getChildAt(ue[de]);var ge=["n-resize","e-resize","n-resize","e-resize"];ue=[1,1,0,0];for(de=0;de<4;de++){var pe=de%2==0?l.width/2:v,fe=de%2==0?v:l.height/2;if(c){he=new kt.Rectangle(v,v,"#AAA","#333",2,null,null,!1);x&&he.cache(-1,-1,v+2,v+2)}else he=new kt.Rectangle(pe,fe,"rgba(0,0,0,0)",null,null,null,null,!1);he.centerReg(de%2==0?te:ee),he.rotation=U,he.expand(0),W=z?"none":ge[de],he.drag({overCursor:W,dragCursor:W,onTop:!1}),he.controlType="side",he.cu=ge[de]}for(de=0;de<ue.length;de++){var me=de%2==0?te:ee;me.getChildAt(Math.floor(de/2)).op=me.getChildAt(ue[de])}var ze=["ne-resize","nw-resize","ne-resize","nw-resize"];for(de=0;de<4;de++){(he=new kt.Circle(v,u?"#e472c4":"rgba(0,0,0,0)",null,null,null,null,!1)).addTo(oe),x&&he.cache(-v,-v,2*v,2*v),he.expand(0),W=z?"none":ze[de],he.drag({overCursor:W,dragCursor:W,onTop:!1}),he.controlType="rotate",he.cu=ze[de]}var ve=1.8;function ye(){var e=v*ve*kt.sign(K),t=v*ve*kt.sign(Z);oe.getChildAt(0).reg(e,t),oe.getChildAt(1).reg(-e,t),oe.getChildAt(2).reg(-e,-t),oe.getChildAt(3).reg(e,-t),S.update()}function be(){V.c(),N.c(),G.c(),L=l.localToGlobal(M.x,M.y),Y=l.localToGlobal(M.x+M.width,M.y),X=l.localToGlobal(M.x+M.width,M.y+M.height),R=l.localToGlobal(M.x,M.y+M.height),pTM=l.localToGlobal(M.x+M.width/2,M.y),pRM=l.localToGlobal(M.x+M.width,M.y+M.height/2),pBM=l.localToGlobal(M.x+M.width/2,M.y+M.height),pLM=l.localToGlobal(M.x,M.y+M.height/2),_=l.localToGlobal(l.regX,l.regY),pMid=l.localToGlobal(M.x+M.width/2,M.y+M.height/2),F=[L,Y,X,R],mids=[pTM,pRM,pBM,pLM],g&&(V.s(p),m&&V.sd([10,5],0),V.ss(f).mt(L.x,L.y).lt(Y.x,Y.y).lt(X.x,X.y).lt(R.x,R.y).lt(L.x,L.y).cp()),zot(k)||(N.s(k),A&&N.sd([10,5],0),N.ss(T).mt(L.x,L.y).lt(Y.x,Y.y).lt(X.x,X.y).lt(R.x,R.y).lt(L.x,L.y).cp()),O.setBounds(L.x,L.y,Y.x-L.x,R.y-L.y),h&&(G.s("#eee").ss(f).f("rgba(0,0,0,.1)").dc(0,0,y),G.s("#222").ss(f).dc(0,0,.3*y)),le();for(var e=Math.min(50,Math.abs(Q))*kt.sign(Q),t=Math.min(50,Math.abs(J))*kt.sign(J),o=U*kt.sign(K*Z)*kt.sign(l.scaleX*l.scaleY),n=0;n<F.length;n++){var r=F[n];$.getChildAt(n).loc(r.x,r.y).ske(e,t).rot(o),oe.getChildAt(n).loc(r.x,r.y).rot(o);var i=mids[n],a=n%2==0?te:ee;a.getChildAt(Math.floor(n/2)).loc(i.x,i.y).ske(e,t).rot(o),c||a.getChildAt(Math.floor(n/2)).sca(n%2==0?K/2:1,n%2==0?1:Z/2)}D.x=_.x,D.y=_.y}oe.alpha=.5,ye(),be();var we=new kt.Shape(1e3,1e3,null,null,null,!1);function xe(){we.x=0,we.y=0,we.graphics.c().f("rgba(0,0,0,.01)").mt(L.x,L.y).lt(Y.x,Y.y).lt(X.x,X.y).lt(R.x,R.y).lt(L.x,L.y).cp(),we.reg(_.x,_.y),we.x=_.x,we.y=_.y}xe(),q.on("dblclick",function(e){frame.ctrlKey&&l.transformControls.visible&&(l.scaleX=1,l.scaleY=1,l.rotation=0,be(),xe(),S.update()),Ue(e,!0)});var Ce=q.on("mousedown",Te),ke=l.on("mousedown",Te);function Te(e){var t=S.getObjectUnderPoint(e.stageX,e.stageY,1);t&&(l.contains&&l.contains(t)||!l.contains&&l==t)?l.transformControls.visible||(z?(et=!1,we.mouseEnabled=!1):frame.canvas.style.cursor="move",l.transformControls.show(),l.dispatchEvent("transformshow")):!l.transformControls.visible||t&&q.contains(t)||(l.transformControls.hide(),l.dispatchEvent("transformhide"))}var Ae,Pe,Be,Ie,Se,Ee,Me,Oe,je,De,Le,Ye=S.on("stagemousedown",function(e){var t=S.getObjectUnderPoint(e.stageX,e.stageY,1),o=t&&t.parent&&t.parent.layer&&t.parent.layer==l;!l.transformControls.visible||t&&(q.contains(t)||o)||(l.dispatchEvent("transformhide"),l.transformControls.hide())});i||(q.off("mousedown",Ce),l.off("mousedown",ke),S.off("stagemousedown",Ye));var Xe,Re,_e,We=!1,Fe=!1,He=l.cursor,Ve=new kt.Circle(30,"rgba(0,0,0,0)",null,null,null,null,!1).expand(20);if(z){Ve.mouseEnabled=!1,Ve.mouseChildren=!1,Ve.addChild(re),$.on("mouseover",Ze),$.on("mouseout",Qe),ee.on("mouseover",Ze),ee.on("mouseout",Qe),te.on("mouseover",Ze),te.on("mouseout",Qe),oe.on("mouseover",Ze),oe.on("mouseout",Qe);var Ne=new kt.Circle(30,"rgba(0,0,0,0)",null,null,null,null,!1).expand(20);Ne.cursor="none"}function Ge(e){if(Fe=!0,s&&Je(),Xe&&S.off("stagemousemove",Xe),Ae=e.target.x,Pe=e.target.y,Oe=l.x,je=l.y,startSX=l.scaleX,startSY=l.scaleY,"rotate"==e.target.controlType){We=!0,Be=l.rotation;var t=e.stageX,o=e.stageY,n=H.localToGlobal(Oe,je);De=n.x,Le=n.y,Ie=180*Math.atan2(o-Le,t-De)/Math.PI}Ee=frame.ctrlKey||"rotate"==e.target.controlType?(Se=Math.abs(Ae-l.x),Math.abs(Pe-l.y)):(Se=Math.abs(Ae-e.target.op.x),Math.abs(Pe-e.target.op.y)),cornerPointObj=e.target.op,"rotate"!=e.target.controlType&&(Me=e.target.op.parent.localToLocal(e.target.op.x,e.target.op.y,l.parent)),Ve.stage?S.setChildIndex(Ve,S.getChildIndex(q)):Ve.addTo(S,S.getChildIndex(q)+1),Ve.x=e.stageX,Ve.y=e.stageY,Ve.cursor=z?"none":e.target.cu,z&&(l.getConcatenatedMatrix().decompose(E),E.rotation||(E.rotation=0),re.rotation=E.rotation*kt.sign(K*Z)*kt.sign(l.scaleX*l.scaleY)+ae[e.target.cu]+se,"side"!=e.target.controlType&&K*Z<0&&(re.rotation+=90),Ne.addTo(S,1).pos({x:e.stageX,y:e.stageY,reg:!0})),we.visible=!1,l.cursor="none"}function qe(e){var t;if(t=frame.ctrlKey&&"corner"==e.target.controlType?Ee<Se?(e.target.x-Oe)/(Ae-Oe):(e.target.y-je)/(Pe-je):Ee<Se?(e.target.x-e.target.op.x)/(Ae-e.target.op.x):(e.target.y-e.target.op.y)/(Pe-e.target.op.y),"corner"==e.target.controlType?(l.scaleX=t*startSX,l.scaleY=t*startSY):(l.scaleX="e-resize"==e.target.cu?t*startSX:startSX,l.scaleY="n-resize"==e.target.cu?t*startSY:startSY),be(),Ve.x=e.stageX,Ve.y=e.stageY,z&&(Ne.x=e.stageX,Ne.y=e.stageY),!frame.ctrlKey||"side"==e.target.controlType){var o=e.target.op.parent.localToLocal(e.target.op.x,e.target.op.y,l.parent);l.x-=(o.x-Me.x)*kt.sign(K)*kt.sign(l.scaleX),l.y-=(o.y-Me.y)*kt.sign(Z)*kt.sign(l.scaleY)}(be(),l.transformControls.events)&&Ke(e,e.target.controlType)}function Ue(e,t){ye();var o=e?e.target.controlType:"move";t&&(o="reset"),z&&Ne.removeFrom(S),Ke(e,o,!0),S.update()}function Ke(e,t,o,n){null==n&&(n=!0);var r=!1;_e=null,"move"==t?(l.x==tt.x&&l.y==tt.y||((_e=new createjs.Event("transformed")).transformType="move"),n&&(r=we.hitTestPoint(e.stageX,e.stageY))):"corner"==t?(l.scaleX==tt.scaleX&&l.scaleY==tt.scaleY||((_e=new createjs.Event("transformed")).transformType="size"),n&&(r=$.hitTestPoint(e.stageX,e.stageY))):"side"==t?(l.scaleX==tt.scaleX&&l.scaleY==tt.scaleY||((_e=new createjs.Event("transformed")).transformType="stretch"),n&&(r=ee.hitTestPoint(e.stageX,e.stageY)||te.hitTestPoint(e.stageX,e.stageY))):"rotate"==t?(l.rotation!=tt.rotation&&((_e=new createjs.Event("transformed")).transformType="rotate"),n&&(r=oe.hitTestPoint(e.stageX,e.stageY))):"reg"==t?l.regX==tt.regX&&l.regY==tt.regY||((_e=new createjs.Event("transformed")).transformType="reg"):(_e=new createjs.Event("transformed")).transformType="reset"==t?"reset":"unknown",n&&!r&&(Ve.removeFrom(S),frame.canvas.style.cursor="default",l.cursor=He),_e&&(_e.pressup=o,l.dispatchEvent(_e))}function Ze(e){Fe||(Ve.stage?S.setChildIndex(Ve,S.getChildIndex(q)):Ve.addTo(S,S.getChildIndex(q)+1),Ne.addTo(S,1),Ve.x=e.stageX,Ve.y=e.stageY,Ne.x=e.stageX,Ne.y=e.stageY,l.getConcatenatedMatrix().decompose(E),E.rotation||(E.rotation=0),re.rotation=E.rotation*kt.sign(K*Z)*kt.sign(l.scaleX*l.scaleY)+ae[e.target.cu]+se,"side"!=e.target.controlType&&K*Z<0&&(re.rotation+=90),S.update(),Xe&&S.off("stagemousemove",Xe),Xe=S.on("stagemousemove",function(e){Ve.x=e.stageX,Ve.y=e.stageY,S.update()}))}function Qe(e){S.off("stagemousemove",Xe),Fe||(l.cursor=He,Ve.removeFrom(S),Ne.removeFrom(S),S.update())}function Je(){if(s){var e=H.numChildren-1;"Keyboard"==H.getChildAt(e).type&&e--,H.setChildIndex(l,e),$e()}}function $e(){if(H==S)q.removeFrom(),S.addChildAt(q,S.getChildIndex(l)+1);else{for(var e=H;e.parent&&e.parent!=S;)e=e.parent;q.stage?S.setChildIndex(q,S.getChildIndex(e)+1):S.addChildAt(q,S.getChildIndex(e)+1)}}$.on("mousedown",Ge),$.on("pressmove",qe),$.on("pressup",Ue),ee.on("mousedown",Ge),ee.on("pressmove",qe),ee.on("pressup",Ue),te.on("mousedown",Ge),te.on("pressmove",qe),te.on("pressup",Ue),oe.on("mousedown",Ge),oe.on("pressmove",function(e){var t=180*Math.atan2(e.stageY-Le,e.stageX-De)/Math.PI;frame.shiftKey?l.rot(45*Math.round((Be+(t-Ie)*kt.sign(K)*kt.sign(l.scaleX))/45)):l.rot(Be+(t-Ie)*kt.sign(K)*kt.sign(l.scaleX));be(),Ve.x=e.stageX,Ve.y=e.stageY,z&&(l.getConcatenatedMatrix().decompose(E),E.rotation||(E.rotation=0),re.rotation=E.rotation*kt.sign(K*Z)*kt.sign(l.scaleX*l.scaleY)+ae[e.target.cu]+se,"side"!=e.target.controlType&&K*Z<0&&(re.rotation+=90),Ne.x=e.stageX,Ne.y=e.stageY);if(be(),l.transformControls.events){var o=e.target.controlType;Ke(e,o,null,!1)}}),oe.on("pressup",Ue),D.drag(),D.on("mousedown",Je),D.on("pressup",function(e){if(!frame.ctrlKey){for(var t=0;t<F.length;t++)if(kt.dist(D.x,D.y,F[t].x,F[t].y)<b){D.x=F[t].x,D.y=F[t].y;break}kt.dist(D.x,D.y,pMid.x,pMid.y)<b&&(D.x=pMid.x,D.y=pMid.y)}var o=l.rotation,n=l.globalToLocal(D.x,D.y),r=H.globalToLocal(D.x,D.y);l.reg(n.x,n.y),l.rotation=0,l.x=l.x+r.x-l.x,l.y=l.y+r.y-l.y,l.rotation=o,be(),xe(),Ue(e),S.update()});var et=!0;W=z?"none":"move",we.drag({overCursor:W,dragCursor:W,onTop:!1}),we.controlType="move",z&&(we.on("mouseover",function(e){if(Fe||!z||!et)return;ne.addTo(q).pos({x:e.stageX,y:e.stageY,reg:!0}),S.update(),Re&&S.off("stagemousemove",Re);Re=S.on("stagemousemove",function(e){ne.x=e.stageX,ne.y=e.stageY,S.update()})}),we.on("mouseout",function(){if(S.off("stagemousemove",Re),Fe)return;ne.removeFrom(q),S.update()})),we.on("mousedown",Je),we.on("pressmove",function(e){if(l.transformControls.visible){var t=H.globalToLocal(we.x,we.y);if(l.x=t.x,l.y=t.y,be(),l.transformControls.events){Ke(e,"move")}}}),we.on("pressup",function(e){l.transformControls.visible&&Ue(e)});var tt,ot=S.on("stagemouseup",function(){Fe=!1,we.mouseEnabled=!0,et||l.x==tt.x&&l.y==tt.y||((_e=new createjs.Event("transformed")).transformType="move",l.dispatchEvent(_e)),et=!0,we.visible=!0,We&&!frame.ctrlKey&&1<w&&(l.rotation=Math.round(l.rotation/w)*w,be()),xe(),we.mouseEnabled=!0,We=!1,S.update()});function nt(){tt={x:l.x,y:l.y,rotation:l.rotation,regX:l.regX,regY:l.regY,scaleX:l.scaleX,scaleY:l.scaleY}}nt();var rt,it=l.on("mousedown",nt);q.on("mousedown",nt);q.addChild(O),t&&q.addChild(we),n&&q.addChild($),e&&q.addChild(ee),o&&q.addChild(te),r&&q.addChild(oe),q.addChild(D),t&&(l.drag({overCursor:"pointer",dragCursor:"pointer",onTop:!1,removeTweens:!1}),rt=l.on("pressmove",function(){be(),xe(),ye()}));var at=i;return l.transformControls={visible:a,events:C,ghost:!zot(k),ghostEnabled:!zot(k),show:function(){return s&&Je(),$e(),l.toggled=!0,l.transformControls.visible=!0,j.parent&&j.removeFrom(),S.update(),l},hide:function(){if(l.transformControls.ghost)var e=S.getChildIndex(q);return S.removeChild(q),l.transformControls.ghost&&l.transformControls.ghostEnabled&&S.addChildAt(j,e),l.toggled=!1,l.transformControls.visible=!1,z&&(Xe&&S.off("stagemousemove",Xe),Re&&S.off("stagemousemove",Re),Fe=!1,Ve.removeFrom(S),Ne.removeFrom(S)),t||(l.cursor=He),S.update(),l},remove:function(e){e||l.transformControls.hide(),toggle=!1,t&&(l.noDrag(),l.off("pressmove",rt))},add:function(e){e||l.transformControls.show(),toggle=at,t&&(l.drag({overCursor:"pointer",dragCursor:"pointer",onTop:!1,removeTweens:!1}),rt=l.on("pressmove",rt))},allowToggleOn:function(){toggle=at=!0,Ce=q.on("mousedown",Ce),ke=l.on("mousedown",ke),Ye=S.on("stagemousedown",Ye)},allowToggleOff:function(){toggle=at=!1,q.off("mousedown",Ce),l.off("mousedown",ke),S.off("stagemousedown",Ye)},disable:function(){q.mouseChildren=!1,q.mouseEnabled=!1,t&&(l.noDrag(),l.off("pressmove",rt))},enable:function(){q.mouseChildren=!0,q.mouseEnabled=!0,t&&(l.drag({overCursor:"pointer",dragCursor:"pointer",onTop:!1,removeTweens:!1}),rt=l.on("pressmove",rt))},recordData:function(e){var t={type:l.type,index:H.getChildIndex(l),x:l.x,y:l.y,scaleX:l.scaleX,scaleY:l.scaleY,rotation:l.rotation,skewX:l.skewX,skewY:l.skewY,regX:l.regX,regY:l.regY,controls:l.transformControls.visible};return e?JSON.stringify(t):t},setData:function(e,t){if(!zot(e)){t&&(e=JSON.parse(e));e.controls;delete e.controls;var o=e.index;for(var n in zot(o)&&(o=0),delete e.index,e)l[n]=e[n];return timeout(90,function(){be(),xe(),ye(),H.setChildIndex(l,o),l.transformControls.visible&&"Layer"!=l.type?l.transformControls.show():l.transformControls.hide(),!l.transformControls.ghost||l.transformControls.ghostEnabled||l.transformControls.visible||S.addChild(j)}),l}},hideGhost:function(){l.transformControls.ghost=!1,j.removeFrom()},showGhost:function(){if(l.transformControls.ghost=!0,l.transformControls.ghostEnabled&&!l.transformControls.visible){for(var e=H;e.parent&&e.parent!=S;)e=e.parent;j.stage?S.setChildIndex(j,S.getChildIndex(e)+1):S.addChildAt(j,S.getChildIndex(e)+1)}},addGhost:function(){0<T?(l.transformControls.ghostEnabled=!0,l.transformControls.showGhost()):zon&&zog("ZIM transform() - ghostWidth must be > 0 when making transform")},removeGhost:function(){l.transformControls.ghostEnabled=!1,l.transformControls.hideGhost()},resize:function(e){if(H=l.parent,be(),xe(),ye(),a&&l.transformControls.show(),e){var t=new createjs.Event("transformed");t.pressup=!0,t.transformType="resize",l.dispatchEvent(t)}return l},dispose:function(){l.transformControls.hide(),toggle=!1,t&&(l.noDrag(),l.off("pressmove",rt)),q.removeAllEventListeners(),ke&&l.off("mousedown",ke),Ce&&l.off("mousedown",Ce),Ye&&S.off("stagemousedown",Ye),Xe&&S.off("stagemousemove",Xe),Re&&S.off("stagemousemove",Re),ot&&S.off("stagemouseup",ot),it&&l.off("mousedown",it),rt&&l.off("pressmove",rt),q=Ve=Ne=null,l.transformControls=null},scaleControls:$,stretchXControls:ee,stretchYControls:te,rotateControls:oe},l.toggle=function(e){return!0===e?l.transformControls.show():!1===e?l.transformControls.hide():l.transformControls.visible?l.transformControls.hide():l.transformControls.show(),l},l.transformControls.ghost&&(l.transformControls.toggleGhost=function(e){return!0===e?l.transformControls.showGhost():!1===e?l.transformControls.hideGhost():l.transformControls.visible?l.transformControls.hideGhost():l.transformControls.showGhost(),l}),a?l.transformControls.show():!P&&l.transformControls.ghost&&l.transformControls.showGhost(),l},kt.gesture=function(C,e,t,s,o,k,T,c,n,u,d,A,r,i,a,l){var h;if(h=zob(kt.gesture,arguments,"obj, move, scale, rotate, boundary, minScale, maxScale, snapRotate, localBounds, slide, slideEffect, regControl, onTop, surround, circularBounds, rect"))return h;if(z_d("34.5"),!zot(C)&&C.on){var g,p;if(zot(e)&&(e=!0),zot(t)&&(t=!0),zot(s)&&(s=!0),zot(n)&&(n=!1),zot(c)&&(c=1),zot(u)&&(u=!1),zot(d)&&(d=5),zot(A)&&(A=!1),zot(r)&&(r=!0),zot(i)&&(i=!1),i&&s&&(i=l=null,zon&&zog("ZIM Gesture() - does not support surround when rotate is true")),zot(a)&&(a=!1),zot(o)&&!zot(l)&&(o=l),zot(C.zimMaskDynamic)||C.zimMaskApply(),!C.zimTouch){var P,B,I,S,E,M,O,f,j=new kt.Damp(C.scaleX,.05),D=new kt.Damp(C.scaleY,.05),L=C.scaleX/C.scaleY;if(C.zimTouch={move:e,scale:t,rotate:s,pointers:{},checkBounds:function(e,t){if(C.zimTouch.boundary){var o=C.zimTouch.boundary,n=C.parent.localToLocal(e,t,C.parent);t=i?(e=Math.min(o.x,Math.max(o.x+o.width,n.x)),Math.min(o.y,Math.max(o.y+o.height,n.y))):(e=Math.max(o.x,Math.min(o.x+o.width,n.x)),Math.max(o.y,Math.min(o.y+o.height,n.y))),e=(n=C.parent.globalToLocal(e,t)).x,t=n.y}return{x:e,y:t}}},o){C.zimTouch.boundary=o,n&&(C.zimTouch.boundary=kt.boundsToGlobal(C.parent,o)),C.zimTouch.boundaryStartX=C.zimTouch.boundary.x,C.zimTouch.boundaryStartY=C.zimTouch.boundary.y,C.zimTouch.boundaryStartW=C.zimTouch.boundary.width,C.zimTouch.boundaryStartH=C.zimTouch.boundary.height;var m=C.zimTouch.checkBounds(C.x,C.y);C.x=m.x,C.y=m.y}u&&(slideSlice=10,slideTotal=5,p=0,g=[],C.zimTouch.slideInterval=kt.interval(slideSlice,function(){g[p++%slideTotal]=[C.x,C.y]}),C.zimTouch.slideInterval.pause(),C.animate({x:C.x,y:C.y},10,"quadOut")),C.zimTouch.mousedown=C.on("mousedown",function(e){if(zot(f)?f=1:f++,r){var t=C.parent.numChildren-1;"Keyboard"==C.parent.getChildAt(t).type&&t--,C.parent.setChildIndex(C,t),C.ZIMoutlineShape&&C.outline()}A||(O=null,B=C.scaleX,I=C.scaleY,S=C.rotation,E=C.regX,M=C.regY,C.reg(0,0),P=C.getMatrix(),C.regX=E,C.regY=M);var o="id"+Math.abs(e.pointerID+1),n=C.parent.globalToLocal(e.stageX,e.stageY);C.zimTouch.pointers[o]={startX:n.x,startY:n.y,x:n.x,y:n.y},(C.zimTouch.move||C.zimTouch.rotate)&&(C.zimTouch.total=0,kt.loop(C.zimTouch.pointers,function(e){C.zimTouch.total++})),u&&1==C.zimTouch.total&&C.zimTouch.slideInterval.pause(!1),z()}),C.zimTouch.pressmove=C.on("pressmove",function(e){var t="id"+Math.abs(e.pointerID+1),o=C.parent.globalToLocal(e.stageX,e.stageY);C.zimTouch.pointers[t].x=o.x,C.zimTouch.pointers[t].y=o.y;var n,r,i=0,a=0,l=0,s=0;kt.loop(C.zimTouch.pointers,function(e,t){i+=t.x-t.startX,a+=t.y-t.startY,l+=t.x,s+=t.y}),n=i/C.zimTouch.total,r=a/C.zimTouch.total,i=C.zimTouch.startX+n,a=C.zimTouch.startY+r,l/=C.zimTouch.total,s/=C.zimTouch.total;var c={x:C.x,y:C.y,scaleX:C.scaleX,scaleY:C.scaleY,rotation:C.rotation};if(C.zimTouch.move){var u=C.zimTouch.checkBounds(i,a);c.x=u.x,c.y=u.y}if(2==C.zimTouch.pair.length){var d=C.zimTouch.pair[0],h=C.zimTouch.pair[1];if(C.zimTouch.scale){var g=Math.sqrt(Math.pow(h.startX-d.startX,2)+Math.pow(h.startY-d.startY,2)),p=Math.sqrt(Math.pow(h.x-d.x,2)+Math.pow(h.y-d.y,2)),f=C.zimTouch.startSX+(p/g-1),m=C.zimTouch.startSY+(p/g-1);c.scaleX=f,c.scaleY=m,c.scaleX=j.convert(f),c.scaleY=D.convert(m);var z=!zot(k)&&Math.min(f,m)<k,v=!zot(T)&&Math.max(f,m)>T;(z||v)&&(z?1<L?(c.scaleY=k,c.scaleX=k*L):(c.scaleX=k,c.scaleY=k/L):v&&(1<L?(c.scaleX=T,c.scaleY=T/L):(c.scaleY=T,c.scaleX=T*L)),j.immediate(c.scaleX),D.immediate(c.scaleY))}if(C.zimTouch.rotate){var y=Math.atan2(d.startY-h.startY,d.startX-h.startX)*(180/Math.PI),b=Math.atan2(d.y-h.y,d.x-h.x)*(180/Math.PI)-y;c.rotation=C.zimTouch.startR+b}if(A)C.scaleX=c.scaleX,C.scaleY=c.scaleY,C.rotation=c.rotation,C.zimTouch.move&&(C.x=c.x,C.y=c.y);else{C.reg(0,0);var w=C.parent.localToGlobal(l,s);l=w.x,s=w.y;var x=zot(O)?C.globalToLocal(l,s):C.globalToLocal(O.x,O.y);P.clone().translate(x.x,x.y).rotate(c.rotation-S).scale(c.scaleX/B,c.scaleY/I).translate(-x.x,-x.y).decompose(C),C.zimTouch.move&&(C.x+=n,C.y+=r),O=C.localToGlobal(x.x,x.y),C.reg(E,M)}C.zimTouch.scale&&C.dispatchEvent("scale"),C.zimTouch.rotate&&C.dispatchEvent("rotate"),C.zimTouch.move&&C.dispatchEvent("move")}else C.x=c.x,C.y=c.y,C.zimTouch.move&&C.dispatchEvent("move");"Tag"!=C.type&&"TextArea"!=C.type&&"Loader"!=C.type||C.resize(),C.ZIMoutlineShape&&C.outline(),C.getStage&&C.stage&&C.stage.update()});function z(){C.zimTouch.pair=[],kt.loop(C.zimTouch.pointers,function(e,t,o){t.startX=t.x,t.startY=t.y,o<=1&&C.zimTouch.pair.push(t)}),C.zimTouch.startX=C.x,C.zimTouch.startY=C.y,C.zimTouch.startSX=C.scaleX,C.zimTouch.startSY=C.scaleY,C.zimTouch.startR=C.rotation}function v(){var e=C.localToGlobal(C.regX,C.regY);if(a)var t=C.parent.localToGlobal(C.x-C.width/2,C.y-C.height/2),o=C.parent.localToGlobal(C.x+C.width/2,C.y+C.height/2),n={x:t.x,y:t.y,width:o.x-t.x,height:o.y-t.y};else n=C.boundsToGlobal();var r={x:C.zimTouch.boundaryStartX+e.x-n.x,y:C.zimTouch.boundaryStartY+e.y-n.y,width:C.zimTouch.boundaryStartW-n.width,height:C.zimTouch.boundaryStartH-n.height};C.gestureBoundary(r,!1)}C.on("mousedown",function(){var e=1;C.stage.on("stagemousedown",function(){e++}),C.stage.on("stagemouseup",function(){0==--e&&setTimeout(function(){C.zimTouch&&(C.zimTouch.total=0),C.zimTouch&&(C.zimTouch.pointers={}),f=null},50)})},null,!0),C.zimTouch.pressup=C.on("pressup",function(e){var t="id"+Math.abs(e.pointerID+1);if(delete C.zimTouch.pointers[t],(C.zimTouch.move||C.zimTouch.rotate)&&C.zimTouch.total--,s&&!zot(c)&&0==C.zimTouch.total&&(0<c?C.rotation=Math.round(C.rotation/c)*c:0==c&&(C.rotation=Math.round(C.rotation))),u&&0==C.zimTouch.total&&1==f){C.zimTouch.slideInterval.pause();var o=g[(p+1)%g.length],n=g[p%g.length],r=C.x+(o[0]-n[0])*d,i=C.y+(o[1]-n[1])*d,a=C.zimTouch.checkBounds(r,i),l=slideTotal*slideSlice*d*Math.min((C.x-a.x)/(C.x-r)||1,(C.y-a.y)/(C.y-i)||1);C.animate({x:a.x,y:a.y},l,"quadOut",function(){C.dispatchEvent("slidestop")})}0==C.zimTouch.total&&(f=null),C.getStage&&C.stage&&C.stage.update(),z()}),o&&(v(),C.on("move",v))}return C}},kt.noGesture=function(e,t,o,n){var r;return(r=zob(kt.noGesture,arguments,"obj, move, scale, rotate"))?r:(z_d("34.6"),!zot(e)&&e.on&&e.zimTouch?(zot(t)&&(t=!0),zot(o)&&(o=!0),zot(n)&&(n=!0),e.zimTouch.move=!t,e.zimTouch.scale=!o,e.zimTouch.rotate=!n,e.zimTouch.move||e.zimTouch.scale||e.zimTouch.rotate||(e.off("mousedown",e.zimTouch.mousedown),e.off("pressmove",e.zimTouch.pressmove),e.off("pressup",e.zimTouch.pressup),delete e.zimTouch),e):void 0)},kt.gestureBoundary=function(e,t,o){if(z_d("34.7"),!zot(e)&&e.on&&!zot(t)&&e.zimTouch){e.zimTouch.localBounds&&e.parent?e.zimTouch.boundary=kt.boundsToGlobal(e.parent,t):e.zimTouch.boundary=t,zot(o)&&(o=!0),o&&(e.zimTouch.boundaryStartX=t.x,e.zimTouch.boundaryStartY=t.y,e.zimTouch.boundaryStartW=t.width,e.zimTouch.boundaryStartH=t.height);var n=e.zimTouch.checkBounds(e.x,e.y);return e.x=n.x,e.y=n.y,e}},kt.addPhysics=function(e,t,o,n,r,i,a,l,s,c,u,d){var h;if(h=zob(kt.addPhysics,arguments,"obj, dynamic, contract, shape, friction, linear, angular, density, restitution, maskBits, categoryBits, physics"))return h;if(z_d("34.8"),zot(d)){if("undefined"==typeof zimPhysics)return zon&&zog("ZIM Physics module must be imported"),e;zot(zimDefaultPhysics)&&(zimDefaultPhysics=new kt.Physics),d=zimDefaultPhysics}e.physics=d;var g="rectangle";return"Circle"==e.type||"Dial"==e.type?g="circle":"Triangle"==e.type&&(g="triangle"),zot(n)&&(n=g),function(g,e,t,o,n,r,i,a,l,s,c){z_d("69.97"),zot(t)&&(t=0);"rectangle"==o?g.body=g.physics.makeRectangle(g.width-t,g.height-t,e,n,i,a,l,s,c,r):"circle"==o?g.body=g.physics.makeCircle(g.width/2-t,e,n,i,a,l,s,c,r):"triangle"==o&&(zot(g.a)&&(g.a=g.width,g.b=g.c=Math.sqrt(Math.pow(g.a/2,2)+Math.pow(g.height,2))),g.body=g.physics.makeTriangle(g.a-t,g.b-t,g.c-t,e,n,i,a,l,s,c,r));function u(){zimContactListener=new b2ContactListener,p=new kt.Dictionary(!0),f=new kt.Dictionary(!0),zimContactListener.BeginContact=function(e){var t=p.at(e.m_fixtureB.GetBody());t?t(e.m_fixtureA.GetBody().zimObj,e.m_fixtureA.GetBody()):(t=p.at(e.m_fixtureA.GetBody()))&&t(e.m_fixtureB.GetBody().zimObj,e.m_fixtureB.GetBody())},zimContactListener.EndContact=function(e){var t=f.at(e.m_fixtureB.GetBody());t?t(e.m_fixtureA.GetBody().zimObj,e.m_fixtureA.GetBody()):(t=f.at(e.m_fixtureB.GetBody().zimObj,e.m_fixtureB.GetBody()))&&t(e.m_fixtureB.GetBody())},g.physics.world.SetContactListener(zimContactListener)}g.body.x=g.x,g.body.y=g.y,g.body.rotation=g.rotation,g.physics.addMap(g.body,g),g.impulse=function(e,t,o,n){zot(e)&&(e=0),zot(t)&&(t=0);var r=g.body.GetWorldCenter();return zot(o)&&(o=r.x*g.physics.scale),zot(n)&&(n=r.y*g.physics.scale),g.body.ApplyImpulse(new b2Vec2(e,t),new b2Vec2(o/g.physics.scale,n/g.physics.scale)),g},g.force=function(e,t,o,n){zot(e)&&(e=0),zot(t)&&(t=0);var r=g.body.GetWorldCenter();return zot(o)&&(o=r.x*g.physics.scale),zot(n)&&(n=r.y*g.physics.scale),g.body.ApplyForce(new b2Vec2(e,t),new b2Vec2(o/g.physics.scale,n/g.physics.scale)),g},g.spin=function(e){return zot(e)&&(e=10),g.body.ApplyTorque(1e3*e),g},g.torque=function(e){return zot(e)&&(e=10),g.body.ApplyTorque(e),g},g.follow=function(e,t,o,n,r,i,a,l,s,c,u,d){var h;return(h=zob(g.follow,arguments,"damp, dampY, leftOffset, rightOffset, upOffset, downOffset, offsetDamp, offsetDampY, horizontal, vertical, borderLock, borderOriginal"))?h:(g.physics.follow(g,e,t,o,n,r,i,a,l,s,c,u,d),g)},g.noFollow=function(){return g.physics.follow(null),g},g.control=function(e,t,o,n,r){var i;return(i=zob(g.control,arguments,"type, speed, speedY, horizontal, vertical"))?i:(g.physics.control(g,e,t,o,n,r),g)},g.noControl=function(){return g.physics.noControl(g),g},g.sleep=function(){return zog(g.body),g.body.SetAwake(!1),g},g.wake=function(){return g.body.SetAwake(!0),g},g.contact=function(e){return zimContactListener||u(),p.add(g.body,e),g},g.noContact=function(){return p.remove(g.body),g},g.contactEnd=function(e){return zimContactListener||u(),f.add(g.body,e),g},g.noContactEnd=function(){return f.remove(g.body),g},Object.defineProperty(g,"dynamic",{get:function(){return 2==g.body.GetType()},set:function(e){g.body.SetType(1==e?2:0)}})}(e,t,o,n,r,i,a,l,s,c,u),e},kt.removePhysics=function(e){return z_d("34.85"),zot(e.physics)||(e==e.physics.followObj&&e.physics.follow(null),e.physics.remove(e.body),e.follow=e.noFollow=e.control=e.noControl=e.sleep=e.wake=null,e.physics=e.impulse=e.force=e.spin=e.torque=null),e},kt.hitTestPoint=function(e,t,o,n){if(z_d("35"),!e.stage)return!1;if(!zot(e)&&e.globalToLocal){zot(n)&&(n=!0);var r=e.globalToLocal(t,o),i=e.getBounds();if(n&&i){if(r.x>i.x+i.width||r.x<i.x)return!1;if(r.y>i.y+i.height||r.y<i.y)return!1}return e.hitTest(r.x,r.y)}},kt.hitTestReg=function(e,t,o){if(z_d("36"),!e.stage||!t.stage)return!1;if(!zot(e)&&!zot(t)&&e.localToLocal&&t.localToLocal){zot(o)&&(o=!0);var n=t.localToLocal(t.regX,t.regY,e),r=e.getBounds();if(o&&r){if(n.x>r.x+r.width||n.x<r.x)return!1;if(n.y>r.y+r.height||n.y<r.y)return!1}return e.hitTest(n.x,n.y)}},kt.hitTestRect=function(e,t,o,n){if(z_d("37"),!e.stage||!t.stage)return!1;if(!zot(e)&&!zot(t)&&e.hitTest&&t.getBounds){zot(o)&&(o=0),zot(n)&&(n=!0);var r=t.getBounds();if(r){var i=e.getBounds();if(n&&i&&!kt.hitTestBounds(e,t))return!1;var a,l,s=r.x+r.width/2,c=r.y+r.height/2,u=t.localToLocal(s,c,e);if(e.hitTest(u.x,u.y))return!0;for(var d=0;d<=o;d++){if(a=r.width*(d+1)/(o+1),l=r.height*(d+1)/(o+1),u=t.localToLocal(r.x+a,r.y,e),e.hitTest(u.x,u.y))return!0;if(u=t.localToLocal(r.x+r.width,r.y+l,e),e.hitTest(u.x,u.y))return!0;if(u=t.localToLocal(r.x+r.width-a,r.y+r.height,e),e.hitTest(u.x,u.y))return!0;if(u=t.localToLocal(r.x,r.y+r.height-l,e),e.hitTest(u.x,u.y))return!0}}else zog("zim methods - hitTestRect():\n please setBounds() on param b object")}},kt.hitTestCircle=function(e,t,o,n){if(z_d("38"),e.stage&&t.stage&&!zot(e)&&!zot(t)&&e.hitTest&&t.getBounds){zot(o)&&(o=8),zot(n)&&(n=!0);var r=t.getBounds();if(r){var i=e.getBounds();if(n&&i&&!kt.hitTestBounds(e,t))return!1;var a=r.x+r.width/2,l=r.y+r.height/2,s=t.localToLocal(a,l,e);if(e.hitTest(s.x,s.y))return!0;for(var c,u,d,h=(r.width+r.height)/2/2,g=0;g<o;g++)if(c=g/o*2*Math.PI,u=a+h*Math.cos(c),d=l+h*Math.sin(c),s=t.localToLocal(u,d,e),e.hitTest(s.x,s.y))return!0}else zog("zim methods - hitTestCircle():\n please setBounds() on param b object")}},kt.hitTestCircles=function(e,t,o){if(z_d("38.5"),e.stage&&t.stage&&!zot(e)&&!zot(t)&&e.hitTest&&e.getBounds&&t.getBounds){var n=e.getBounds(),r=t.getBounds();if(n&&r){zot(o)&&(o=0);var i=e.localToGlobal(n.x+n.width/2,n.y+n.height/2),a=t.localToGlobal(r.x+r.width/2,r.y+r.height/2),l=e.getConcatenatedMatrix(),s=t.getConcatenatedMatrix();scale1X=Math.sqrt(l.a*l.a+l.c*l.c),scale1Y=Math.sqrt(l.b*l.b+l.d*l.d),scale2X=Math.sqrt(s.a*s.a+s.c*s.c),scale2Y=Math.sqrt(s.b*s.b+s.d*s.d);var c=Math.sqrt(Math.abs(Math.pow(i.x-a.x,2)+Math.pow(i.y-a.y,2)));return n.width*Math.max(scale1X,scale1Y)/2+r.width*Math.max(scale2X,scale2Y)/2>=c-o}zog("zim methods - hitTestCircles():\n please setBounds() on both objects")}},kt.hitTestBounds=function(e,t,o,n){if(z_d("39"),e.stage&&t.stage&&!zot(e)&&!zot(t)&&e.getBounds&&t.getBounds){var r=!1;n&&n.graphics&&(r=!0);var i=e.getBounds(),a=t.getBounds();if(i&&a){zot(o)&&(o=0);var l,s,c=kt.boundsToGlobal(e),u=kt.boundsToGlobal(t);if(r){var d=n.graphics;d.c(),d.ss(1).s("blue"),d.r(c.x,c.y,c.width,c.height),d.s("green"),d.r(u.x,u.y,u.width,u.height),n.stage.update()}return s=u,!((l=c).x>=s.x+s.width+o||l.x+l.width+o<=s.x||l.y>=s.y+s.height+o||l.y+l.height+o<=s.y)}zog("zim methods - hitTestBounds():\n please setBounds() on both objects")}},kt.hitTestGrid=function(e,t,o,n,r,i,a,l,s,c,u,d,h){if(z_d("41"),!e.stage)return!1;if(!zot(e)&&!d){var g=e.globalToLocal(i,a);i=g.x,a=g.y}zot(l)&&(l=0),zot(s)&&(s=0),zot(c)&&(c=0),zot(u)&&(u=0);var p=t/n,f=o/r,m=Math.min(n-1,Math.max(0,Math.floor((i-l)/p))),z=Math.min(r-1,Math.max(0,Math.floor((a-s)/f)));if(!(p*(m+1)-c<i-l||i-l<p*m||f*(z+1)-u<a-s||a-s<f*z)){var v=z*n+m;return zot(h)||"index"==h?v:"col"==h?m:"row"==h?z:"array"==h?[v,m,z]:void 0}},kt.animate=function(s,e,n,c,r,i,a,t,o,l,u,d,h,g,p,f,m,z,v,y,b,w,x,C,k,T,A,P,B,I,S,E,M,O,j,D,L,Y,X,R,_){var W;if(W=zob(kt.animate,arguments,"target, props, time, ease, call, params, wait, waitedCall, waitedParams, loop, loopCount, loopWait, loopCall, loopParams, loopWaitCall, loopWaitParams, rewind, rewindWait, rewindCall, rewindParams, rewindWaitCall, rewindWaitParams, sequence, sequenceCall, sequenceParams, sequenceReverse, ticker, cjsProps, css, protect, override, from, set, id, events, sequenceTarget, dynamic, drag, clamp, startPaused, obj"))return W;if(z_d("45"),0==kt.ANIMATE||!window.zns&&!ANIMATE)return s;if(zot(e)&&!zot(_)&&(e=_),zot(_=e))return zon&&zog("animate() - need props"),s;s=kt.Pick.choose(s),n=kt.Pick.choose(n),c=kt.Pick.choose(c),a=kt.Pick.choose(a),u=kt.Pick.choose(u),d=kt.Pick.choose(d),m=kt.Pick.choose(m),z=kt.Pick.choose(z),T=kt.Pick.choose(T),E=kt.Pick.choose(E),M=kt.Pick.choose(M);var F={override:!zot(s)&&!zot(s.zimX)&&!zot(_.x)||!zot(s)&&!zot(s.zimY)&&!zot(_.y)};if(zot(l)||(F.loop=l),zot(u)||(F.count=u),zot(d)||(F.loopWait=d),zot(h)||(F.loopCall=h),zot(f)||(F.loopWaitParams=f),zot(p)||(F.loopWaitCall=p),zot(g)||(F.loopParams=g),zot(m)||(F.rewind=m),zot(z)||(F.rewindWait=z),zot(v)||(F.rewindCall=v),zot(y)||(F.rewindParams=y),zot(b)||(F.rewindWaitCall=b),zot(w)||(F.rewindWaitParams=w),zot(e)||(F=kt.merge(F,P)),P=F,zot(x)&&(x=0),0<x&&s.addChild){for(var H=[],V=0;V<s.numChildren;V++)H.push(s.getChildAt(V));D=s,s=H}if(s instanceof Array){T&&s.reverse();var N=0;for(V=0;V<s.length;V++)!function(){var e,o=V;if(E)for(var t in s[o].zimObj={},_)e=kt.Pick.choose(_[t]),s[o].zimObj[t]=s[o][t],s[o][t]=e;else for(var t in s[o].zimObj={},_)s[o].zimObj[t]=kt.Pick.choose(_[t]);setTimeout(function(){var e=s[N];if(N++,kt.animate(e,e.zimObj,n,c,r,i,a,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,A,kt.copy(P),B,I,S,null,M,O,j,D,L,Y,X,R,_),o==s.length-1&&C){var t=(n||1e3)+(a||0);P&&P.rewind&&(t+=(n||1e3)+(P.rewindWait?P.rewindWait:0)),P&&P.loop&&P.loopWait&&(t+=P.loopWait),setTimeout(function(){C(k)},t)}},x*V)}();return D}var G,q,U,K=n;if(zot(K)&&(K=1e3),zot(c)&&(c="quadInOut"),zot(a)&&(a=0),zot(P)&&(P={override:!zot(s.zimX)&&!zot(_.x)||!zot(s.zimY)&&!zot(_.y)}),zot(i)&&(i=s),zot(A)&&(A=!0),zot(B)&&(B=!1),zot(I)&&(I=!1),zot(E)&&(E=!1),zot(M)&&(M={}),M.scale&&(M.scaleX=M.scaleY=M.scale,delete M.scale),zot(S)||(P.override=S),zot(Y)&&(Y=!1),zot(R)&&(R=!!Y),zot(L)&&(L=!1),zot(X)&&(X=!0),_ instanceof Array){var Z,Q=1;if(0==_.length)return this;function J(){for(var e,t,o=a,n=0,r=0;r<_.length;r++)if(!zot((e=_[r]).target)){zot(e.time)&&(e.time=K),o+=e.wait?e.wait:0,t=e.time,e.rewind&&(t=2*t+(e.rewindWait?e.rewindWait:0)),e.loop&&(t*=e.loopCount,t+=(e.loopCount-1)*(e.loopWait?e.loopWait:0));var i={target:e.target,obj:kt.copy(e.obj),wait:n+o,waitedCall:e.waitedCall,waitedParams:e.waitedParams,time:e.time,ease:e.ease,from:e.from,rewind:e.rewind,call:e.call,params:e.params,loop:e.loop,loopCount:e.loopCount,loopWait:e.loopWait,loopCall:e.loopCall,loopParams:e.loopParams,loopWaitCall:e.loopWaitCall,loopWaitParams:e.loopWaitParams,rewind:e.rewind,rewindWait:e.rewindWait,rewindCall:e.rewindCall,rewindParams:e.rewindParams,rewindWaitCall:e.rewindWaitCall,rewindWaitParams:e.rewindWaitParams,set:kt.copy(e.masterSet),override:!1,id:O};r==_.length-1&&$(i),kt.animate(i),n+=o+t,o=0}}function $(e){P.loop&&(!P.count||Q<P.count)?e.call=function(){function e(){for(var e=0;e<Z.objects.length;e++)Z.objects[e].set&&Z.objects[e].set(Z.values[e]);P.loopWaitCall&&"function"==typeof P.loopWaitCall&&P.loopWaitCall(P.loopWaitParams),J()}P.loopCall&&"function"==typeof P.loopCall&&P.loopCall(P.loopParams),P.loopWait?(zot(s.zimTweens)&&(s.zimTweens={}),G=s.zimTweens[O]=s.zimTween=createjs.Tween.get(s,{override:P.override}).wait(P.loopWait,!0).call(e)):e()}:e.call=function(){r&&"function"==typeof r&&r(i),yt(O)},Q++}return function(){var e=new kt.Dictionary;Z=new kt.Dictionary;for(var t=0;t<_.length;t++)if(oe=_[t],s||(s=oe.target),zot(oe.target)&&(oe.target=s),zot(oe.ease)&&(oe.ease=c),!zot(oe.target)){if(zot(oe.props)&&!zot(oe.obj)&&(oe.props=oe.obj),oe.obj=oe.props,oe.loop&&(zot(oe.loopCount)||oe.loopCount<=0)&&(oe.loopCount=0,_.splice(t+1,_.length)),zot(oe.obj.scale)||(oe.obj.scaleX=oe.obj.scaleY=oe.obj.scale,delete oe.obj.scale),oe.from){var o=e.at(oe.target);if(o){if(oe.set){var n=kt.copy(oe.obj),r=kt.merge(o,oe.set);oe.obj=ht(oe.target,oe.obj,r),oe.set=kt.merge(oe.set,n)}else oe.set=kt.copy(oe.obj),oe.obj=ht(oe.target,oe.obj,o);oe.from=!1}else e.add(oe.target,ht(oe.target,oe.obj,oe.set))}var i={};for(var a in oe.obj)i[a]=oe.set&&oe.set[a]?oe.set[a]:oe.target[a];zot(Z.at(oe.target))&&Z.add(oe.target,{});var l=kt.merge(Z.at(oe.target),i);Z.remove(oe.target),Z.add(oe.target,l),oe.masterSet=kt.copy(oe.set)}zot(s.zimTweens)&&(s.zimTweens={})}(),dt(),J(),s}if(_&&(_.x&&(s.zimX=!0),_.y&&(s.zimY=!0)),!zot(s)){var ee;if(s.pathRatio=s.percentComplete&&100!=Math.round(s.percentComplete)?s.percentComplete/100:0,B&&(A=!1),zot(s.zimTweens)&&(s.zimTweens={}),!B)if(s.stage)ee=s.stage;else{if(!zimDefaultFrame)return;ee=zimDefaultFrame.stage}if(zot(_.scale)||(_.scaleX=_.scaleY=kt.Pick.choose(_.scale),delete _.scale),s.setColorRange&&!zot(_.color)){var te=_.color;delete _.color,_.colorRange=1,s.setColorRange(s.color,te),s.colorRange=0}for(var oe in _){if(!s.zimBusy)break;s.zimBusy[oe]&&delete _[oe]}if(!kt.isEmpty(_)){s.paused=!1;var ne=s.mouseEnabled;(I||P.loop||P.rewind)&&(s.mouseEnabled=!1,setTimeout(function(){for(var e in s.zimBusy||(s.zimBusy={}),_)s.zimBusy[e]=!0;s.mouseEnabled=ne},70)),dt();var re,ie=["extra","zoom","speed","layer","fade"],ae={zoom:"Pen"==s.type?"size":"scale",speed:"percentSpeed",layer:"layer",fade:"alpha"};for(var V in _)0<=ie.indexOf(V)||(_[V]=kt.Pick.choose(_[V]));for(V in ie.shift(),M)M[V]=kt.Pick.choose(M[V]);for(V in P)"waitedCall"!=V&&"waitedParams"!=V&&"loopCall"!=V&&"rewindCall"!=V&&"loopWaitCall"!=V&&"rewindWaitCall"!=V&&(P[V]=kt.Pick.choose(P[V]));for(V in _)"string"==typeof _[V]&&(_[V]=s[V]+Number(_[V].replace(/\s/g,"")));for(V in M)"string"==typeof M[V]&&(M[V]=s[V]+Number(M[V].replace(/\s/g,"")));if(s.getBounds&&zot(s.percentCompleteCheck)&&(s.percentCompleteCheck=!0,Object.defineProperty(s,"percentComplete",{get:function(){return this.zimTween&&this.zimTween.duration?this.zimTween.position/this.zimTween.duration*100:0},set:function(e){this.zimTween&&(this.zimTween.startPaused=!1,L?zot(this.zimTween.currentTime)||(this.zimTween.currentTime=this.zimTween.currentTime-this.zimTween.position+e*this.zimTween.duration/100):this.zimTween.setPosition(Math.round(e*this.zimTween.duration/100)),ft())}})),!zot(_.path)&&_.path.segmentPoints){"Pen"==s.type&&(s.infinite=!0),s.zimOnPath=!0,zot(s.pathRatio)&&(s.pathRatio=0),zot(_.orient)&&(_.orient=_.path);var le=!(re=_.path).lockControls;delete _.path,_.pathRatio=1}E&&(_=ht(s,_,M,!0));s.percentComplete;var se,ce,ue,de,he,ge=!0,pe=!1,fe=!0,me=0,ze=!0;if(zot(_.redirect)||(ze=_.redirect,delete _.redirect),re){var ve,ye;le||(ve=kt.copy(re.segmentPoints),ye=kt.copy(re.segmentRatios));var be=re.getCurvePoint(s.pathRatio,ye,ve);if(s.parent&&be){var we=s.parent.globalToLocal(be.x,be.y);s.x=we.x,s.y=we.y}if(Y){s.cursor="pointer";var xe,Ce=s.percentComplete;R||s.paused;function ke(e){var t=re.getAdjacentSegmentData(me),o=t[0],n=t[1],r=re.globalToLocal(e.stageX,e.stageY),i=closestPointAlongCurve(r,o,20,!1,!0);i/=100;var a=re.segmentRatios;a.unshift(0);for(var l=[],s=a.length-2;0<=s;s--)l.unshift(a[s+1]-a[s]);var c=0;for(s=0;s<n.length;s++)c+=l[n[s]];var u=i*c,d=a[n[0]];newPP=1<d+u?d+u-1:d+u,newPP*=100,m&&(newPP/=2,G.position>G.duration/2&&(newPP=100-newPP)),Ce=constrain(newPP,0,99.5)}s.zimAnimateDragDown=s.on("mousedown",function(e){fe=!(ge=!1),setTimeout(function(){ge=!0},50),xe=G.forward,pe=!0,ke(e),Te.immediate(Ce)}),s.zimAnimateDragPress=s.on("pressmove",ke),s.zimAnimateDragUp=s.on("pressup",function(){0==s.paused&&(pe=!1),ge=!1,setTimeout(function(){ge=!0},50),!s.paused&&m&&xe!=G.forward&&ze&&(s.percentComplete=100-s.percentComplete)});var Te=new kt.Damp(Ce,.2),Ae=0;s.zimDragAnimateTicker=kt.Ticker.add(function(){if(Y)if(pe||fe&&1==s.paused){if("Blob"==re.type&&Math.abs(Ae-Ce)>(m?45:90)){var e=Ce;Te.immediate(e)}else e=Te.convert(Ce);.1<Math.abs(Ae-e)?(s.percentComplete=e,Ae=e):(s.percentComplete=Ae,fe=!1)}else fe=!1},ee)}}if(_.orient){if(!0===_.orient){var Pe=s.parent.localToGlobal(zot(_.x)?s.x:_.x,zot(_.y)?s.y:_.y);_.orient={x:Pe.x,y:Pe.y}}se=_.orient,delete _.orient;var Be,Ie=s.rotation;if(se!=re)Be=se.parent?se.parent.localToLocal(se.x,se.y,s.parent):s.parent.globalToLocal(se.x,se.y),s.rotation=kt.angle(s.x,s.y,Be.x,Be.y)+Ie}_.flip&&(ce=_.flip,delete _.flip,ue=s.scaleX),_.flipVertical&&(de=_.flipVertical,delete _.flipVertical,he=s.scaleY);var Se=s.x,Ee=s.y,Me=0;if(P.loop&&!zot(P.count)){Me=P.count,delete P.count;Q=1}var Oe,je=0;P.loopWait&&(je=P.loopWait,delete P.loopWait),P.loopCall&&(Oe=P.loopCall,delete P.loopCall);var De,Le=s;P.loopParams&&(Le=P.loopParams,delete P.loopParams),P.loopWaitCall&&(De=P.loopWaitCall,delete P.loopWaitCall);var Ye,Xe=s;if(P.loopWaitParams&&(Xe=P.loopWaitParams,delete P.loopWaitParams),P.rewind){if(c){var Re=c;-1==Re.indexOf("InOut")&&(-1!=Re.indexOf("Out")?Re=Re.replace("Out","In"):-1!=Re.indexOf("In")&&(Re=Re.replace("In","Out")))}var _e,We,Fe=0;if(delete P.rewind,P.rewindWait&&(Fe=P.rewindWait,delete P.rewindWait),P.rewindCall){_e=P.rewindCall;var He=P.rewindParams;zot(He)&&(He=s),delete P.rewindCall,delete P.rewindParams}function Ve(){_e&&"function"==typeof _e&&_e(He)}if(P.rewindWaitCall){We=P.rewindWaitCall;var Ne=P.rewindWaitParams;zot(Ne)&&(Ne=s),delete P.rewindWaitCall,delete P.rewindWaitParams}function Ge(){We&&"function"==typeof We&&We(Ne)}function qe(){var e=zt();s.set&&!E&&s.set(M),G=s.zimTweens[O]=s.zimTween=createjs.Tween.get(s,P).to(_,K,createjs.Ease[c]).call(Ge).wait(Fe,!0).call(Ve).to(e,K,createjs.Ease[Re]).call(mt).wait(je,!0).call(gt),vt()}0<a?G=s.zimTweens[O]=s.zimTween=createjs.Tween.get(s,{override:P.override}).wait(a,!0).call(function(){t&&"function"==typeof t&&t(zot(o)?s:o),qe()}):qe()}else{function Ue(){s.set&&!E&&s.set(M),G=s.zimTweens[O]=s.zimTween=createjs.Tween.get(s,P).to(_,K,createjs.Ease[c]).call(mt).wait(je,!0).call(gt),vt()}0<a?G=s.zimTweens[O]=s.zimTween=createjs.Tween.get(s,{override:P.override}).wait(a,!0).call(function(){t&&"function"==typeof t&&t(zot(o)?s:o),Ue()}):Ue()}G.startPaused=R,G.rewinding=!1,!B&&A&&(Ye=j&&!zot(D)&&D.dispatchEvent?kt.Ticker.add(function(){(re||se||ce||de)&&ft(),D.dispatchEvent("animation")},ee):j&&s.dispatchEvent?kt.Ticker.add(function(){(re||se||ce||de)&&ft(),s.dispatchEvent("animation")},ee):kt.Ticker.add(function(){(re||se||ce||de)&&ft()},ee));var Ke=[1,1,1];zot(s.zimMaskDynamic)||s.zimMaskApply();var Ze,Qe,Je=!1;vt(),s.stopAnimate&&s.stopAnimate.real||(s.stopAnimate=function(e,t,o){if(zot(o)&&(o=!0),s.paused=null,"Pen"==s.type&&s.zimOnPath&&(s.stop(),s.zimOnPath=!1),zot(t)&&(t=!0),o&&Y&&(s.off("mousedown",s.zimAnimateDragDown),s.off("pressmove",s.zimAnimateDragPress),s.off("pressup",s.zimAnimateDragUp),kt.Ticker.remove(s.zimDragAnimateTicker)),zot(e)){if(!t)return s;for(var n in s.zimBusy=null,createjs.Tween.removeTweens(s),s.zimTweens)bt(n);s.zimTweens=null,s.zimIdSets=null,kt.idSets&&kt.idSets[q||n]&&(delete kt.idSets[q||n],kt.isEmpty(kt.idSets)&&delete kt.idSets),kt.animatedObjects.remove(s)}else{Array.isArray(e)||(e=[e]);var r=xt(e);for(var n in s.zimTweens)s.zimTweens[n].requestID&&cancelAnimationFrame(s.zimTweens[n].requestID),t&&0<=r.indexOf(n)&&yt(n),!t&&r.indexOf(n)<0&&yt(n)}return s},s.stopAnimate.real=!0,s.pauseAnimate=function(e,t,o,n){if("Pen"==s.type&&(!1===e?s.zimOnPath&&(s.infinite=!0):s.stop()),Qe&&!n)return s.pause(e,t),s;if(zot(e)&&(e=!0),pe=!1,s.paused=e,zot(o)&&(o=!0),zot(t)&&!o)return s;if(zot(t))for(var r in s.zimTweens)wt(r,e);else{Array.isArray(t)||(t=[t]);var i=xt(t);for(var r in s.zimTweens)o&&0<=i.indexOf(r)&&wt(r,e),!o&&i.indexOf(r)<0&&wt(r,e)}return s}),R&&s.pauseAnimate(!0,O,null,!0),_.extra&&(Ze=_.extra,delete _.extra,Array.isArray(Ze)||(Ze=[Ze]));for(V=0;V<ie.length;V++){var $e=ie[V];_[$e]&&(zot(Ze)&&(Ze=[]),Ct($e,_[$e]),delete _[$e])}if(Ze){var et;G.extraTickers=[];for(V=0;V<Ze.length;V++){var tt=Ze[V];for(var ot in zot(tt.inputObj)&&(tt.inputObj=s),zot(tt.inputProp)&&(tt.inputProp="y"),zot(tt.inputMin)&&(tt.inputMin=0),zot(tt.inputMax)&&(tt.inputMax="x"==tt.inputProp?ee.width:ee.height),zot(tt.outputObj)&&(tt.outputObj=s),zot(tt.outputProp)&&(tt.outputProp="scale"),zot(tt.outputMin)&&(tt.outputMin=0),zot(tt.outputMax)&&(tt.outputMax=tt.outputMin+1),zot(tt.constrain)&&(tt.constrain=!0),tt)_[ot]=kt.Pick.choose(_[ot]);"percentSpeed"==tt.outputProp&&(L=!0),et=new kt.Proportion(tt.inputMin,tt.inputMax,tt.outputMin,tt.outputMax,tt.factor,tt.outputRound);var nt=function(){var n=tt,r=et;return function(){var e,t=n.outputObj;if(e=n.constrain?kt.constrain(r.convert(n.inputObj[n.inputProp]),n.outputMin,n.outputMax):r.convert(n.inputObj[n.inputProp]),"scale"==n.outputProp)t.scaleX=kt.sign(t.scaleX)*e,t.scaleY=kt.sign(t.scaleY)*e;else if("scaleX"==n.outputProp)t.scaleX=kt.sign(t.scaleX)*e;else if("scaleY"==n.outputProp)t.scaleY=kt.sign(t.scaleY)*e;else if("layer"==n.outputProp){if(!t.parent)return;var o=kt.constrain(Math.round(e),0,t.parent.numChildren-1);o!=t.parent.getChildIndex(t)&&t.parent.setChildIndex(t,o)}else t[n.outputProp]=e}}();nt(),G.extraTickers.push(kt.Ticker.add(nt,ee))}}if(L||s.zimAnimateDragDown){if(L){Qe=!0,s.pauseAnimate(!0,O,null,!0),s.paused=!1,G.currentTime=0;var rt=G;zot(s.percentSpeed)&&(s.percentSpeed=G.startPaused?0:100);var it=1e3/60;G.currentTime=0;var at=!a&&zot(u)&&l;X&&l&&zot(u)&&(X=!1);var lt,st=n+(m?n:0)+(z||0)+(d||0),ct=1;l&&u&&(ct=u),X&&(lt=st*ct),function e(){if(G.requestID=requestAnimationFrame(e),L&&(!G.startPaused||0!=s.percentSpeed)){G.startPaused=!1,0<a&&G!=rt&&(a=0,G.currentTime=0,s.pauseAnimate(!0,O),s.paused=!1,at=zot(u)&&l),at&&(G.currentTime+=1e4*st,G.setPosition(G.currentTime,!0),at=!1);var t=G.currentTime+it*s.percentSpeed/100;lt&&0==a&&(t=kt.constrain(t,0,lt)),G.currentTime=t,G.setPosition(G.currentTime),(re||se||ce||de)&&ft(),ee.update()}}()}var ut;s.pause=function(e,t){if(zot(e)&&(e=!0),zot(t)&&(t=0),e){if(s.zimAnimateDragDown&&(Y=!1,s.cursor="default",s.off("mousedown",s.zimAnimateDragDown),s.off("pressmove",s.zimAnimateDragPress),s.off("pressup",s.zimAnimateDragUp),!L))return;ut=s.percentSpeed,0<t?(!0,kt.animate({target:s,props:{percentSpeed:0},override:!1,ticker:!1,time:t,call:function(){!1,s.percentSpeed=0,s.paused=!0,L=!1,s.dispatchEvent("pause")}})):(G.startPaused=!1,!1,s.percentSpeed=0,s.paused=!0,L=!1,setTimeout(function(){s.dispatchEvent("pause")},10))}else{if(s.zimAnimateDragDown&&(Y=!0,s.cursor="pointer",s.zimAnimateDragDown=s.on("mousedown",s.zimAnimateDragDown),s.zimAnimateDragPress=s.on("pressmove",s.zimAnimateDragPress),s.zimAnimateDragUp=s.on("pressup",s.zimAnimateDragUp),!L))return;pe=!1,G.currentTime=G.position,0<t?(!0,kt.animate({target:s,props:{percentSpeed:ut},override:!1,ticker:!1,time:t,call:function(){!1,s.percentSpeed=ut,s.paused=!1,L=!0}})):(!1,s.percentSpeed=ut,s.paused=!1,L=!0)}return s}}return s}}function dt(){zot(O)?O=kt.makeID(10):(O=String(O),U=O),zot(s.zimIdSets)&&(s.zimIdSets={}),zot(s.zimIdSets[O])?zot(s.zimTweens[O])||(q=O,O=kt.makeID(10),s.zimIdSets[q]=[q],s.zimTweens[q].zimIdSet=q,s.zimIdSets[q].push(O)):(q=O,O=kt.makeID(10),s.zimIdSets[q].push(O))}function ht(e,t,o,n){re&&(!zot(e.percentComplete)||o&&!zot(o.percentComplete))&&(o||(o={}),zot(o.pathRatio)&&(o.pathRatio=zot(o.percentComplete)?e.percentComplete/100:o.percentComplete/100));var r={};for(V in t)o&&!zot(o[V])?r[V]=o[V]:r[V]=e[V],n&&(e[V]=t[V]);return r}function gt(){Oe&&"function"==typeof Oe&&Oe(Le)}function pt(){De&&"function"==typeof De&&De(Xe)}function ft(){if(s.parent&&!G.passive&&!G.startPaused){if(re){le&&(ve=re.segmentPoints,ye=re.segmentRatios);var e=re.getCurvePoint(s.pathRatio,ye,ve);if(e){me=e.z;var t=s.parent.globalToLocal(e.x,e.y);s.x=t.x,s.y=t.y}}var o;if(ce&&ge&&(Se>s.x&&kt.sign(s.scaleX)==kt.sign(ue)&&(s.scaleX*=-1),Se<s.x&&kt.sign(s.scaleX)!=kt.sign(ue)&&(s.scaleX*=-1)),de&&ge&&(Ee>s.y&&kt.sign(s.scaleY)==kt.sign(he)&&(s.scaleY*=-1),Ee<s.y&&kt.sign(s.scaleY)!=kt.sign(he)&&(s.scaleY*=-1)),se){var n;if(re==se)o=kt.angle(Se,Ee,s.x,s.y)+Ie;else n=se.parent?se.parent.localToLocal(se.x,se.y,s.parent):s.parent.globalToLocal(se.x,se.y),o=kt.angle(s.x,s.y,n.x,n.y)+Ie;0!=o&&(ce&&0<Se-s.x&&(o+=180),s.rotation=o==Ie?s.rotation:o)}if(Y){var r=s.x-Se+s.y-Ee;2<Math.abs(r)&&(Ke.push(sign(r)),Ke.shift(),G.forward=function(e){if(Array.isArray(e)){for(var t=0,o=0,n=e.length;o<n;o++)t+=e[o];return t}}(Ke))}Se=s.x,Ee=s.y}}function mt(){if(s.paused&&"Sprite"!=s.type)r&&"function"==typeof r&&r(i);else{if(P.loop){if(!(0<Me))return void pt();if(Q<Me)return pt(),void Q++;m?s.set&&s.set(zt()):s.set&&s.set(_)}yt(O),s.paused=null,s.zimX=null,s.zimY=null,r&&"function"==typeof r&&r(i)}}function zt(){var e={};for(var t in _)B?zot(M[t])||E?e[t]=s.style[t]:e[t]=M[t]:zot(M[t])||E?e[t]=s[t]:e[t]=M[t];return e}function vt(){G.zimObj=_,G.zimTicker=Ye,G.zimPaused=Je,q&&(G.zimIdSet=q),U&&(zot(kt.idSets)&&(kt.idSets={}),zot(kt.idSets[U])?kt.idSets[U]=[s]:kt.idSets[U].indexOf(s)<0&&kt.idSets[U].push(s)),kt.animatedObjects||(kt.animatedObjects=new kt.Dictionary(!0)),kt.animatedObjects.add(s,!0)}function yt(e){if(!zot(s.zimTweens)&&!zot(s.zimTweens[e])){!function(e){if(s.zimBusy){for(var t in e)delete s.zimBusy[t];kt.isEmpty(s.zimBusy)&&(s.zimBusy=null)}}(s.zimTweens[e].zimObj),s.zimTweens[e].paused=!0,bt(e);var t=s.zimTweens[e].zimIdSet;if(!zot(t)&&s.zimIdSets){var o=s.zimIdSets[t];o&&o.splice(o.indexOf(e),1),o&&0==o.length&&(delete s.zimIdSets[t],kt.isEmpty(s.zimIdSets)&&delete s.zimIdSets)}if("Pen"==s.type&&s.zimOnPath&&(s.stop(),s.zimOnPath=!1),delete s.zimTweens[e],kt.isEmpty(s.zimTweens)&&s.stopAnimate(null,null,!1),s.zimTweens&&s.zimTweens[e]||s.zimIdSets&&s.zimIdSets[t||e]);else if(kt.idSets&&kt.idSets[t||e]){kt.idSets[t||e];var n=kt.idSets[t||e].indexOf(s);0<=n&&kt.idSets[t||e].splice(n,1),kt.idSets[t||e].length<=0&&(delete kt.idSets[t||e],kt.isEmpty(kt.idSets)&&delete kt.idSets)}}}function bt(o){!function(){var e=s.zimTweens[o].zimTicker;if(s.zimTweens[o].extraTickers)for(var t=0;t<s.zimTweens[o].extraTickers.length;t++)kt.Ticker.remove(s.zimTweens[o].extraTickers[t]);setTimeout(function(){e&&kt.Ticker.remove(e),e=null},200)}()}function wt(e,t){var o=s.zimTweens[e];(o.paused=t)!=o.zimPaused&&((o.zimPaused=t)?o.zimTicker&&(o.zimAnimateTimeout=setTimeout(function(){kt.Ticker.remove(o.zimTicker)},200)):(o.startPaused=!1,clearTimeout(o.zimAnimateTimeout),o.zimTicker&&(o.zimTicker=kt.Ticker.add(o.zimTicker,ee))))}function xt(e){for(var t=[],o=0;o<e.length;o++)s.zimIdSets&&!zot(s.zimIdSets[e[o]])?t=t.concat(s.zimIdSets[e[o]]):t.push(e[o]);return t}function Ct(e,t){!0===t?Ze.push({outputProp:ae[e]}):Array.isArray(t)?Ze.push({outputProp:ae[e],outputMin:t[0],outputMax:t[1],inputMin:t[2],inputMax:t[3]}):Ze.push({outputProp:ae[e],outputMax:t})}},kt.stopAnimate=function(e){if(z_d("45.12"),zot(e)){if(kt.animatedObjects)for(var t=kt.animatedObjects.length-1;0<=t;t--)kt.animatedObjects.objects[t].stopAnimate()}else if(Array.isArray(e)||(e=[e]),kt.idSets)for(var o=0;o<e.length;o++){var n=e[o];if(kt.idSets[n])for(t=kt.idSets[n].length-1;0<=t;t--)kt.idSets[n][t].stopAnimate(n)}},kt.stopZimAnimate=function(e){z_d("45.1"),kt.stopAnimate(e)},kt.pauseAnimate=function(e,t){if(z_d("45.22"),zot(e)&&(e=!0),zot(t)){if(kt.animatedObjects)for(var o=kt.animatedObjects.length-1;0<=o;o--)kt.animatedObjects.objects[o].pauseAnimate(e)}else if(Array.isArray(t)||(t=[t]),kt.idSets)for(var n=0;n<t.length;n++){var r=t[n];if(kt.idSets[r])for(o=kt.idSets[r].length-1;0<=o;o--)kt.idSets[r][o].pauseAnimate(e,r)}},kt.pauseZimAnimate=function(e,t){z_d("45.2"),kt.pauseAnimate(e,t)},kt.wiggle=function(i,a,l,s,c,u,d,e,h,g,p,f,m,t){var o;if(o=zob(kt.wiggle,arguments,"target, property, baseAmount, minAmount, maxAmount, minTime, maxTime, totalTime, type, ease, integer, id, startType, ticker"))return o;if(z_d("45.25"),zot(i)||zot(l)||zot(s))return i;zot(c)&&(c=s),zot(u)&&(u=1e3),zot(d)&&(d=u),zot(g)&&(g="quadInOut"),zot(p)&&(p=!1),zot(f)&&(f=kt.makeID()),zot(h)&&(h="both"),zot(m)&&(m="both"),zot(t)&&(t=!0),zot(e)||(i.wiggleTimeout=setTimeout(function(){i.stopAnimate(f),i.dispatchEvent("wigglestop")},e));var z,v=0;return function e(){var t=kt.rand(kt.Pick.choose(u),kt.Pick.choose(d)),o={},n={};if(n[a]=kt.Pick.choose(l),"negative"==h||0==v&&"negative"==m)var r=-kt.rand(kt.Pick.choose(s),kt.Pick.choose(c),p);else r="positive"==h||0==v&&"positive"==m?kt.rand(kt.Pick.choose(s),kt.Pick.choose(c),p):0==v?kt.rand(kt.Pick.choose(s),kt.Pick.choose(c),p,!0):kt.rand(kt.Pick.choose(s),kt.Pick.choose(c),p)*kt.sign(z)*-1;o[a]=kt.Pick.choose(l)+r,0==v&&(t/=2),z=r,v++,"negative"==h||"positive"==h?kt.animate({target:i,obj:o,set:n,ease:g,time:2*t,rewind:!0,override:!1,call:e,id:f,ticker:!!i.stage}):kt.animate({target:i,obj:o,ease:g,time:t,override:!1,call:e,id:f,ticker:!!i.stage})}(),i},kt.zimLoopCheck=!1,kt.loop=function(e,t,o,n,r,i){var a;if(a=zob(kt.loop,arguments,"obj, call, reverse, step, start, end"))return a;if(kt.zimLoopCheck||z_d("45.3"),kt.zimLoopCheck=!0,!zot(e)&&!zot(t)){zot(o)&&(o=!1),(zot(n)||n<=0)&&(n=1);var l="number"==typeof e?"number":e.constructor===Array?"array":e.constructor==={}.constructor?"object":e instanceof NodeList?"nodelist":e instanceof HTMLCollection?"htmlcollection":"invalid";if("container"!=l||e.addChild)if("number"==l||"array"==l||"nodelist"==l||"htmlcollection"==l){if(0==(h=g((u="number"==l?e:e.length)-1)))return;if(o)for(var s=r;i<=s;s-=n){if("number"==l)var c=t(s,h,r,i,e);else if("array"==l)c=t(e[s],s,h,r,i,e);else c=t(e.item(s),s,h,r,i,e);if(void 0!==c)return c}else for(s=r;s<=i;s+=n){if("number"==l)c=t(s,h,r,i,e);else if("array"==l)c=t(e[s],s,h,r,i,e);else c=t(e.item(s),s,h,r,i,e);if(void 0!==c)return c}}else if("object"==l){var u=0,d=[];for(var s in e)u++,d.push(s);if(0==(h=g(u-1)))return;if(o)for(s=r;i<=s;s-=n){if(void 0!==(c=t(d[s],e[d[s]],s,h,r,i,e)))return c}else for(s=r;s<=i;s+=n){if(void 0!==(c=t(d[s],e[d[s]],s,h,r,i,e)))return c}}else{var h;if(0==(h=g(e.numChildren-1)))return;if(o)for(s=r;i<=s;s-=n){if(void 0!==(c=t(e.getChildAt(s),s,h,r,i,e)))return c}else for(s=r;s<=i;s+=n){if(void 0!==(c=t(e.getChildAt(s),s,h,r,i,e)))return c}}}function g(e){return zot(r)&&(r=o?e:0),zot(i)&&(i=o?0:e),o&&r<i||!o&&i<r?0:(r<0&&i)<0||e<r&&e<i?0:(r=Math.max(0,Math.min(r,e)),i=Math.max(0,Math.min(i,e)),Math.floor((o?r-i:i-r)/n)+1)}},kt.scaleTo=function(e,t,o,n,r,i){var a;if(a=zob(kt.scaleTo,arguments,"obj, boundObj, percentX, percentY, type, boundsOnly"))return a;if(z_d("43"),!zot(e)&&e.getBounds&&e.getBounds()){if(!zot(t)&&t.getBounds&&t.getBounds()){zot(o)&&(o=-1),zot(n)&&(n=-1),-1==o&&-1==n&&(o=n=100),zot(r)&&(r="smallest"),zot(i)&&(i=!1);var l=t.getBounds().width*o/100*(i?1:t.scaleX),s=t.getBounds().height*n/100*(i?1:t.scaleY);if((-1==o||-1==n)&&"both"!=r&&"stretch"!=r)return-1==o?kt.sca(e,s/e.getBounds().height):kt.sca(e,l/e.getBounds().width),e;if("both"==r||"stretch"==r)return e.scaleX=-1!=o?l/e.getBounds().width:e.scaleX,e.scaleY=-1!=n?s/e.getBounds().height:e.scaleY,e;if("biggest"==r||"largest"==r||"outside"==r)var c=Math.max(l/e.getBounds().width,s/e.getBounds().height);else c=Math.min(l/e.getBounds().width,s/e.getBounds().height);return kt.sca(e,c),e}zog("zim methods - scaleTo(): please provide a boundObject (with setBounds) to scale to")}else zog("zim methods - scaleTo(): please provide an object (with setBounds) to scale")},kt.fit=function(e,t,o,n,r,i){var a;if(a=zob(kt.fit,arguments,"obj, left, top, width, height, inside"))return a;if(z_d("46"),!zot(e)&&e.getBounds){if(e.getBounds()){if(zot(t)){if(!e.stage)return void zog("zim methods - fit(): please add boundary dimensions or add obj to stage first");if(!e.stage.getBounds())return void zog("zim methods - fit(): please add boundary dimensions or add obj with bounds to stage first");o=t=0,n=e.stage.getBounds().width,r=e.stage.getBounds().height}zot(i)&&(i=!0),e.scaleX=e.scaleY=1;var l,s=n,c=r,u=e.getBounds().width,d=e.getBounds().height;l=i?u/d<=s/c?c/d:s/u:u/d<=s/c?s/u:c/d,e.scaleX=e.scaleY=l;var h=u*l,g=d*l;return e.x=(e.regX-e.getBounds().x)*l+t+(s-h)/2,e.y=(e.regY-e.getBounds().y)*l+o+(c-g)/2,{x:e.x,y:e.y,width:h,height:g,scale:l,bX:t,bY:o,bWidth:n,bHeight:r}}zog("zim methods - fit(): please setBounds() on object")}},kt.boundsCheck=!1,kt.boundsToGlobal=function(e,t,o){if(kt.boundsCheck||(z_d("40"),kt.boundsCheck=!0),!zot(e)&&e.getBounds){zot(o)&&(o=!1);var n=e.getBounds();if(n||!zot(t)){if(t&&(n=t),o)var r=e.globalToLocal(n.x,n.y),i=e.globalToLocal(n.x+n.width,n.y),a=e.globalToLocal(n.x+n.width,n.y+n.height),l=e.globalToLocal(n.x,n.y+n.height);else r=e.localToGlobal(n.x,n.y),i=e.localToGlobal(n.x+n.width,n.y),a=e.localToGlobal(n.x+n.width,n.y+n.height),l=e.localToGlobal(n.x,n.y+n.height);var s=Math.min(r.x,i.x,a.x,l.x),c=Math.min(r.y,i.y,a.y,l.y),u=Math.max(r.x,i.x,a.x,l.x),d=Math.max(r.y,i.y,a.y,l.y);return new createjs.Rectangle(s,c,u-s,d-c)}zog("zim methods - boundsToGlobal():\n please setBounds() on object (or a rectangle)")}},kt.resetBounds=function(e,t,o,n,r){if(z_d("40.5"),zot(n))i=0,a=t,l=0,s=o;else var i=t,a=n,l=o,s=r;return zot(s)&&(s=a),zot(t)?e.setBounds(null):e.setBounds(i,l,a,s),e},kt.copyMatrix=function(e,t){return z_d("45.5"),e.x=t.x,e.y=t.y,e.scaleX=t.scaleX,e.scaleY=t.scaleY,e.regX=t.regX,e.regY=t.regY,e.rotation=t.rotation,e.skewX=t.skewX,e.skewY=t.skewY,e},kt.expand=function(e,t,o){if(z_d("50"),zot(e)||!e.getBounds||!e.getBounds())return zog("zim methods - expand(): please provide object with bounds set"),e;zot(t)&&(t=20),zot(o)&&(o=t);var n=e.getBounds(),r=new createjs.Shape;return r.graphics.f("0").r(n.x-t,n.y-o,n.width+2*t,n.height+2*o),e.hitArea=r,e},kt.setSwipe=function(i,e){if(z_d("34"),!zot(i)&&i.on)return i.zimNoSwipe=!e||null,i instanceof createjs.Container&&function e(t){var o=t.numChildren;var n;for(var r=0;r<o;r++)(n=t.getChildAt(r)).zimNoSwipe=i.zimNoSwipe,n instanceof createjs.Container&&e(n)}(i),i},kt.setMask=function(e,t,o){if(z_d("50.1"),zot(e)&&zog("zim methods - setMask(): please provide obj"),zot(t))return n(),e;function n(){e.zimMask&&e.zimMask.parent&&e.zimMask.parent.removeChild(e.zimMask),e.zimMask=null,e.zimMaskTicker&&kt.Ticker.remove(e.zimMaskTicker),e.mask=null}var r;function i(){if(o&&(!e.stage||!t.stage))return e;r=null,e.zimMask=t.zimMask=r=t.shape.clone(),kt.copyMatrix(r,t),r.regX=t.regX,r.regY=t.regY,t.addChildAt(r,0),r.alpha=0,r.x=t.x+t.shape.x,r.y=t.y+t.shape.y,e.mask=r}return e.zimMaskOriginal&&e.zimMaskOriginal!=t&&n(),zot(o)&&(o=!("Blob"!=t.type&&zot(t.zimDown)&&zot(t.transformControls)&&zot(t.zimTouch)&&zot(t.zimTweens)),t.zimMaskDynamic=o),(e.zimMaskOriginal=t).zimMaskApply=function(){e.zimMaskTicker&&kt.Ticker.remove(e.zimMaskTicker),e.zimMaskTicker=kt.Ticker.add(i)},t&&t.shape?(i(),o&&t.zimMaskApply()):(r=t,e.mask=r),e},kt.outline=function(t,e,o){var n;if(n=zob(kt.outline,arguments,"obj, color, size"))return n;if(z_d("47"),t.type&&"zimOultineShape"==t.type)return zon&&zog("zim.outline() - warning, you are trying to outline an outline - do not outline in a loop"),t;if(zot(t)||!t.getBounds)return zog("zim methods - outline(): please provide object with bounds set"),t;if(!t.getBounds())return zog("zim methods - outline(): please setBounds() on object"),t;if(!t.parent)return zog("zim methods - outline(): object should be on stage first"),t;if(zot(e)&&(e="brown"),zot(o)&&(o=2),o<=0)return t.ZIMoutlineShape&&t.ZIMoutlineShape.parent.removeChild(t.ZIMoutlineShape),t.ZIMoutlineShapeC&&t.ZIMoutlineShapeC.parent.removeChild(t.ZIMoutlineShapeC),void(t.ZIMoutlineShape=t.ZIMoutlineShapeC=null);var r=t.getBounds(),i=t.ZIMoutlineShape=t.ZIMoutlineShape?t.ZIMoutlineShape:new kt.Shape;i.type="zimOutlineShape";var a=t.ZIMoutlineShapeC=t.ZIMoutlineShapeC?t.ZIMoutlineShapeC:new kt.Shape;a.type="zimOutlineShape";var l=t.parent;t.outlineToggled=!0,t.outlineToggle=function(e){return t.ZIMoutlineShapeC.visible=!0===e?t.ZIMoutlineShape.visible=!0:!1===e?t.ZIMoutlineShape.visible=!1:(t.ZIMoutlineShape.visible=!t.ZIMoutlineShape.visible,!t.ZIMoutlineShapeC.visible),t.outlineToggled=t.ZIMoutlineShape.visible,t};var s=t.localToLocal(r.x,r.y,l),c=t.localToLocal(r.x+r.width,r.y,l),u=t.localToLocal(r.x+r.width,r.y+r.height,l),d=t.localToLocal(r.x,r.y+r.height,l),h=t.localToLocal(0,0,l),g=i.graphics.c(),p=a.graphics.c();g.s(e).ss(o).mt(s.x,s.y).lt(c.x,c.y).lt(u.x,u.y).lt(d.x,d.y).lt(s.x,s.y).cp();p.s("white").ss(o+2),p.mt(-11,0).lt(11,0),p.mt(0,-11).lt(0,11),p.s(e).ss(o),p.mt(-10,0).lt(10,0),p.mt(0,-10).lt(0,10),a.x=h.x,a.y=h.y,a.rotation=t.rotation,g.s("white").ss(o+2).dc(t.x,t.y,16),g.s(e).ss(o).dc(t.x,t.y,16),t.parent.removeChild(i),t.parent.removeChild(a);var f=t.parent.getChildIndex(t);return t.parent.addChildAt(a,f+1),t.parent.addChildAt(i,f+1),i.mouseEnabled=!1,a.mouseEnabled=!1,t},kt.STYLE=null,kt.STYLECHECK=!1,kt.ignore="ignore",kt.getStyle=function(e,t,o){kt.STYLECHECK||(z_d("50.34"),kt.STYLECHECK=!0);var n=["pos","addTo","center","centerReg","mov","drag","transform","gesture","outline","bounds","animate","wiggle"],r=kt.STYLE;if("undefined"!=typeof STYLE&&(r=STYLE),r=zot(r)?{}:kt.copy(r),zot(o))o={};else for(var i=0;i<n.length;i++)delete o[n[i]];var a,l=o,s=r.type;if(s&&delete r.type,!zot(t)&&!zot(r.group)){var c=t.split(","),u={};for(i=0;i<c.length;i++){var d=c[i].trim();zot(r.group[d])||(u=kt.merge(u,r.group[d]))}delete r.group}for(var h in zot(e)||zot(s)||zot(s[e])||(r=kt.merge(r,s[e])),zot(t)||zot(u)||(r=kt.merge(r,u)),r)l[h]?delete r[h]:"ignore"!=(a=-1!=n.indexOf(h)||r.delayPick?r[h]:kt.Pick.choose(r[h]))?(a&&a.constructor==={}.constructor&&(a=kt.copy(a,!0,!1)),r[h]=a):delete r[h];return!1===(r=kt.merge(r,l)).style?{}:r};var r=["visible","x","y","scale","scaleX","scaleY","rotation","alpha","skewX","skewY","regX","regY"],Oe=function(t,o){if(o){o.add&&t.addTo(),o.addTo&&t.addTo(!0===o.addTo?null:o.addTo),o.center&&t.center(!0===o.center?null:o.center),o.centerReg&&t.centerReg(!0===o.centerReg?null:o.centerReg);for(var n=0;n<r.length;n++)null!=o[r[n]]&&(t[r[n]]=kt.Pick.choose(o[r[n]]));if(o.bounds&&o.bounds.constructor==={}.constructor&&t.setBounds(o.bounds.x?o.bounds.x:0,o.bounds.y?o.bounds.y:0,o.bounds.width?o.bounds.width:100,o.bounds.height?o.bounds.height:100),(o.mov||o.move)&&(o.move&&(o.mov=o.move),o.mov.constructor==={}.constructor?t.mov(kt.Pick.choose(o.mov.x),kt.Pick.choose(o.mov.y)):t.mov(kt.Pick.choose(o.mov))),o.pos)if(o.pos.constructor==={}.constructor)t.pos(kt.Pick.choose(o.pos.x),kt.Pick.choose(o.pos.y),kt.Pick.choose(o.pos.right),kt.Pick.choose(o.pos.bottom),kt.Pick.choose(o.pos.index),o.pos.add,kt.Pick.choose(o.pos.reg),kt.Pick.choose(o.pos.regX),kt.Pick.choose(o.pos.regY));else{var e=kt.Pick.choose(o.pos);"left"!=e&&"top"!=e||t.pos(),"right"==e&&t.pos({right:!0}),"bottom"==e&&t.pos({bottom:!0}),"rightbottom"!=e&&"bottomright"!=e||t.pos({right:!0,bottom:!0}),"center"==e&&t.center()}if(o.outline&&setTimeout(function(){t.outline(o.outline.constructor==={}.constructor?o.outline:null),t.stage&&t.stage.update()},20),o.drag&&t.drag(o.drag.constructor==={}.constructor?o.drag:{currentTarget:!0}),o.gesture&&t.gesture(o.gesture.constructor==={}.constructor?o.gesture:null),o.transform&&setTimeout(function(){t.transform(o.transform.constructor==={}.constructor?o.transform:null)},20),o.animate){Array.isArray(o.animate)||(o.animate=[o.animate]);for(n=0;n<o.animate.length;n++)!function(){var e=o.animate[n];e.constructor==={}.constructor&&setTimeout(function(){t.animate(e)},20)}()}if(o.wiggle){Array.isArray(o.wiggle)||(o.wiggle=[o.wiggle]);for(n=0;n<o.wiggle.length;n++)!function(){var e=o.wiggle[n];e.constructor==={}.constructor&&setTimeout(function(){t.wiggle(e)},20)}()}}};kt.ANIMATE=!0,kt.OPTIMIZE=!1,kt.ACTIONEVENT="mousedown",kt.KEYFOCUS=null,kt.POSREG=!1,kt.DRAGALL=!1,kt.Ticker={stages:null,myUpdate:null,alwaysList:new kt.Dictionary,list:new kt.Dictionary,setFPS:function(e,t){zot(e)&&zot(t)?(e=30,t=60):zot(e)?e=30:zot(t)&&(t=e),kt.Ticker.framerate=createjs.Ticker.framerate=kt.mobile()?e:t},setTimingMode:function(e){createjs.Ticker.timingMode=createjs.Ticker.RAF,"synched"==e&&(createjs.Ticker.timingMode=createjs.Ticker.RAF_SYNCHED),"timeout"==e&&(createjs.Ticker.timingMode=createjs.Ticker.TIMEOUT)},add:function(e,t){z_d("30");var o=kt.Ticker;return o.has(e,t)?e:(o.framerate||o.setFPS(),!zot(t)&&t.update||(t=zimDefaultFrame.stage),zot(e)||"function"!=typeof e?void zog("zim.Ticker.add() - only add functions"):(o.ticker||(o.ticker=createjs.Ticker.on("tick",o.call)),o.list.at(t)?o.list.at(t).push(e):o.list.add(t,[e]),e))},rawID:{},raw:function(o){z_d("30");var n=kt.makeID(7,"letters");return function e(t){o(t),kt.Ticker.rawID[n]=requestAnimationFrame(e)}(),n},removeRaw:function(e){cancelAnimationFrame(kt.Ticker.rawID[e]),delete kt.Ticker.rawID[e]},call:function(e){for(var t,o,n=kt.Ticker,r=0;r<n.list.length;r++){t=n.list.objects[r],o=n.list.values[r];for(var i=0;i<o.length;i++)o[i](e);n.alwaysList.at(t)?t.update():0<o.length&&(!zot(n.update)||kt.OPTIMIZE||!zns&&OPTIMIZE?n.update&&t.update():t.update())}for(r=0;r<n.alwaysList.length;r++)t=n.alwaysList.objects[r],null==n.list[t]&&t.update()},always:function(e){z_d("30");var t=kt.Ticker;t.framerate||t.setFPS(),!zot(e)&&e.update||(e=zimDefaultFrame.stage),t.alwaysList.add(e,!0),t.ticker||(t.ticker=createjs.Ticker.on("tick",t.call))},alwaysOff:function(e){var t=kt.Ticker;!zot(e)&&e.update||(e=zimDefaultFrame.stage),t.alwaysList.remove(e)},remove:function(e){var t=kt.Ticker;if(zot(e)||"function"!=typeof e)zog("zim.Ticker - only remove functions");else{for(var o=0,n=0;n<t.list.length;n++){t.list.objects[n];var r=t.list.values[n].indexOf(e);-1<r&&t.list.values[n].splice(r,1),o+=t.list.values[n].length}0<t.alwaysList.length||0==o&&(createjs.Ticker.off("tick",t.ticker),t.ticker=null)}},removeAll:function(e){for(var t,o=kt.Ticker,n=0,r=0;r<o.list.length;r++)t=o.list.objects[r],(zot(e)||e===t)&&(o.list.values[r]=[]),n+=o.list.values[r].length;0<o.alwaysList.length||0==n&&(createjs.Ticker.off("tick",o.ticker),o.ticker=null)},has:function(e,t){return!zot(t)&&t.update||(t=zimDefaultFrame.stage),kt.Ticker.list&&kt.Ticker.list.at(t)&&0<=kt.Ticker.list.at(t).indexOf(e)},dispose:function(e){for(var t,o=kt.Ticker,n=0,r=o.list.length-1;0<=r;r--)t=o.list.objects[r],zot(e)||e===t?(o.list.remove(e),o.alwaysList.remove(e)):n+=o.list.values[r].length;if(!(0<o.alwaysList.length))return 0==n&&(createjs.Ticker.off("tick",o.ticker),o.ticker=null),!0}},Object.defineProperty(kt.Ticker,"update",{get:function(){return kt.Ticker.myUpdate},set:function(e){var t=kt.Ticker;"boolean"!=typeof e&&(e=null),t.myUpdate=e,!1===t.myUpdate&&(cancelAnimationFrame(t.ticker),t.alwaysList=new kt.Dictionary)}}),kt.Pages=function(o,p,f,e,m){var t;if(t=zob(kt.Pages,arguments,"pages, transition, speed, transitionTable, holder",this))return t;if(z_d("71"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Pages",zot(o)&&(o=[]),this.pages=o,zot(p)&&(p="none"),zot(f)&&(f=200),zot(e)&&(e=[]),this.transitionTable=e,zot(m)&&zimDefaultFrame&&(m=zimDefaultFrame.stage),m.getBounds&&m.getBounds()){this.speed=f,this.active=!0;var z=this;z.transitioning=!1;var v,y,b=m.getBounds().width,w=m.getBounds().height;"none"==p&&e==[]||s();for(var n,r,x=["left","right","up","down"],i=0;i<o.length;i++)(n=o[i]).constructor!=={}.constructor&&(n=o[i]={page:o[i]}),c(n.page,n.swipe);var a,C=this.page=o[0]?o[0].page:null;zot(this.page)||(this.index=0),this.addChild(C),A(C),this.swipe=new kt.Swipe(m);var k=!1,l=this.swipe.on("swipe",function(e){if(z.active){var t=e.currentTarget.direction;if("none"!=t){var o="";"left"==t?o="right":"right"==t?o="left":"up"==t?o="down":"down"==t&&(o="up"),t=o;var n=x.indexOf(t);r=C.zimSwipeArray[n],a=[r,t,null,null,!0],z.page=C,z.nextPage=r,z.direction=t,z.dispatchEvent("swipe"),setTimeout(function(){k||z.go(r,t,null,null,!0)},50)}}});this.addPage=function(e,t){c(e,t),C?e.parent&&e.parent.removeChild(e):(C=z.page=e,z.addChild(C))},this.removePage=function(e){P(e),z.currentPage==e&&(z.removeChild(e),m.stage&&m.stage.update()),e.zimSwipeArray=null},this.setSwipeArray=function(e,t){zot(t)&&(t=[]);var o={page:e,swipe:t};o.page.zimSwipeArray=o.swipe?o.swipe:[]},this.pause=function(){k=!0},this.unpause=function(){k&&z.go(a[0],a[1],a[2],a[3],a[4])};var T=!0;this.go=function(e,t,o,n,r){if("number"==typeof e){var i=z.pages[e];if(zot(i))return;e=i.page}setTimeout(function(){k=!1},200);for(var a=[{x:b},{x:-b},{y:w},{y:-w}],l=[{x:b/2,alpha:0},{x:-b/2,alpha:0},{y:w/2,alpha:0},{y:-w/2,alpha:0}],s=p,c=f,u=0;u<z.transitionTable.length;u++)if(z.transitionTable[u][0]==C&&z.transitionTable[u][1]==e){s=z.transitionTable[u][2],c=z.transitionTable[u][3];break}if(zot(o)&&(o=s),zot(n)&&(n=c),z.speed=n,z.direction=t,""==e||null==e)z.page=C,z.dispatchEvent("nothing");else if("string"==typeof e)z.page=C,z.dispatchEvent(e);else{if(e==C)return;zot(t)&&(t="right");var d=x.indexOf(t);if(!T)return;function h(e){e[0].uncache(),e[1].uncache(),z.transitioning=!1,z.dispatchEvent("pagetransitioned"),z.removeChild(z.lastPage),z.removeChild(v),z.removeChild(y),A(C),T=!0}function g(e){z.removeChild(z.lastPage),kt.animate(e.shift(),{alpha:0},z.speed/2,null,h,e)}T=!1,e.x=0,e.y=0,e.alpha=e.zimOriginalAlpha,z.transitioning=!0,"slide"==o?(e.x=-(0|a[d].x),e.y=-(0|a[d].y),e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),z.addChild(e),z.addChild(C),kt.animate(C,a[d],z.speed,null,h,[C,e]),kt.animate(e,[{x:0},{x:0},{y:0},{y:0}][d],z.speed)):"reveal"==o?(e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),z.addChild(e),z.addChild(C),kt.animate(C,l[d],z.speed,null,h,[C,e])):"fade"==o?(e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),e.alpha=1,z.addChild(e),z.addChild(C),kt.animate(C,{alpha:0},z.speed,null,h,[C,e])):"black"==o?(e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),e.alpha=1,z.addChild(e),z.addChild(C),v.alpha=0,z.addChild(v),kt.animate(v,{alpha:1},z.speed/2,null,g,[v,C,e])):"clear"==o?(e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),e.alpha=0,z.addChild(e),z.addChild(C),kt.animate(C,{alpha:0},z.speed/2),kt.animate(e,{alpha:1},z.speed/2,null,h,[C,e],z.speed/2)):"white"==o?(e.cache(0,0,(b+1)/e.scaleX,(w+1)/e.scaleY),C.cache(0,0,(b+1)/C.scaleX,(w+1)/C.scaleY),e.alpha=1,z.addChild(e),z.addChild(C),y.alpha=0,z.addChild(y),kt.animate(y,{alpha:1},z.speed/2,null,g,[y,C,e])):(z.transitioning=!1,z.addChild(e),z.removeChild(C),T=!0),P(C),z.lastPage=C,z.page=e,z.index=-1;for(u=0;u<z.pages.length;u++){z.pages[u].page==z.page&&(z.index=u)}"none"==o&&A(e),zot(r)&&(r=!1),z.fromSwipe=r,z.dispatchEvent("page"),C=e,m.stage&&m.stage.update()}},this.resize=function(){b=m.getBounds().width,w=m.getBounds().height,"none"==p&&e==[]||s()},this.puff=function(e){for(var t=0;t<o.length;t++)z.addChild(o[t].page);z.addChild(C),0<e&&setTimeout(function(){z.settle()},e)},this.settle=function(){z.removeAllChildren(),z.addChild(C),z.dispatchEvent("puffed")},this.disable=function(){z.active=!1},this.enable=function(){z.active=!0},this.dispose=function(){return z.swipe.off("swipe",l),this.zimContainer_dispose(),!0}}else zog("zim controls - Pages():\nholder object must have bounds set");function s(){(v=new createjs.Shape).graphics.f("black").r(0,0,b,w+1),(y=new createjs.Shape).graphics.f("white").r(0,0,b,w+1)}function c(e,t){e.zimHTMLList=new kt.Dictionary,P(e),e.zimSwipeArray=t||[],e.zimOriginalAlpha=e.alpha,e.parent&&e.parent.removeChild(n.page)}function A(e){for(var t=0;t<e.zimHTMLList.length;t++)e.addChildAt(e.zimHTMLList.values[t].obj,e.zimHTMLList.values[t].depth)}function P(e){e.zimHTMLList.clear();for(var t=0;t<e.numChildren;t++)if(ch=e.getChildAt(t),"TextArea"==ch.type||"Loader"==ch.type||"Tag"==ch.type){var o={obj:ch,depth:e.getChildIndex(ch)};e.zimHTMLList.add(ch,o)}for(t=e.numChildren-1;0<=t;t--)ch=e.getChildAt(t),"TextArea"!=ch.type&&"Loader"!=ch.type&&"Tag"!=ch.type||e.removeChild(ch)}},kt.extend(kt.Pages,kt.Container,["clone","dispose"],"zimContainer",!1),kt.HotSpots=function(a,o,n){var e;if(e=zob(kt.HotSpots,arguments,"spots, local, mouseDowns",this))return e;if(z_d("72"),this.zimContainer_constructor(null,null,null,null,!1),this.type="HotSpots",!zot(a)&&Array.isArray(a)){zot(o)&&(o=!0),zot(n)&&(n=!1);for(var l,r,i=(zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",s=this.hotSpots=[],t=0;t<a.length;t++)c(a[t]);this.addHotSpot=function(e,t,o,n,r,i){l={page:e,rect:t,call:o,callOver:n,callOut:r,talk:i},a.push(l),c(l)},this.show=function(){for(var e=0;e<s.length;e++)(r=s[e]).button||(r.spot.alpha=.2)},this.hide=function(){for(var e=0;e<s.length;e++)(r=s[e]).spot.alpha=0},this.removeHotSpots=function(e,t){for(var o=a.length-1;0<=o;o--)l=a[o],r=s[o],t&&!Array.isArray(t)&&(t=[t.x,t.y,t.getBounds().width,t.getBounds().height]),(zot(e)&&zot(t)||zot(t)&&e==l.page||zot(e)&&kt.arraysEqual(t,l.rect)||e==l.page&&kt.arraysEqual(t,l.rect))&&(a.splice(o,1),r.button&&(r.button.off(i,r.button.zimHSEvent),r.button.zimHSEvent=null,n||(r.button.off("mousedown",r.button.zimHSMDEvent),r.button.zimHSMDEvent=null)),r.off(i,u),r.dispose(),s.splice(o,1))},this.dispose=function(){for(var e=0;e<s.length;e++)(r=s[e]).button&&(r.button.off(i,r.button.zimHSEvent),r.button.zimHSCall=null,r.button.zimHSEvent=null,n||(r.button.off("mousedown",r.button.zimHSMDEvent),r.button.zimHSMDEvent=null)),r.off(i,u),r.dispose();return!0}}else zog("zim controls - HotSpots():\nplease provide an array of HotSpot data");function c(e){var t=null;if(!Array.isArray(e.rect)){if(!(t=e.rect))return void zog("zim controls - HotSpots(): HotSpot "+e.page+" "+e.rect+" button does not exist");e.rect=[t.x,t.y,t.width,t.height]}(r=new kt.HotSpot(e.page,e.rect[0],e.rect[1],e.rect[2],e.rect[3],e.call,e.callOver,e.callOut,o,e.talk)).zimHSpage=e.page,r.button=t,s.push(r),r.on(i,u),t&&zot(e.callOver)&&zot(e.callOut)&&(r.spot.mouseEnabled=!1,r.spot.mouseChildren=!1,t.zimHScall=e.call,t.zimHSEvent=t.on(i,u,!0),n||(t.zimHSMDEvent=t.on("mousedown",function(e){e.stopImmediatePropagation()})),t.cursor="pointer")}function u(e){e.stopImmediatePropagation&&e.stopImmediatePropagation(),window.event&&(window.event.cancelBubble=!0),"function"==typeof e.currentTarget.zimHScall&&e.currentTarget.zimHScall(e)}},kt.extend(kt.HotSpots,kt.Container,"clone","zimContainer",!1),kt.HotSpot=function(e,t,o,n,r,i,a,l,s,c){var u;if(u=zob(kt.HotSpot,arguments,"obj, x, y, width, height, call, callOver, callOut, local, talk",this))return u;if(z_d("73"),this.zimContainer_constructor(null,null,null,null,!1),this.type="HotSpot",!zot(e)&&e.addChild)if(e instanceof createjs.Container!=0)if(zot(t)||zot(o)||zot(n)||zot(r))zog("zim controls - HotSpot():\nPlease pass in x, y, width, height");else{zot(s)&&(s=!0),eventType=(zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click";var d=n,h=r;if(s)g=new kt.Point(t,o),f=n,m=r;else var g=e.globalToLocal(t,o),p=e.globalToLocal(t+d,o+h),f=p.x-g.x,m=p.y-g.y;var z=new kt.Shape(n,r);if(z.talk=zot(c)?"HotSpot":c,z.alpha=0,z.graphics.f("black").dr(0,0,f,m),z.x=g.x,z.y=g.y,z.cursor="pointer",z.expand(0),this.spot=z,"function"==typeof i)var v=z.on(eventType,function(e){i(e)});if("function"==typeof a)var y=z.on("mouseover",function(e){a(e)});if("function"==typeof l)var b=z.on("mouseout",function(e){l(e)});e.addChild(z),this.show=function(){e.addChild(backing)},this.hide=function(){e.removeChild(backing)},this.dispose=function(){return v&&z.off(eventType,y),y&&z.off("mouseover",y),b&&z.off("mouseout",b),e.removeChild(z),!(z=null)}}else zog("zim controls - HotSpot():\nObjects passed in should be Containers");else zog("zim controls - HotSpot():\nPlease pass in container object for obj")},kt.extend(kt.HotSpot,kt.Container,"clone","zimContainer",!1),kt.Guide=function(n,r,i,t,o){var e;if(e=zob(kt.Guide,arguments,"obj, vertical, percent, hideKey, pixelKey",this))return e;if(z_d("76"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Guide",zot(n)&&(n=zimDefaultFrame?zimDefaultFrame.stage:"stage"),zot(r)&&(r=!0),"stage"==n||n.addChild&&n.getBounds&&n.getBounds()){zot(i)&&(i=!0),zot(t)&&(t="G"),zot(o)&&(o="P");var a,l,s,c,u,d=this,h=80,g=26,p=h/6+h/2,f=2*g;r?((c=C("#00c5af","white","white")).shape.regX=h+h/6,c.shape.regY=g/2,c.label.x=-h/2-h/6):((c=C("#d61fa0","white","white")).shape.regX=h/2,c.shape.regY=g+g/4,c.label.y=3*-g/4),"stage"!=n&&n.addChild(d);var m,z,v,y,b=kt.added(d,function(){"stage"==n?(u=d.stage,n=u):u=n.stage;n.addChild(d),m=n.getBounds().width,z=n.getBounds().height,c.label.text=r?(c.y=z/2,"x:"+(d.percent?"70%":Math.round(70*m/100))):(c.x=m/2,"y:"+(d.percent?"70%":Math.round(70*z/100)));v=new createjs.Shape,d.addChild(v),r?v.x=.7*m:v.y=.7*z,w||(n.addChild(d),T());u.off("stagemousemove",a),a=u.on("stagemousemove",k),u.update()}),w=!1,x={x:0,y:0};Object.defineProperty(this,"pixels",{get:function(){return!i},set:function(e){i=!e,d.resize()}}),window.addEventListener("keydown",A),this.toggled=!0,this.toggle=function(e){return!0===e?d.visible=d.toggled=!0:!1===e?d.visible=d.toggled=!1:(d.visible=!d.visible,d.toggled=d.visible),u.off("stagemousemove",a),d.visible&&(a=u.on("stagemousemove",k,d)),d},this.resize=function(){return!!d&&(u&&(T(),k()),!0)},this.dispose=function(){return!!d&&(kt.noDrag(v),clearInterval(b),d.removeAllChildren(),window.removeEventListener("keydown",A),d.parent&&d.parent.removeChild(d),!(d=null))}}else zog("zim controls - Guide(): Please provide container with bounds for the obj (setBounds())");function C(e,t,o){var n=new kt.Container({style:!1});return n.shape=new createjs.Shape,n.shape.graphics.s(t).ss(1).f(e).r(0,0,h,g),n.shape.alpha=.9,n.addChild(n.shape),n.label=new createjs.Text("10","16px arial",o),n.label.textAlign="center",n.label.textBaseline="middle",n.addChild(n.label),n.mouseChildren=!1,n.mouseEnabled=!1,n}function k(e){var t,o;e?(t=n.globalToLocal(e.rawX,e.rawY),x=t):t={x:x.x,y:x.y},i?r?(o=Math.round(Math.abs(t.x-v.x)/m*100),c.label.text="x:"+Math.max(0,Math.min(o,100))+"%",c.y=Math.max(f,Math.min(t.y,s))):(o=Math.round(Math.abs(t.y-v.y)/z*100),c.label.text="y:"+Math.max(0,Math.min(o,100))+"%",c.x=Math.max(p,Math.min(t.x,l))):r?(o=Math.round(Math.abs(t.x-v.x)),c.label.text="x:"+Math.max(0,Math.min(o,Math.round(m))),c.y=Math.max(f,Math.min(t.y,s))):(o=Math.round(Math.abs(t.y-v.y)),c.label.text="y:"+Math.max(0,Math.min(o,Math.round(z))),c.x=Math.max(p,Math.min(t.x,l))),u&&u.update()}function T(){var e;w=!0,m=n.getBounds().width,z=n.getBounds().height,y=r?(e="ew-resize",new createjs.Rectangle(0,0,m,0)):(e="ns-resize",new createjs.Rectangle(0,0,0,z)),kt.noDrag(v),setTimeout(function(){kt.drag(v,y,e,e,null,null,!0)},500),u.mouseMoveOutside=!0,u.enableMouseOver(10),l=m-2*h/3,s=z-g-g,v.uncache();var t=v.graphics;r?(t.c().s("rgba(0,255,255,.1)").ss(20).mt(0,0).lt(0,z),t.f().s("white").ss(2).mt(0,0).lt(0,z),t.s("#00c5af").sd([20,20]).mt(0,0).lt(0,z).sd(),v.cache(-10,0,20,z)):(t.c().s("rgba(255,0,255,.1)").ss(20).mt(0,0).lt(m,0),t.f().s("white").ss(2).mt(0,0).lt(m,0),t.s("#d61fa0").sd([20,20]).mt(0,0).lt(m,0).sd(),v.cache(0,-10,m,20)),r?c.x=m:c.y=z,d.addChild(c)}function A(e){e||(e=event),u&&(String.fromCharCode(e.keyCode)==t.toUpperCase()&&d.toggle(),String.fromCharCode(e.keyCode)==o.toUpperCase()&&(d.pixels=!d.pixels))}},kt.extend(kt.Guide,kt.Container,"clone","zimContainer",!1),kt.Grid=function(r,i,a,t,o){var e;if(e=zob(kt.Grid,arguments,"obj, color, percent, hideKey, pixelKey",this))return e;if(z_d("78"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Grid",zot(r)&&(r=zimDefaultFrame?zimDefaultFrame.stage:"stage"),zot(i)&&(i="black"),"stage"==r||r.addChild&&r.getBounds&&r.getBounds()){zot(a)&&(a=!0),zot(t)&&(t="G"),zot(o)&&(o="P");var n,l=this,s=10;this.mouseChildren=!1,this.mouseEnabled=!1;var c=80,u=26,d=k("#dddddd",i,"#333333");d.shape.regX=c/2,d.shape.regY=-u/4,d.label.y=3*u/4;var h=k("#dddddd",i,"#333333");h.shape.regX=-c/6,h.shape.regY=u/2,h.label.x=c/2+c/6;var g,p,f,m=c/6+c/2,z=2*u;d.x=m,h.y=z,d.label.text="x:0",h.label.text="y:0","stage"!=r&&r.addChild(l);var v,y,b,w=kt.added(l,function(){"stage"==r?(f=l.stage,r=f):f=r.stage;x||(A(),r.addChild(l));f.off("stagemousemove",n),n=f.on("stagemousemove",T),f.update()}),x=!1,C={x:0,y:0};Object.defineProperty(this,"pixels",{get:function(){return!a},set:function(e){a=!e,l.resize()}}),window.addEventListener("keydown",P),this.toggled=!0,this.toggle=function(e){return!0===e?l.visible=l.toggled=!0:!1===e?l.visible=l.toggled=!1:(l.visible=!l.visible,l.toggled=l.visible),f.off("stagemousemove",n),l.visible&&(n=f.on("stagemousemove",T,l)),l},this.resize=function(){return!!l&&(l.removeChild(b),b=null,f&&(A(),T(),setTimeout(function(){l.removeChild(b),b=null,A()},200)),!0)},this.dispose=function(){return clearInterval(w),l.removeAllChildren(),window.removeEventListener("keydown",P),l.parent&&l.parent.removeChild(l),!(l=null)}}else zog("zim controls - Grid(): Please provide container with bounds for the obj (setBounds())");function k(e,t,o){var n=new kt.Container({style:!1});return n.shape=new createjs.Shape,n.shape.graphics.s(t).ss(1).f(e).r(0,0,c,u),n.shape.alpha=.9,n.addChild(n.shape),n.label=new createjs.Text("10","16px arial",o),n.label.textAlign="center",n.label.textBaseline="middle",n.addChild(n.label),n.mouseChildren=!1,n.mouseEnabled=!1,n}function T(e){var t;e?(t=r.globalToLocal(e.rawX,e.rawY),C=t):t={x:C.x,y:C.y},h.y=(h.label.text=a?(d.label.text="x:"+Math.max(0,Math.min(Math.round(t.x/v*100),100))+"%",d.x=Math.max(m,Math.min(t.x,g)),"y:"+Math.max(0,Math.min(Math.round(t.y/y*100),100))+"%"):(d.label.text="x:"+Math.max(0,Math.min(Math.round(t.x),Math.round(v))),d.x=Math.max(m,Math.min(t.x,g)),"y:"+Math.max(0,Math.min(Math.round(t.y),Math.round(y)))),Math.max(z,Math.min(t.y,p))),f&&f.update()}function A(){x=!0,r&&r.getBounds&&(v=r.getBounds().width,y=r.getBounds().height),f&&(f.mouseMoveOutside=!0,f.enableMouseOver(10)),g=v-2*c/3,p=y-u-u,b=new kt.Container({style:!1}),l.addChild(b);var e=new createjs.Shape;b.addChild(e);var t=e.graphics;t.s(i).ss(1);var o=new createjs.Shape;if(b.addChild(o),a){for(n=1;n<22;n++)t.mt(n*v/20,0).lt(n*v/20,y);for(n=1;n<20;n++)t.mt(0,n*y/20).lt(v,n*y/20);e.alpha=.3,(t=o.graphics).s(i).ss(1);for(n=1;n<10;n++)t.mt(n*v/10,0).lt(n*v/10,y);for(n=1;n<10;n++)t.mt(0,n*y/10).lt(v,n*y/10)}else{for(var n=0;n<v/s;n++)t.mt(n*s,0).lt(n*s,y);for(var n=0;n<y/s;n++)t.mt(0,n*s).lt(v,n*s);e.alpha=.3,(t=o.graphics).s(i).ss(1);for(var n=0;n<v/(10*s);n++)t.mt(n*(10*s),0).lt(n*(10*s),y);for(var n=0;n<y/(10*s);n++)t.mt(0,n*(10*s)).lt(v,n*(10*s))}t.s("#FFFFFF").ss(8),t.mt(v/2,y/2-40).lt(v/2,y/2+40),t.mt(v/2-40,y/2).lt(v/2+40,y/2),t.s("#000000").ss(4),t.mt(v/2,y/2-40).lt(v/2,y/2+40),t.mt(v/2-40,y/2).lt(v/2+40,y/2),t.s(i).ss(3),t.dr(0,0,v,y),o.alpha=.5,b.cache(0,0,v,y),l.addChild(d),l.addChild(h),f&&f.update()}function P(e){e||(e=event),f&&(String.fromCharCode(e.keyCode)==t.toUpperCase()&&l.toggle(),String.fromCharCode(e.keyCode)==o.toUpperCase()&&(l.removeChild(b),b=null,l.pixels=!l.pixels))}},kt.extend(kt.Grid,kt.Container,"clone","zimContainer",!1),kt.Tile=function(e,t,o,n,r,i,a,l,s,c,u,p,f,d,g,m,z,v,y,b,x){var C;if(C=zob(kt.Tile,arguments,"obj, cols, rows, spacingH, spacingV, width, height, squeezeH, squeezeV, colSize, rowSize, align, valign, count, mirrorH, mirrorV, snapToPixel, clone, group, style, inherit",this))return C;z_d("66.5"),this.zimContainer_constructor(null,null,null,null,!1),this.type="Tile",this.group=y;var k=!1===b?{}:kt.getStyle(this.type,this.group,x);zot(e)&&(e=null!=k.obj?k.obj:new kt.Circle),zot(t)&&(t=null!=k.cols?k.cols:1),zot(o)&&(o=null!=k.rows?k.rows:1),zot(i)&&(i=null!=k.width?k.width:null),zot(a)&&(a=null!=k.height?k.height:null),zot(c)&&(c=null!=k.colSize?k.colSize:null),zot(u)&&(u=null!=k.rowSize?k.rowSize:null),zot(i)||(c=null),zot(a)||(u=null),zot(n)&&(n=null!=k.spacingH?k.spacingH:null),zot(r)&&(r=null!=k.spacingV?k.spacingV:null),!zot(n)&&zot(c)||(n=0),!zot(r)&&zot(u)||(r=0),zot(l)&&(l=null!=k.squeezeH&&k.squeezeH),zot(s)&&(s=null!=k.squeezeV&&k.squeezeV),zot(p)&&(p=null!=k.align?k.align:"left"),zot(f)&&(f=null!=k.valign?k.valign:"top"),zot(d)&&(d=null!=k.count?k.count:null),0==d&&(d=null,zon&&zog("ZIM Tile() - count parameter of 0 is ignored - see docs")),zot(g)&&(g=null!=k.mirrorH&&k.mirrorH),zot(m)&&(m=null!=k.mirrorV&&k.mirrorV),zot(z)&&(z=null==k.snapToPixel||k.snapToPixel),z&&(e&&e.stage?e.stage.snapToPixelEnabled=!0:"undefined"!=typeof elem&&zimDefaultFrame&&(zimDefaultFrame.stage.snapToPixelEnabled=!0)),zot(v)&&(v=null==k.clone||k.clone);var T=this;T.cols=t,T.rows=o,T.spacingH=n,T.spacingV=r,T.squeezeH=l,T.squeezeV=s;var A,P="function"==typeof p,B="function"==typeof f;T.align=P?"left":p,T.valign=B?"top":f,T.mirrorH=g,T.mirrorV=m,T.items=[];var I,S,E,M,O,j,D,L,Y,X,R,_,W,F,H=0;e:for(var V=0;V<o;V++)for(var N=0;N<t;N++){if(H++,!zot(d)&&d<H)break e;zot(A=kt.Pick.choose(e))&&(A=new kt.Container(0,0,0,0)),v&&(0==V&&0==N||(A=A.clone())),T.items.push(A),A.tileNum=H-1}function G(){T.removeAllChildren(),I=[],S=[],E=[],M=[],O=[],Y=L=D=j=0,X=[],R=[],_=[],F=[],W=[],T.items&&T.items.length||(T.items=[]),d=T.items.length;for(var e,t=0,o=0,n=0,r=0;r<d;r++)o=Math.floor(r/T.cols),n=r%T.cols,zot(I[o])&&(I[o]=[]),zot(T.items[r])&&(T.items[r]=new Container(0,0,0,0)),I[o][n]=T.items[r];T.rows=Math.max(1,I.length),T.cols=Math.max(1,zot(I[0])?0:I[0].length);e:for(o=0;o<T.rows;o++){X.push([]),R.push([]),F.push([]),u&&zot(a)&&(h=kt.Pick.choose(u));for(r=0;r<T.cols;r++){if(t++,!zot(d)&&d<t)break e;(e=I[o][r]).snapToPixel=z,T.addChild(e),X[o].push(e.scaleX),R[o].push(e.scaleY),0==o&&c&&zot(i)&&(w=kt.Pick.choose(c)),0==o&&W.push(kt.Pick.choose(p)),c&&zot(i)||(w=Math.abs(e.width)),u&&zot(a)||(h=Math.abs(e.height)),F[o][r]=[w,h],zot(M[r])&&(M[r]=0),zot(O[o])&&(O[o]=0),w>M[r]&&(M[r]=w),h>O[o]&&(O[o]=h),zot(S[o])&&(S[o]=0),zot(E[r])&&(E[r]=0),S[o]+=w,E[r]+=h,S[o]>j&&(j=S[o]),E[r]>D&&(D=E[r]),zot(_[r])&&(_[r]=0),_[r]++}}!1===T.squeezeH&&kt.loop(M,function(e){L+=e}),!1===T.squeezeV&&kt.loop(O,function(e){Y+=e})}function q(e,t){var o,n,r,i;e<=0&&(e=null),t<=0&&(t=null),o=zot(e)||"full"!=T.squeezeH?zot(e)?0<L?L+(T.cols-1)*T.spacingH:j+(T.cols-1)*T.spacingH:Math.max(j+(T.cols-1)*T.spacingH,e):e,n=zot(t)||"full"!=T.squeezeV?zot(t)?0<Y?Y+(T.rows-1)*T.spacingV:D+(T.rows-1)*T.spacingV:Math.max(D+(T.rows-1)*T.spacingV,t):t,T.setBounds(0,0,o,n);var a=[],l=[],s=[];for(V=0;V<I.length;V++)for(r=I[V],i=0,zot(e)||0,N=0;N<r.length;N++){var c,u,d;A=r[N],0==V&&(a[N]=0,zot(t)||("full"==T.squeezeV?l[N]=1<_[N]?(t-E[N])/(_[N]-1):0:T.squeezeV?l[N]=1<_[N]?Math.max(T.spacingV,(t-E[N])/(_[N]-1)):0:l[N]=1<_[N]?Math.max(T.spacingV,(n-E[N])/(_[N]-1)):0),T.squeezeV?"center"==T.valign||"middle"==T.valign?s[N]=(n-(E[N]+(_[N]-1)*(zot(t)?T.spacingV:l[N])))/2:"bottom"==T.valign?s[N]=n-(E[N]+(_[N]-1)*(zot(t)?T.spacingV:l[N])):s[N]=0:s[N]=0),c=A.getBounds(),0==N&&(zot(e)||(d="full"==T.squeezeH?1<r.length?(e-S[V])/(r.length-1):0:T.squeezeH?1<r.length?Math.max(T.spacingH,(e-S[V])/(r.length-1)):0:1<r.length?Math.max(T.spacingH,(o-S[V])/(r.length-1)):0),u=T.squeezeH?"center"==T.align||"middle"==T.align?(o-(S[V]+(r.length-1)*(zot(e)?T.spacingH:d)))/2:"right"==T.align?o-(S[V]+(r.length-1)*(zot(e)?T.spacingH:d)):0:0,finalVAlign=kt.Pick.choose(f)),p=W[N];var h=F[V][N][0],g=F[V][N][1];T.mirrorH&&N%2==1?(A.scaleX=-X[V][N],A.x=i+h-2*c.x*A.scaleX):A.pos(i,null),!T.squeezeH&&P?!zot(e)||"center"!=p&&"middle"!=p?zot(e)&&"right"==p&&(A.x+=M[N]-A.width*A.scaleX):A.x+=(M[N]-A.width*A.scaleX)/2:T.squeezeH?!zot(e)||"center"!=T.align&&"middle"!=T.align?zot(e)&&"right"==T.align&&(A.x+=h-A.width*A.scaleX):A.x+=(h-A.width*A.scaleX)/2:!zot(e)||"center"!=T.align&&"middle"!=T.align?zot(e)&&"right"==T.align&&(A.x+=M[N]-A.width*A.scaleX):A.x+=(M[N]-A.width*A.scaleX)/2,T.mirrorV&&V%2==1?(A.scaleY=-R[V][N],A.y=a[N]+g-2*c.y*A.scaleY):A.pos(null,a[N]),!T.squeezeV&&B?!zot(t)||"center"!=finalVAlign&&"middle"!=finalVAlign?zot(t)&&"bottom"==finalVAlign&&(A.y+=O[V]-A.height*A.scaleY):A.y+=(O[V]-A.height*A.scaleY)/2:T.squeezeV?!zot(t)||"center"!=T.valign&&"middle"!=T.valign?zot(t)&&"bottom"==T.valign&&(A.y+=g-A.height*A.scaleY):A.y+=(g-A.height*A.scaleY)/2:!zot(t)||"center"!=T.valign&&"middle"!=T.valign?zot(t)&&"bottom"==T.valign&&(A.y+=O[V]-A.height*A.scaleY):A.y+=(O[V]-A.height*A.scaleY)/2,!0!==T.squeezeH&&zot(e)?i+=M[N]+(zot(e)?T.spacingH:d):i+=h+(zot(e)?T.spacingH:d),A.x+=u,A.y+=s[N],!0!==T.squeezeV&&zot(t)?a[N]+=O[V]+(zot(t)?T.spacingV:l[N]):a[N]+=g+(zot(t)?T.spacingV:l[N])}}G(),q(i,a),this.remake=function(e){return zot(e)||(T.items=e),G(),q(i,a),T},!(this.resize=function(e,t){return zot(e)&&(e=i),zot(t)&&(t=a),q(i=e,a=t),T})!==b&&Oe(this,k),this.clone=function(){return T.cloneProps(new kt.Tile(e,T.cols,T.rows,T.spacingH,T.spacingV,i,a,T.squeezeH,T.squeezeV,c,u,p,f,T.items.length,T.mirrorH,T.mirrorV,z,this.style,this.group))}},kt.extend(kt.Tile,kt.Container,"clone","zimContainer",!1),kt.Layout=function(y,b,w,x,C,k,T,t){var e;if(e=zob(kt.Layout,arguments,"holder, regions, lastMargin, backgroundColor, vertical, regionShape, scalingObject, hideKey",this))return e;if(z_d("80"),this.cjsEventDispatcher_constructor(),this.type="Layout",!zot(y)&&y.getBounds)if((T=zot(T)?y:T).getBounds&&T.getBounds()){var A=T.getBounds();y.setBounds(0,0,A.width,A.height),zot(w)&&(w=0),zot(C)&&(C=!0),zot(x)&&(x=""),zot(t)&&(t="B");var P,B=new createjs.Shape,I=this;this.active=!0,this.regions=b;var S=0,E="minWidth",M="width",O="height",j="marginLeft",D="maxHeight";C&&(E="minHeight",M="height",O="width",j="marginTop",D="maxWidth","y","x");for(var o=0;o<b.length;o++){if(!(P=b[o]).object||!P.object.getBounds())return void zog("zim controls - Layout(): each region object must have an object with setBounds() set");P[E]||(P[E]=0),P[M]||(P[M]=0),P.backgroundColor||(P.backgroundColor=""),P.given=0,P.maxGiven=0,zot(P[j])&&(P[j]=1e-4),P[D]||(P[D]=100),C?(P.align||(P.align="middle"),P.valign||(0==o?P.valign="top":o==b.length-1?P.valign="bottom":P.valign="middle",1==b.length&&(P.valign="middle"))):(P.valign||(P.valign="top"),P.align||(0==o?P.align="left":o==b.length-1?P.align="right":P.align="middle",1==b.length&&(P.align="middle"))),P[M]&&(P[E]=0),S+=P[M]+P[j]}if(100<(S+=w))zog("zim controls - Layout(): cannot fit regions into 100% bounds");else{var L=100-S;Y(),this.resize=function(){if(I.active){A=T.getBounds(),y.setBounds(0,0,A.width,A.height),B.graphics.clear(),""!=x&&B.graphics.f(x).r(0,0,A.width,A.height);for(var e=0;e<b.length;e++)(P=b[e]).maxGiven=0,P.marginGiven=0;for(var t,o,n,r=!0,i=L;r;){t=!(r=!1);for(e=0;e<b.length;e++)0<(P=b[e]).given&&0==P.maxGiven&&(d=P.object.getBounds()[M],h=P.object.getBounds()[O],o=P.given*A[M]/100,(n=P[D]*A[O]/100)<h/d*o?(P.maxGiven=d/h*n*100/A[M],P.given-P.maxGiven,i-=P.maxGiven):t=!1);if(t)break;for(e=totalPrimaries=0;e<b.length;e++)0==(P=b[e])[M]&&0==P.maxGiven&&(totalPrimaries+=P.object.getBounds()[M]);for(e=0;e<b.length;e++)0==(P=b[e])[M]&&0==P.maxGiven&&(P.given=P.object.getBounds()[M]/totalPrimaries*i)}var a=!0;if(0<(P=b[0]).maxGiven?P.maxGiven<P[E]&&(P[M]=P[E],a=!1):0<P.given&&P.given<P[E]&&(P[M]=P[E],a=!1),0<(P=b[b.length-1]).maxGiven?P.maxGiven<P[E]&&(P[M]=P[E],a=!1):0<P.given&&P.given<P[E]&&(P[M]=P[E],a=!1),!a){for(e=S=0;e<b.length;e++)P=b[e],S+=P[M]+P[j];return 100<(S+=w)?void zog("zim display - Layout(): cannot fit regions into 100% bounds"):(L=100-S,Y(),void I.resize())}var l=!0,s=0,c=0;for(e=0;e<b.length;e++)s+=(P=b[e])[j],0<P[M]?c+=P[M]:0<P.maxGiven?c+=P.maxGiven:0<P.given&&(c+=P.given),0==P[M]&&(l=!1);if(l||t){var u=100-c-(s+=w);if(s-=w+b[0][j],0!=u&&0!=s)for(e=0;e<b.length;e++)0!=e&&((P=b[e]).marginGiven=P[j]/s*(s+u))}var d,h,g,p,f,m=0,z=0;if(k&&k.graphics){var v=k.graphics;v.c()}for(e=0;e<b.length;e++)0<(P=b[e]).marginGiven?m+=P.marginGiven*A[M]/100:m+=P[j]*A[M]/100,d=(d=0<P[M]?P[M]:0<P.maxGiven?P.maxGiven:0<P.given?P.given:0)*A[M]/100,h=P[D]*A[O]/100,z=(A[O]-h)/2,g=C?kt.fit(P.object,z,m,h,d):kt.fit(P.object,m,z,d,h),"top"==P.valign?P.object.y=g.bY:"bottom"==P.valign&&(P.object.y=g.bY+g.bHeight-g.height),"left"==P.align?P.object.x=g.bX:"right"==P.align&&(P.object.x=g.bX+g.bWidth-g.width),k&&k.graphics&&(v.s("white").ss(2).r(g.bX,g.bY,g.bWidth,g.bHeight),v.s("#ff8203").sd([20,20]).r(g.bX,g.bY,g.bWidth,g.bHeight).sd()),f=p=0,0!=m&&m+d!=A[M]||(C?f=1:p=1),h==A[O]&&(C?p=1:f=1),""!=P.backgroundColor&&B.graphics.f(P.backgroundColor).r(g.bX,g.bY,g.bWidth+p,g.bHeight+f),m+=d}},this.resize(),k&&y.addChild(k),y.addChildAt(B,0),window.addEventListener("keydown",n),this.disable=function(){I.active=!1,window.removeEventListener("keydown",n),k&&(k.alpha=0)},this.enable=function(){I.active=!0,window.addEventListener("keydown",n),I.resize(),k&&(k.alpha=1)},this.removeShape=function(){k&&(k.graphics.clear(),y.removeChild(k),k=null,k=!1),window.removeEventListener("keydown",n)},this.toggled=!0,this.toggle=function(e){return k.visible=!0===e||!1!==e&&!k.visible,I.toggled=k.visible,I},this.addShape=function(e,t){I.removeShape(),k=e,window.addEventListener("keydown",n),y.addChild(k),I.resize()},this.dispose=function(){return I.removeShape(),!0}}}else zog("zim controls - Layout(): holder must have bounds set or provide a scalingObject with bounds");else zog("zim controls - Layout(): please provide an object with bounds set that holds the objects being laid out");function Y(){for(var e=0,t=0;t<b.length;t++)((P=b[t]).given=0)==P[M]&&(e+=P.object.getBounds()[M]);for(t=0;t<b.length;t++)0==(P=b[t])[M]&&(P.given=P.object.getBounds()[M]/e*L)}function n(e){e||(e=event),k&&String.fromCharCode(e.keyCode)==t.toUpperCase()&&(I.toggle(),k.stage&&k.stage.update())}},kt.extend(kt.Layout,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.Accessibility=function(d,e,o,t,n,g,r,i,a,l,s,c,u,h){var p;if(p=zob(kt.Accessibility,arguments,"appName, tabOrder, tabIndex, cycle, decimals, frame, alwaysHighlight, AHTime, AHColor, AHBorderWidth, AHBorderPadding, AHAlpha, AHObject, AHObjectScale",this))return p;if(z_d("30.5"),this.cjsEventDispatcher_constructor(),this.type="Accessibility",zot(d)&&(d="application"),zot(t)&&(t=!1),zot(n)&&(n=2),zot(g)&&(g=zimDefaultFrame),zot(r)&&(r=!1),zot(i)&&(i=700),zot(a)&&(a="brown"),zot(l)&&(l=3),zot(s)&&(s=5),zot(c)&&(c=.8),zot(h)&&(h=.8),zot(u)){var f=new kt.Shape({style:!1});f.mouseEnabled=!1}else u.mouseEnabled&&(u.mouseEnabled=!1);var m=this;m.cycle=t,m.decimals=n,m.alwaysHighlight=r,m.AHTime=i,m.AHColor=a,m.AHBorderWidth=l,m.AHBorderPadding=s,m.AHAlpha=c,m.AHObjectScale=h;var z,v,y,b,w,x,C,k,T=-1,A=-1,P=[],B=[],I={RadioButtons:"option",Tabs:"tab",Pad:"key"},S=g.canvas.id,E=kt.mobile(),M=!1,O=null,j=[];function D(e){var t=e.currentTarget.boundsToGlobal(),o=t.x+t.width/2,n=t.y+t.height/2;e.stageX<o-5||e.stageX>o+5||e.stageY<n-5||e.stageY>n+5?X():Y()}function L(){b&&(b.innerHTML="")}function Y(){var e,t;O=!0,F(),b&&b.setAttribute("aria-hidden",!1),kt.ACTIONEVENT="click",zns||(ACTIONEVENT="click"),g.stage.removeChild(z),m.alwaysHighlight=!1,g.stage.update();for(var o=0;o<T.length;o++)(t=(e=T[o]).obj.zimTabTag).disabled=!1,e.title=e.title.replace(/\s\(use arrow keys\)/,""),t.setAttribute("aria-label",e.title),t.addEventListener("focus",R)}function X(){O=!1;for(var e=0;e<T.length;e++)T[e].obj.zimTabTag.disabled=!1;F(),r&&function(){for(var e=0;e<P.length;e++){var t=P[e];(!t.zimObject||"Loader"!=t.zimObject.type&&"TextArea"!=t.zimObject.type&&"Tag"!=t.zimObject.type)&&(P[e].style.left="-2000px")}}()}function R(e){var t=e.currentTarget,o=t.zimObject;A=o.zimTabIndex,o.focus=!0;var n=new createjs.Event("change");n.title=t.getAttribute("aria-label"),m.dispatchEvent(n)}function _(e){O=!1,e.target.focusTab.focus()}function W(){zot(O)||O?Y():X()}function F(){M=!0,v.removeEventListener("focus",W),y.removeEventListener("focus",W),w.removeEventListener("focus",_),x.removeEventListener("focus",_),w.parentNode.removeChild(w),x.parentNode.removeChild(x),C.removeEventListener("focus",_),k.removeEventListener("focus",_),C.parentNode.removeChild(C),k.parentNode.removeChild(k);for(var e=0;e<j.length;e++)j[e][0].off("mousedown",j[e][1])}function H(e){var t=e.currentTarget;if("RadioButton"==t.type||"TabsButton"==t.type||"PadButton"==t.type)for(var o=0;o<t.zimTabParent.buttons.length;o++){var n=t.zimTabParent.buttons[o];n.zimTabTag.setAttribute("aria-label",n.zimTabTag.getAttribute("aria-label").split(" - currently")[0]+(t.zimTabParent.selectedIndex==n.tabIndex?" - currently selected.":" - currently not selected."))}m.tabIndex=e.currentTarget.zimTabIndex,m.activatedObject=t}function V(e){return e.talk?e.talk:"TextArea"==e.type||"RadioButtons"==e.type||"Tabs"==e.type||"Pad"==e.type?e.type:"Waiter"==e.type?"Waiter active - please wait":e.text?e.type+" - "+("a"==e.text||"A"==e.text?"eh":e.text):e.type+("Dial"==e.type||"Slider"==e.type||"ColorPicker"==e.type||"Stepper"==e.type?" (use arrow keys)":"")+("TextArea"==e.type?" (press ENTER to edit)":"")}function N(e){var t=e.obj;e.title=e.title.replace(/\.$/,""),"RadioButton"==t.type||"TabsButton"==t.type||"PadButton"==t.type?e.title=e.title+(t.tabIndex==t.zimTabParent.selectedIndex?" - currently selected":" - currently not selected"):"CheckBox"==t.type?e.title=e.title+(t.checked?" - currently checked":" - currently not checked"):"Stepper"==t.type?e.title=e.title+" - currently displaying "+t.currentValue:"Slider"==t.type||"Dial"==t.type?e.title=e.title+" - currently at "+kt.decimals(t.currentValue,m.decimals):"ColorPicker"==t.type?e.title=e.title+" - currently at "+t.selectedColor:"TextArea"==t.type?e.title=e.title+(""!=t.tag.value?"":" - placeholder: "+t.tag.placeholder):"Indicator"==t.type&&(e.title=e.title+" - currently "+(0<=t.selectedIndex?"at "+(t.selectedIndex+1)+" of "+t.num:"not indicating")),e.title+="."}function G(e,t,o,n,r){var i;if(n&&(d=n.obj),n&&("TextArea"==d.type||"Loader"==d.type))return(i=d.tag).setAttribute("aria-label",t),d&&i.setAttribute("aria-hidden",!d.stage),"before"==r?o.parentNode.insertBefore(i,o):o.parentNode.insertBefore(i,o.nextSibling),i.style.zIndex=-5,i.zimObject=d,n.obj.zimTabTag=i,P.push(i),i;if(!n||"Dial"!=d.type&&"Slider"!=d.type&&"Stepper"!=d.type&&"ColorPicker"!=d.type)i=document.createElement("div"),d&&(i.zimObject=d),i.innerHTML="tag",i.setAttribute("role","button");else{var a,l,s=[];if("Dial"==d.type||"Slider"==d.type)for(var c=d.step<=0?(d.max-d.min)/20:d.step,u=d.min;u<d.max;u+=c)s.push(d.min+u);else"Stepper"==d.type?s=d.stepperArray:"ColorPicker"==d.type&&(s=d.colors);(i=document.createElement("select")).disabled=!0,i.zimObject=d,i.addEventListener("change",function(e){O&&(e.currentTarget.zimObject.zimTabParent.currentValueEvent=e.target.value,g.stage.update())}),i.size=1;for(u=0;u<s.length;u++)a=s[u],(l=document.createElement("option")).setAttribute("aria-label",a),l.innerHTML=a,i.add(l),a==d.zimTabParent.currentValue&&l.setAttribute("selected","selected");i.setAttribute("role","button")}if(i.setAttribute("id",e),i.setAttribute("tabindex",0),i.setAttribute("aria-label",t),d&&i.setAttribute("aria-hidden",!d.stage),"before"==r?o.parentNode.insertBefore(i,o):o.parentNode.insertBefore(i,o.nextSibling),i.style.position="absolute",n){var d,h=(d=n.obj).boundsToGlobal();i.style.left=g.x+h.x*g.scale+"px",i.style.top=g.y+h.y*g.scale+"px",i.style.width=h.width*g.scale+"px",i.style.height=h.height*g.scale+"px",n.obj.zimTabTag=i}else i.style.left="-1000px",i.style.top=g.y+"px";return i.style.overflow="hidden",i.style.zIndex=-5,i.style.fontSize="20px",i.style.color="rgba(0,0,0,.01)",P.push(i),i}Object.defineProperty(this,"tabOrder",{get:function(){return T},set:function(e){v&&v.removeEventListener("focus",L),y&&y.removeEventListener("focus",L);for(var t=0;t<P.length;t++)P[t].parentElement&&(P[t].outerHTML="");var o,n;for(P=[],t=0;t<B.length;t++)(o=T[t])&&B[t][0].off("mousedown",B[t][1]);B=[],T=[];var r=[],i=g.canvas,a=0;for(t=0;t<e.length;t++){if("HotSpots"==(o=e[t]).type&&(e.splice.apply(e,[t,1].concat(o.hotSpots)),o=o.hotSpots[0]),"HotSpot"==o.type&&(o=o.spot),o.constructor=={}.constructor){if(!(n=o.obj)||!n.getStage)continue;o.title||(o.title=V(n))}else o={obj:n=o,title:V(o)};if("RadioButtons"==n.type||"Tabs"==n.type||"Pad"==n.type){var l=[];a--;for(var s=0;s<n.buttons.length;s++){a++;var c=n.buttons[s],u={obj:c,title:o.title+" - "+I[n.type]+": "+("a"==c.text||"A"==c.text?"eh":c.text)};l.push(u),c.zimTabParent=n,c.zimTabParent.zimAccessibility=m,c.zimTabIndex=t+a,c.tabIndex=s,c.zimAccessibility=m,N(u),i=G(S+"Tab"+(t+a),u.title,i,u),B.push([c,c.on("mousedown",H)]),M||j.push([c,c.on("mousedown",D)])}r=r.concat(l)}else n.zimTabIndex=t+a,n.zimTabParent=n,N(o),n.zimAccessibility=m,B.push([n,n.on("mousedown",H)]),M||j.push([n,n.on("mousedown",D)]),r.push(o),i=G(S+"Tab"+(t+a),o.title,i,o)}(v=m.startAppTag=G(S+"PrefixTab",d+" start",g.canvas,null,"before")).addEventListener("focus",L),M||(v.addEventListener("focus",W),(w=G(S+"noAriaTab","",v,null,"before")).setAttribute("aria-hidden",!0),w.focusTab=v,w.addEventListener("focus",_),(C=G(S+"noAriaTab","",v)).setAttribute("aria-hidden",!0),C.focusTab=v,C.addEventListener("focus",_)),i=G(S+"BufferTab","",i),E&&i.setAttribute("aria-hidden",!0),i=y=m.endAppTag=G(S+"SuffixTab",d+" end",i),y.addEventListener("focus",L),M||(y.addEventListener("focus",W),i=x=G(S+"noAriaTab","",y),x.setAttribute("aria-hidden",!0),x.focusTab=y,x.addEventListener("focus",_),(k=G(S+"noAriaTab","",y,null,"before")).setAttribute("aria-hidden",!0),k.focusTab=y,k.addEventListener("focus",_)),T=r}}),Object.defineProperty(this,"tabIndex",{get:function(){return A},set:function(e){if(_state)if(e<0||e>=T.length)u();else{e!=A&&c();var t=T[e].obj;if(t.stage){if(A=e,t.focus=!0,K=!(U=!0),m.changeTitle(t),t.zimTabTag.focus(),setTimeout(function(){t.zimTabTag.focus();var e=new createjs.Event("change");e.title=t.zimTabTag.getAttribute("aria-label"),m.dispatchEvent(e)},150),m.alwaysHighlight&&!O){if(m.AHObject){z=m.AHObject;var o=kt.boundsToGlobal(t);m.AHObject.alp(m.AHAlpha).addTo(g.stage,null,!1),m.AHObject.fit(o.x,o.y,o.width,o.height),m.AHObject.sca(m.AHObject.scaleX*m.AHObjectScale),0<m.AHTime&&(q=setTimeout(function(){g.stage.removeChild(m.AHObject),g.stage.update()},m.AHTime))}else{z=f;var n=t.getBounds(),r=t.localToGlobal(n.x-5,n.y-5),i=t.localToGlobal(n.x+n.width+5,n.y-5),a=t.localToGlobal(n.x+n.width+5,n.y+n.height+5),l=t.localToGlobal(n.x-5,n.y+n.height+5),s=f.graphics;s.clear(),s.s(m.AHColor).ss(m.AHBorderWidth).mt(r.x,r.y).lt(i.x,i.y).lt(a.x,a.y).lt(l.x,l.y).lt(r.x,r.y).cp(),f.alpha=m.AHAlpha,0<m.AHTime&&(q=setTimeout(function(){g.stage.removeChild(f),g.stage.update()},m.AHTime))}g.stage.addChild(z),g.stage.update()}}else u()}function c(){if(A&&-1<A)T&&T[A]&&(T[A].obj.focus=!1);else for(var e=0;e<T.length;e++)T[e].obj.focus=!1}function u(){c(),U=!1,m.AHObject&&g.stage.removeChild(m.AHObject),m.alwaysHighlightShape&&g.stage.removeChild(m.alwaysHighlightShape),g.stage.update(),A=-1}}}),Object.defineProperty(this,"aria",{get:function(){return O},set:function(e){(O=e)&&Y()}}),zot(e)?setTimeout(function(){if(-1==T){T=[];var t=[];kt.loop(g.stage,function(e){e.type&&t.push(e)}),m.tabOrder=t,zot(o)||(m.tabIndex=o)}},50):(T=[],m.tabOrder=e,zot(o)||(m.tabIndex=o));var q,U=!1,K=!0,Z=g.on("keydown",function(e){var t;if(9==e.keyCode&&(function(){for(var e=!1,t=0;t<P.length;t++)if(document.activeElement==P[t]){e=!0;break}return!(document.activeElement!=g.canvas&&!e)}()||(U=!1,-1!=m.tabIndex&&(m.tabIndex=-1)),U?Q(e):(t=e,g.shiftKey||zid(S+"PrefixTab")!=document.activeElement&&g.canvas!=document.activeElement?!g.shiftKey||zid(S+"SuffixTab")!=document.activeElement&&zid(S+"BufferTab")!=document.activeElement||(0<T.length&&(T[0].obj.focus=!0),U=K=!0,Q(t)):(0<T.length&&(T[T.length-1].obj.focus=!0),U=K=!0,Q(t)))),U&&0<T.length&&0<=m.tabIndex&&13==e.keyCode){var o=T[m.tabIndex],n=o.obj;if(o&&n.stage){var r=new createjs.Event("mousedown"),i=new createjs.Event("click");r.fromEnter=i.fromEnter=!0,"Pane"==n.type?(n.backdrop.dispatchEvent(r),n.backdrop.dispatchEvent(i)):(n.dispatchEvent(r),n.dispatchEvent(i))}}});function Q(e){e.ctrlKey?J(e.shiftKey?-1:1):(e.shiftKey?m.tab(-1):m.tab(1),e.preventDefault())}function J(e){U=!1,zid(S+(1==e?"SuffixTab":"PrefixTab")).focus(),g.stage.removeChild(u),g.stage.update(),m.tabIndex=-1}this.tab=function(e){if(clearTimeout(q),z&&g.stage.removeChild(z),zot(e)&&(e=1),0!=T.length)for(var t=0;t<T.length;t++){var o=T[t].obj;if(o.focus){o.focus=!1;var n=t+e,r=(n+1e4*T.length)%T.length,i=T[r];o=i.obj;for(var a=0,l=!1;!o.stage||!(!o.zimTabParent&&(zot(o.enabled)||o.enabled)||o.zimTabParent&&(zot(o.zimTabParent.enabled)||o.zimTabParent.enabled));)if(a++,r=((n+=e)+100*T.length)%T.length,o=(i=T[r]).obj,a==T.length){l=!0;break}if(l||!m.cycle&&n!=r&&!K)return void J(e);K=!1,m.tabIndex=r;break}}else J(e)};var $=!(this.changeTitle=function(e,t,o){if("number"!=typeof e&&(e=e.zimTabIndex),!zot(e))if(o&&zot(t))m.tabIndex=e;else{var n=T[e],r=n.obj;zot(t)&&(t=r.zimTabTag.getAttribute("aria-label").split(" - currently")[0]),n.title=t,N(n),r.zimTabTag.setAttribute("aria-label",n.title),o&&(m.tabIndex=e)}});this.talk=function(e){$||((b=G(S+"TalkTab","",y)).setAttribute("role","alert"),$=!0),b.setAttribute("aria-label",e),b.innerHTML=" ",b.innerHTML=e,zog(b.innerHTML);var t=new createjs.Event("change");t.title=e,m.dispatchEvent(t)},this.resize=function(e){if(zot(e)){if(m.alwaysHighlight&&!zot(O))return;for(var t=0;t<T.length;t++)n(T[t].obj)}else{if("number"!=typeof e&&(e=e.zimTabIndex),e<0)return;var o=T[e].obj;if(!o.stage&&z&&o==m.currentObject&&(g.stage.removeChild(z),g.stage.update()),m.alwaysHighlight&&!zot(O))return;n(o)}function n(e){if("TextArea"!=e.type&&"Loader"!=e.type){var t=e.boundsToGlobal(),o=e.zimTabTag;o.style.left=g.x+t.x*g.scale+"px",o.style.top=g.y+t.y*g.scale+"px",o.style.width=t.width*g.scale+"px",o.style.height=t.height*g.scale+"px",o.setAttribute("aria-hidden",!e.stage),o.hidden=!e.stage}else e.resize()}},Object.defineProperty(this,"currentObject",{get:function(){return T[A]&&T[A].obj?T[A].obj:null},set:function(e){for(var t=0;t<T.length;t++)if(T[t].obj==e){m.tabIndex=t;break}}}),_state=!0,Object.defineProperty(this,"enabled",{get:function(){return _state},set:function(e){_state=e}}),this.dispose=function(){m.tabOrder=[];for(var e=0;e<P.length;e++)P[e].parentElement&&(P[e].outerHTML="");m.removeAllEventListeners(),g.off("keydown",Z)}},kt.extend(kt.Accessibility,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.Manager=function(e){z_d("75");var r=this;this.type=e,this.items=[],this.add=function(e){Array.isArray(e)?r.items=r.items.concat(e):r.items.push(e)},this.remove=function(e){if(zot(e))r.items=[];else{var t;Array.isArray(e)||(e=[e]);for(var o=0;o<e.length;o++){t=e[o];var n=r.items.indexOf(t);-1!=n&&r.items.splice(n,1)}}},this.resize=function(){if(r)for(var e=0;e<r.items.length;e++)r.items[e].resize?r.items[e].resize():r.items.splice(e)},this.toggle=function(e){if(r)for(var t=0;t<r.items.length;t++)r.items[t].toggle?r.items[t].toggle(e):r.items.splice(t)},this.dispose=function(){for(var e=r.items.length-1;0<=e;e--)r.items[e].dispose();return r.items=[],!(r=null)}},kt.ResizeManager=function(){z_d("75.5"),kt.Manager.call(this,"ResizeManager")},kt.ResizeManager.prototype=new kt.Manager,kt.ResizeManager.prototype.constructor=kt.ResizeManager,kt.TransformManager=function(e,r){z_d("75.7");var a=this;function l(e){!localStorage||e&&!e.pressup||a.savePersist(e)}this.type="TransformManager",this.items=[],this.add=function(e){var t,o=[];o=Array.isArray(e)?e:[e];for(var n=!1,r=0;r<o.length;r++)t=o[r],0==a.items.length&&0==r&&(n=!0),"Blob"==t.type||"Squiggle"==t.type?(a.persistID||(n?(n=!1,t.controlsVisible=!0,a.currentObject=t):t.controlsVisible=!1),t.on("change",function(e){var t=new createjs.Event("transformed");t.transformObject=e.target,t.transformType=e.controlType,a.dispatchEvent(t)}),t.on("controlsshow",function(e){var t=new createjs.Event("transformshow");a.currentObject=t.transformObject=e.target,a.dispatchEvent(t)}),t.on("controlshide",function(e){var t=new createjs.Event("transformhide");t.transformObject=e.target,a.currentObject=null,a.dispatchEvent(t)}),t.on("update",function(e){var t=new createjs.Event("transformed");t.transformObject=e.target,t.transformType=e.controlType,a.dispatchEvent(t)})):(transObj=t.transformControls,a.persistID||(n&&"Layer"!=t.type?(n=!1,transObj&&transObj.visible&&transObj.show(),a.currentObject=t):transObj&&transObj.hide()),t.on("transformed",function(e){var t=new createjs.Event("transformed");t.transformObject=e.target,t.transformType=e.transformType,a.dispatchEvent(t)}),t.on("transformshow",function(e){var t=new createjs.Event("transformshow");a.currentObject=t.transformObject=e.target,a.dispatchEvent(t)}),t.on("transformhide",function(e){var t=new createjs.Event("transformhide");t.transformObject=e.target,a.currentObject=null,a.dispatchEvent(t)}));a.items=a.items.concat(e)},this.remove=function(e){if(zot(e))a.items=[];else{var t;Array.isArray(e)||(e=[e]);for(var o=0;o<e.length;o++){t=e[o],a.currentObject==t&&(a.currentObject=null),t.transformedEvent&&(t.off("transformed",t.transformedEvent),t.transformedEvent=null),"Blob"==t.type||"Squiggle"==t.type?t.controlsVisible=!1:t.transformControls.remove();var n=a.items.indexOf(t);-1!=n&&a.items.splice(n,1)}r&&a.savePersist()}},this.show=function(e){if(!zot(e)){if("Blob"==e.type||"Squiggle"==e.type)e.controlsVisible||(e.controlsVisible=!0);else{var t=e.transformControls;if(!t||t.visible)return;t.show()}a.currentObject=e}},this.hide=function(e){if(!zot(e))if(a.currentObject==e&&(a.currentObject=null),"Blob"==e.type||"Squiggle"==e.type)e.controlsVisible&&(e.controlsVisible=!1);else{var t=e.transformControls;if(!t||t.visible)return;t.hide()}},this.hideAll=function(e){for(var t,o,n=0;n<a.items.length;n++)if((o=a.items[n])&&(o.transformControls||o.update)){if(a.items[n]==e)continue;"Blob"==o.type||"Squiggle"==o.type?o.controlsVisible&&(o.controlsVisible=!1):(t=a.items[n].transformControls).visible&&t.hide()}else a.items.splice(n);a.currentObject=null},this.resize=function(){if(a){for(var e,t=0;t<a.items.length;t++)(e=a.items[t])&&(e.transformControls||e.update)?"Blob"==e.type||"Squiggle"==e.type?e.update():e.transformControls.resize():a.items.splice(t);r&&a.savePersist()}},zot(e)||a.add(e);var s="TransformManager persist(persistID) - sorry, must provide id";this.persist=function(e){if(zot(e)&&zon)zog(s);else{a.persistID=e;var t,n=0;if(localStorage&&localStorage[e]){var r=a.persistData=JSON.parse(localStorage[e]);if(r.length==a.items.length)for(var i=0;i<a.items.length;i++)r[i].controlsVisible&&(a.currentObject=a.items[i]),!r[i]||"Blob"!=r[i].type&&"Squiggle"!=r[i].type?r[i]&&(zot(a.items[i].transformControls)?function(){var t=a.items[i],o=r[i];interval(50,function(e){t.transformControls&&(t.transformControls.setData(o),t.dispatchEvent("persistset"),++n==r.length&&setTimeout(function(){a.dispatchEvent("persistcomplete")},100),e.clear())},20)}():(a.items[i].transformControls.setData(r[i]),function(){var t=a.items[i];timeout(50,function(e){t.dispatchEvent("persistset"),++n==r.length&&setTimeout(function(){a.dispatchEvent("persistcomplete")},100)})}())):(a.items[i].points.length!=r[i].points.length&&(a.items[i].points=r[i].points),a.items[i].setData(r[i]))}for(i=0;i<a.items.length;i++)(t=a.items[i]).transformedEvent||("Blob"==t.type||"Squiggle"==t.type?(t.transformedEvent=t.on("change",l),t.transformedEvent=t.on("update",l),t.transformedEvent=t.on("controlsshow",l),t.transformedEvent=t.on("controlshide",l)):(t.transformedEvent=t.on("transformed",l),t.transformedEvent=t.on("transformshow",l),t.transformedEvent=t.on("transformhide",l)))}},this.savePersist=function(e){for(var t=[],o=0;o<a.items.length;o++)it=a.items[o],"Blob"==it.type||"Squiggle"==it.type?it.recordData&&t.push(it.recordData()):it.transformControls&&it.transformControls.recordData&&t.push(it.transformControls.recordData());a.persistData=t,localStorage[a.persistID]=JSON.stringify(t)},this.clearPersist=function(e){zot(e)&&zon?zog(s):(a.persistData=null,localStorage&&localStorage.removeItem(e))},this.stopPersist=function(){for(var e=0;e<a.items.length;e++)it=a.items[e],it.transformedEvent&&("Blob"==it.type||"Squiggle"==it.type?it.off("change",it.transformedEvent):it.off("transformed",it.transformedEvent),it.transformedEvent=null);a.persistData=null},zot(r)||a.persist(r),this.dispose=function(e,t){if(zot(e)&&(e=!0),a.removeAllEventListeners(),a.persistID&&e&&a.stopPersist(),t)for(var n=0;n<a.items.length;n++)o=a.items[n],"Blob"==o.type||"Squiggle"==o.type?o.dispose():o.transformControls.dispose()}},kt.extend(kt.TransformManager,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.GuideManager=function(){z_d("77"),kt.Manager.call(this,"GuideManager")},kt.GuideManager.prototype=new kt.Manager,kt.GuideManager.prototype.constructor=kt.GuideManager,kt.GridManager=function(){z_d("79"),kt.Manager.call(this,"GridManager")},kt.GridManager.prototype=new kt.Manager,kt.GridManager.prototype.constructor=kt.GridManager,kt.LayoutManager=function(){z_d("81"),this.type="LayoutManager";var t=this;this.items=[],this.add=function(e){t.items.push(e)},this.resize=function(){for(var e=0;e<t.items.length;e++)t.items[e].resize()},this.disable=function(){for(var e=0;e<t.items.length;e++)t.items[e].disable()},this.enable=function(){for(var e=0;e<t.items.length;e++)t.items[e].enable()},this.dispose=function(){for(var e=0;e<t.items.length;e++)t.items[e].removeShape();return!0}},kt.SelectionSet=function(e){z_d("81.5"),this.type="SelectionSet",zot(e)&&(e=[]),this.selections=e,this.clear=function(){this.selections=[]},this.isSelected=function(e){return 0<=this.selections.indexOf(e)},this.add=function(e,t,o,n){if(!zot(e)&&(zot(t)&&(zot(this.selectionManager)||(t=this.selectionManager.multiple)),zot(this.selectionManager)||(this.selectionManager.setCurrent(this),!t&&this.selectionManager.multipleSets&&this.selectionManager.clear()),t||this.clear(),!(0<=this.selections.indexOf(e)))){if(this.selections.push(e),!zot(o)){Array.isArray(o)||(o=[o]);for(var r=0;r<=o.length;r++)o[r].add(e,t)}if(!zot(n))for(Array.isArray(n)||(n=[n]),r=0;r<=n.length;r++)n[r].remove(e,t)}},this.remove=function(e,t,o,n){if(!zot(e)){zot(t)&&(zot(this.selectionManager)||(t=this.selectionManager.multiple)),zot(this.selectionManager)||this.selectionManager.setCurrent(this),t||this.clear();var r=this.selections.indexOf(e);if(zot(this.selectionManager)||(this.selectionManager.setCurrent(this),!t&&this.selectionManager.multipleSets&&this.selectionManager.clear()),t||this.clear(),t?0<=r&&this.selections.splice(r,1):this.clear(),!zot(o)){Array.isArray(o)||(o=[o]);for(var i=0;i<=o.length;i++)o[i].remove(e,t)}if(!zot(n))for(Array.isArray(n)||(n=[n]),i=0;i<=n.length;i++)n[i].add(e,t)}},this.toggle=function(e,t,o,n){this.isSelected(e)?this.remove(e,t,o,n):this.add(e,t,o,n)},this.dispose=function(){return this.clear(),!(this.selections=null)}},kt.SelectionManager=function(o,e,t){z_d("81.6"),this.cjsEventDispatcher_constructor(),this.type="SelectionManager",zot(o)&&(o=[]),zot(t)&&(t=!0),Array.isArray(o)||(o=[o]),this.sets=o,this.multipleKey=e,this.multipleSets=t,this.multiple=!1;for(var n=this,r=0;r<o.length;r++)o[r].selectionManager=this;this.clear=function(){this.currentSet=null;for(var e=0;e<o.length;e++)o[e].clear()},this.setCurrent=function(e){this.currentSet=e;for(var t=0;t<o.length;t++)o[t]!=e&&(this.multipleSets||o[t].clear())};var i=new createjs.Event("keydown");this.eventRemove=i.remove,this.keydownEvent=window.addEventListener("keydown",function(e){e.remove=n.eventRemove,n.multipleKey&&(n.multiple=e[n.multipleKey+"Key"]),n.ctrlKey=e.ctrlKey,n.shiftKey=e.shiftKey,n.metaKey=e.metaKey,n.dispatchEvent(e),90==e.keyCode&&(n.ctrlKey||n.metaKey)&&n.dispatchEvent("undo")}),this.keyupEvent=window.addEventListener("keyup",function(e){n.multipleKey&&(n.multiple=e[n.multipleKey+"Key"]),n.ctrlKey=e.ctrlKey,n.shiftKey=e.shiftKey,n.metaKey=e.metaKey,e.remove=n.eventRemove,n.dispatchEvent(e)}),this.dispose=function(){window.removeEventListener("keydown",this.keydownEvent),window.removeEventListener("keyup",this.keyupEvent)}},kt.extend(kt.SelectionManager,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.Swipe=function(e,t,o){var n;if(n=zob(kt.Swipe,arguments,"obj, distance, duration",this))return n;if(z_d("70"),this.cjsEventDispatcher_constructor(),this.type="Swipe",!zot(e)&&e.on){var r,i,a,l,s,c;zot(t)&&(t=30),zot(o)&&(o=80),this.distance=t,this.duration=o,this.active=!0;var u=this;e.on("mousedown",function(t){function o(){var e=new createjs.Event("swipe");e.obj=u.obj,e.stageX=t.stageX,e.stageY=t.stageY,e.rawX=t.rawX,e.rawY=t.rawY,e.swipeX=e.swipeY=0,u.direction="none",Math.abs(a-r)>Math.abs(l-i)?(a-r>u.distance&&(e.swipeX=1,u.direction="right"),r-a>u.distance&&(e.swipeX=-1,u.direction="left")):(l-i>u.distance&&(e.swipeY=1,u.direction="down"),i-l>u.distance&&(e.swipeY=-1,u.direction="up")),u.dispatchEvent(e)}u.active&&!t.target.zimNoSwipe&&(u.obj=t.target,a=r=t.stageX,l=i=t.stageY,s=!0,u.dispatchEvent("swipedown"),clearTimeout(c),c=setTimeout(function(){s&&(o(),s=!1)},u.duration),e.on("pressmove",function(e){a=e.stageX,l=e.stageY}),e.on("pressup",function(e){s&&(o(),s=!1,clearTimeout(c))}))}),this.disable=function(){u.active=!1},this.enable=function(){u.active=!0}}else zog("zim controls - Swipe():\nPlease pass in object")},kt.extend(kt.Swipe,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.Swiper=function(e,t,o,n,r,i,a,l,s,c,u){var d;if(d=zob(kt.Swiper,arguments,"swipeOn, target, property, sensitivity, horizontal, min, max, damp, integer, factor, pauseTime",this))return d;if(z_d("69.5"),this.cjsEventDispatcher_constructor(),this.type="Swiper",!zot(e)&&e.getStage&&e.stage){if(!zot(t)){zot(n)&&(n=1),zot(r)&&(r=!0),zot(l)&&(l=.1),zot(s)&&(s=!1),zot(c)&&(c=1),zot(u)&&(u=200);var h,g,p,f,m,z,v=this,y=e,b=v.desiredValue=t[o];this.target=t,this.property=o;var w=!1;y.canvas?(f=y.on("stagemousedown",function(e){w=!0,A(e),m=y.on("stagemousemove",P),z=y.on("stagemouseup",function(){w=!1,y.off("stagemousemove",m),y.off("stagemouseup",z),v.dispatchEvent("swipeup")})}),p=y):(p=y.stage,B(),f=y.on("mousedown",A),m=y.on("pressmove",P),z=y.on("pressup",function(){w=!1,v.dispatchEvent("swipeup")}));var x=new kt.Damp(v.target[v.property],l),C=(v.target[v.property],0),k=null;v.target.swiperTicker=kt.Ticker.add(function(){b==C?b!=k&&(v.pauseTimeout&&v.pauseTimeout.clear(),k=b,v.pauseTimeout=kt.timeout(u,function(){v.dispatchEvent("swipepause"),v.pauseTimeout=null})):(k=null,C=b,v.pauseTimeout&&v.pauseTimeout.clear()),v.swiperMoving&&(v.target[v.property]=s?Math.round(x.convert(b)):x.convert(b),!w&&Math.abs(v.target[v.property]-b)<(zot(i)||zot(a)?1:Math.abs(a-i)/1e3)?(v.swiperMoving=!1,v.target[v.property]=b,v.immediate(v.target[v.property]),v.dispatchEvent("swipestop")):v.target[v.property])},p),this.immediate=function(e){x.immediate(e),v.target[v.property]=s?Math.round(e):e,v.desiredValue=b=e};var T=!0;Object.defineProperty(v,"enabled",{get:function(){return T},set:function(e){T!=e&&(e?function(){y.canvas?f=y.on("stagemousedown",f):(f=y.on("mousedown",f),m=y.on("pressmove",m),z=y.on("pressup",z));v.immediate(v.target[v.property]),v.target.swiperTicker=kt.Ticker.add(v.target.swiperTicker,p)}():I(),T=Boolean(e))}}),this.dispose=function(){I(),x=null}}}else zog("zim.Swiper() - please provide container on stage");function A(e){w=!0,h=r?e.stageX:e.stageY,g=v.target[v.property],v.dispatchEvent("swipedown")}function P(e){var t=h-(r?e.stageX:e.stageY);0<Math.abs(t)&&(v.swiperMoving=!0),b=g-t*n*c,zot(i)||(b=Math.max(b,i)),zot(a)||(b=Math.min(b,a)),v.desiredValue=b,v.dispatchEvent("swipemove")}function B(){y.off("mousedown",f),y.off("pressmove",m),y.off("pressup",z)}function I(){y.canvas?(y.off("stagemousedown",f),y.off("stagemousemove",m),y.off("stagemouseup",z)):B(),kt.Ticker.remove(v.target.swiperTicker)}},kt.extend(kt.Swiper,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.MotionController=function(a,i,e,t,o,r,l,n,s,c,u,d,h,g,p,f,m,z,v,y,b,w){var x,C;if(x=zob(kt.MotionController,arguments,"target, type, speed, axis, boundary, map, diagonal, damp, flip, rotate, constant, firstPerson, turnSpeed, moveThreshold, stickThreshold, container, localBounds, mouseMoveOutside, mousedownIncludes, minPercentSpeed, maxPercentSpeed, dampKeyup",this))return x;z_d("69.7"),this.cjsEventDispatcher_constructor(),this.type="MotionController";var k="zim MotionController(): Please pass in a reference to the stage or a container on the stage";if(zot(f)){if(!zimDefaultFrame)return void zog(k);C=f=zimDefaultFrame.stage}else if(zot(f.stage)){if(!zimDefaultFrame)return void zog(k);C=zimDefaultFrame.stage}else C=f.stage;zot(a)&&(a=new kt.Container(1,1,null,null,!1));var T="Accelerator"==a.type;zot(e)&&(e=7),(zot(i)||"mousemove"!=i&&"pressmove"!=i&&"keydown"!=i&&"gamebutton"!=i&&"gamestick"!=i&&"swipe"!=i&&"manual"!=i)&&(i="mousedown"),zot(t)&&(t=T?"horizontal":"both"),"keydown"==i&&zot(r)&&(r=[[65,37],[68,39],[87,38],[83,40]]),"gamebutton"==i&&zot(r)&&(r=d?[14,15,kt.GamePad.RT,kt.GamePad.LT]:[14,15,12,13]),"gamestick"==i&&zot(r)&&(r=d?[[0,2],[0,2],[1],[1]]:[0,0,1,1]),"gamestick"==i&&zot(r)&&(r=[0,0,1,1]),zot(l)&&(l=!0),"horizontal"!=t&&"vertical"!=t||(l=!1),zot(n)&&(n="keydown"==i||"gamebutton"==i?1:"pressmove"==i?.2:.1),zot(d)&&(d=!1),zot(h)&&(h=.4*e),zot(g)&&(g=4),zot(p)&&(p=.2),zot(z)&&(z=!1),C.mouseMoveOutside=z,zot(v)&&(v=[]),Array.isArray(v)||(v=[v]),"Pen"!=a.type||a.draggable?v.push(a):v.push(a,a.paper),this.mousedownIncludes=v,zot(w)&&(w=.3);var A=this;A.dampKeyup=w,this.dirX=0,this.dirY=0,this.speed=e,this.turnSpeed=h,this.axis=t,this.target=a,this.moveThreshold=g,this.stickThreshold=p,this.boundary=o;var P,B,I,S=A.speed,E=A.speed,M=0;(A.rotation=0,T)?(I=!(B=f.getBounds())||"vertical"==t&&!B.height||"vertical"!=t&&!B.width?1e3:"vertical"==t?B.height:B.width,zot(y)&&(y=0),zot(b)&&(b=100),zot(this.target.percentSpeed)&&(this.target.percentSpeed=(b-y)/2),A.x=I/2,A.y=I/2,P=new kt.Proportion(0,I,y,b)):(A.x=this.target.x,A.y=this.target.y);var O,j,D,L=A.scaleX=a.scaleX,Y=(A.scaleY=a.scaleY,!1),X=!1;if("keydown"==i||"gamebutton"==i){for(var R=0;R<4;R++)Array.isArray(r[R])||(r[R]=[r[R]]);var _=[0,0,0,0],W=[],F=["X","X","Y","Y"],H=[-1,1,-1,1],V={dirX:0,dirY:0};if("keydown"==i)var N=frame.on("keydown",q);else var G=($=A.gamepad=new kt.GamePad).on("buttondown",q);function q(e){var t,o="keydown"==i?e.keyCode:e.buttonCode;for(R=0;R<4;R++)if(-1<r[R].indexOf(o)){if(l||"both"!=A.axis||(V.dirX=V.dirY=0),V["dir"+F[R]]=H[R],_[R]=1,0==(t=W.indexOf(R)))return;return 0<t&&W.splice(t,1),void W.unshift(R)}}if(zot(u))if("keydown"==i)var U=frame.on("keyup",Z);else var K=$.on("buttonup",Z);function Z(e){var t,o="keydown"==i?e.keyCode:e.buttonCode;for(R=0;R<4;R++)if(-1<r[R].indexOf(o)){if((_[R]=0)<=(t=W.indexOf(R))&&W.splice(t,1),"both"!=A.axis||l)V["dir"+F[R]]=-_[2*Math.floor(R/2)]+_[2*Math.floor(R/2)+1];else if(0<W.length){V["dir"+F[R]]=0;var n=W[0];V["dir"+F[n]]=H[n]}else V.dirX=V.dirY=0;return}}var Q={rotation:0,speedX:A.speed,speedY:A.speed},J=kt.Ticker.add(function(){if(d)re(V);else{var e=A.speed,t=A.speed;if("both"==A.axis&&0!=V.dirX&&0!=V.dirY){var o=le(V.dirX,V.dirY);e=o.speedX,t=o.speedY}"horizontal"!=A.axis&&"both"!=A.axis||(A.x+=e*V.dirX),"vertical"!=A.axis&&"both"!=A.axis||(A.y+=t*V.dirY),ie()}},C)}else if("mousedown"==i||"mousemove"==i)O=C.on("stage"+i,function(e){if("mousedown"==i){if(Array.isArray(A.mousedownIncludes)||(A.mousedownIncludes=[A.mousedownIncludes]),A.mousedownIncludes.indexOf(f)<0)for(var t=0;t<f.numChildren;t++){var o=f.getChildAt(t);if(-1==A.mousedownIncludes.indexOf(o)&&o.mouseEnabled&&o.hitTestPoint&&o.hitTestPoint(e.stageX,e.stageY))return}A.dispatchEvent("mousedown")}var n=f.globalToLocal(z?e.rawX:e.stageX,z?e.rawY:e.stageY);A.x=n.x,A.y=n.y,ie()});else if("pressmove"==i)"Pen"==a.type&&(a.write=!1),O=C.on("stagemousedown",function(e){X=!1,Array.isArray(A.mousedownIncludes)||(A.mousedownIncludes=[A.mousedownIncludes]);for(var t=!1,o=C.getObjectUnderPoint(e.stageX,e.stageY),n=0;n<A.mousedownIncludes.length;n++)A.mousedownIncludes[n].hitTestPoint&&A.mousedownIncludes[n].hitTestPoint(e.stageX,e.stageY)&&A.mousedownIncludes[n].contains(o)&&(t=!0);if(!t)for(n=0;n<f.numChildren;n++){var r=f.getChildAt(n);if(-1==A.mousedownIncludes.indexOf(r)&&r.mouseEnabled&&r.hitTestPoint&&r.hitTestPoint(e.stageX,e.stageY))return}var i=f.globalToLocal(z?e.rawX:e.stageX,z?e.rawY:e.stageY);A.immediate(i.x,i.y),ie(),A.dispatchEvent("mousedown"),Y=!0,j=C.on("stagemousemove",function(e){var t=f.globalToLocal(z?e.rawX:e.stageX,z?e.rawY:e.stageY);A.x=t.x,A.y=t.y,ie(),"Pen"==a.type&&!X&&a.drawing&&(X=!0)}),"Pen"==a.type&&(a.write=!0,a.zimDragCheck=!0)}),D=C.on("stagemouseup",function(e){"Pen"==a.type&&(a.write=!1,a.zimDragCheck=!1,X&&a.stopCheck()),C.off("stagemousemove",j),Y=!1});else if("gamestick"==i){var $=this.gamepad=new kt.GamePad;for(R=0;R<4;R++)Array.isArray(r[R])||(r[R]=[r[R]]);Q={rotation:0,speedX:A.speed,speedY:A.speed};var ee=$.on("data",function(e){for(var t={dirX:0,dirY:0},o=0;o<r[0].length;o++){var n=e.axes[r[0][o]];if(Math.abs(n)>A.stickThreshold){t.dirX=n;break}}for(o=0;o<r[2].length;o++){n=e.axes[r[2][o]];if(Math.abs(n)>A.stickThreshold){t.dirY=n;break}}d?re(t):(A.x+=A.speed*t.dirX,A.y+=A.speed*t.dirY,ie())})}else if("swipe"==i)var te=new kt.Swiper(C,A,"x",.8),oe=new kt.Swiper(C,A,"y",.8,!1),ne=te.on("swipemove",function(){ie()});function re(e){Q.rotation+=e.dirX*A.turnSpeed,A.rotation=Q.rotation,Q.speedX=Math.sin(Q.rotation*Math.PI/180)*A.speed*-e.dirY,Q.speedY=-Math.cos(Q.rotation*Math.PI/180)*A.speed*-e.dirY,A.x+=Q.speedX,A.y+=Q.speedY}function ie(){var e=le(A.x-(T?A.target.percentSpeed:A.target.x),A.y-(T?A.target.percentSpeed:A.target.y));if(S=e.speedX,E=e.speedY,c)if(A.rotation=e.angle,zot(A.rotation))A.rotation=A.target.rotation;else{A.rotation+=M;var t=ae(A.rotation),o=A.target.rotation=ae(A.target.rotation);180<Math.abs(t-o)&&(t<o?o-=360:t-=360),A.dampR.immediate(o),A.target.rotation=o,A.rotation=t}}function ae(e){return(e%360+360)%360}function le(e,t){var o,n=A.speed,r=A.speed,i=Math.sqrt(Math.pow(e,2)+Math.pow(t,2));return 0<i&&(n=Math.abs(e)/i*A.speed,r=Math.abs(t)/i*A.speed,o=90-180*Math.atan2(e,t)/Math.PI),{speedX:n,speedY:r,angle:o}}var se=this.x=T?I/2:this.target.x,ce=this.y=T?I/2:this.target.y;this.dampX=new kt.Damp(se,n),this.dampY=new kt.Damp(ce,n),this.dampR=new kt.Damp(this.target.rotation,n);var ue=0,de=0,he=kt.Ticker.add(function(){if("manual"==i&&ie(),A.boundary&&(A.x=kt.constrain(A.x,A.boundary.x,A.boundary.x+A.boundary.width),A.y=kt.constrain(A.y,A.boundary.y,A.boundary.y+A.boundary.height)),"horizontal"==A.axis||"both"==A.axis){if(A.dirX=kt.sign(A.x-se),Math.abs(A.x-se)<S?se=A.x:se+=A.dirX*S,0==V.dirX){var e=A.boundary?A.boundary.width/2:C.width/2,t=A.x-(A.x-e)*A.dampKeyup;se=t,A.x=se}T&&B&&B.width?A.target.percentSpeed=P.convert(A.dampX.convert(se)):A.target.x=A.dampX.convert(se)}if("vertical"==A.axis||"both"==A.axis){if(A.dirY=kt.sign(A.y-ce),Math.abs(A.y-ce)<E?ce=A.y:ce+=kt.sign(A.y-ce)*E,0==V.dirY){e=A.boundary?A.boundary.height/2:C.height/2;var o=A.y-(A.y-e)*A.dampKeyup;ce=o,A.y=ce}T&&B&&B.height?A.target.percentSpeed=P.convert(A.dampY.convert(ce)):A.target.y=A.dampY.convert(ce)}if("pressmove"==i&&Y&&A.dispatchEvent("pressing"),A.movingX=Math.abs(se-(T?A.target.percentSpeed:A.target.x))>A.moveThreshold,A.movingY=Math.abs(ce-(T?A.target.percentSpeed:A.target.y))>A.moveThreshold,!A.moving||A.movingX||A.movingY?A.moving||!A.movingX&&!A.movingY||A.dispatchEvent("startmoving"):A.dispatchEvent("stopmoving"),A.moving=A.movingX||A.movingY,A.moving&&A.dispatchEvent("moving"),A.dirX!=ue||A.dirY!=de){var n=new createjs.Event("change");if(A.dirX!=ue){var r=["left",null,"right"];n.dir=r[A.dirX+1],ue=A.dirX,"horizontal"!=s&&"both"!=s||(A.scaleX=a.scaleX=A.dirX?Math.abs(a.scaleX)*A.dirX:a.scaleX,M=0!=L&&-1==Math.round(A.scaleX/L)?180:0)}else{r=["up",null,"down"];n.dir=r[A.dirY+1],de=A.dirY,"vertical"!=s&&"both"!=s||(A.scaleY=a.scaleY=A.dirY?Math.abs(a.scaleY)*-A.dirY:a.scaleY)}A.dispatchEvent(n)}c&&!zot(A.rotation)&&(A.target.rotation=A.dampR.convert(A.rotation))},C);this.immediate=function(e,t,o){return!zot(e)&&A.dampX&&(A.dampX.immediate(e),A.x=T?A.target.percentSpeed=se=e:A.target.x=se=e,te&&te.immediate(e)),!zot(t)&&A.dampY&&(A.dampY.immediate(t),A.y=T?A.target.percentSpeed=ce=t:A.target.y=ce=t,oe&&oe.immediate(t)),!zot(o)&&A.dampR&&(A.dampR.immediate(o),A.rotation=A.target.rotation=o),A},this.convert=function(e,t){zot(e)||(A.x=e),zot(t)||(A.y=t),ie()};var ge=!0;function pe(){"keydown"==i?(frame.off("keydown",N),frame.off("keyup",U),kt.Ticker.remove(J)):"gamebutton"==i?($.off("buttondown",G),$.off("buttonup",K),kt.Ticker.remove(J)):"gamestick"==i?$.off("data",ee):"swipe"==i?(te.enabled=!1,oe.enabled=!1,te.off("swipemove",ne)):"mousedown"==i||"mousemove"==i?C.off("stage"+i,O):"pressmove"==i&&(C.off("stagemousedown",O),C.off("stagemousemove",j),C.off("stagemouseup",D)),kt.Ticker.remove(he)}Object.defineProperty(A,"enabled",{get:function(){return ge},set:function(e){ge!=e&&(e?function(){"keydown"==i?(N=frame.on("keydown",N),U=frame.on("keyup",U),J=kt.Ticker.add(J,C)):"gamebutton"==i?(G=$.on("buttondown",G),K=$.on("buttonup",K),J=kt.Ticker.add(J,C)):"gamestick"==i?ee=$.on("data",ee):"swipe"==i?(te.enabled=!0,oe.enabled=!0,ne=te.on("swipemove",ne)):"mousedown"==i||"mousemove"==i?O=C.on("stage"+i,O):"pressmove"==i&&(O=C.on("stagemousedown",O),j=C.on("stagemousemove",j),D=C.on("stagemouseup",D));he=kt.Ticker.add(he,C)}():pe(),ge=Boolean(e))}}),this.dispose=function(){pe(),$&&$.dispose(),te&&te.dispose(),oe&&te.dispose()}},kt.extend(kt.MotionController,createjs.EventDispatcher,"enabled","cjsEventDispatcher"),kt.GamePad=function(){if(z_d("69.8"),this.type="GamePad",this.cjsEventDispatcher_constructor(),!navigator.getGamepads)return this.error=!0,void(zon&&zog("zim.GamePad() - no browswer support"));var a;window.addEventListener("gamepadconnected",e),this.currentIndex=0;var l=this;function e(e){var t,o,n;l.connected=!0,t="gamepadconnected",o=e,(n=new createjs.Event(t)).index=o.gamepad.index,n.id=o.gamepad.id,n.buttons=o.gamepad.buttons,n.axes=o.gamepad.axes,l.dispatchEvent(n);var r=navigator.getGamepads()[l.currentIndex];l.lastData=[];for(var i=0;i<r.buttons.length;i++)l.lastData[i]=r.buttons[i].pressed;!function e(){if(a=requestAnimationFrame(e),l.data=navigator.getGamepads()[l.currentIndex],l.data){for(var t=l.buttons=[],o=0;o<l.data.buttons.length;o++)if(t[o]=l.data.buttons[o].pressed,t[o]!=l.lastData[o]){if(l.lastData[o]=t[o],t[o])var n=new createjs.Event("buttondown");else n=new createjs.Event("buttonup");n.buttonCode=o,n.button=s[o],l.dispatchEvent(n)}(n=new createjs.Event("data")).axes=l.axes=l.data.axes,n.buttons=l.buttons,l.dispatchEvent(n)}}()}var t=setInterval(function(){navigator.getGamepads&&navigator.getGamepads()[0]&&(l.connected||e(),clearInterval(t))},500);var o=window.addEventListener("gamepaddisconnected",function(e){e.gamepad.index==l.currentIndex&&(cancelAnimationFrame(a),connected=!1,l.dispatchEvent("gamepaddisconnected"))});this.dispose=function(){window.removeEventListener("gamepadconnected",e),window.addEventListener("gamepaddisconnected",o),cancelAnimationFrame(a),clearInterval(t),l.connected=!1}};for(var s=["A","B","X","Y","LB","RB","LT","RT","BACK","START","LS","RS","DPAD_UP","DPAD_DOWN","DPAD_LEFT","DPAD_RIGHT"],l=0;l<s.length;l++)kt.GamePad[s[l]]=l;var p,f,e=["LSX","LSY","RSX","RSY"];for(l=0;l<e.length;l++)kt.GamePad[e[l]]=l;kt.extend(kt.GamePad,createjs.EventDispatcher,null,"cjsEventDispatcher"),kt.Portal=function(t,o){var e;if(e=zob(kt.Portal,arguments,"obj, lands",this))return e;if(z_d("69.96"),!zot(t)&&t.stage){this.type="Portal";var n=this,r=o&&o.numChildren&&0<o.numChildren;if(r){var i=o.getChildAt(o.numChildren-1),a=o.getChildAt(o.numChildren-2);o.setChildIndex(a,o.numChildren-1),a.setMask(t)}t.on(mobile()?"mousedown":"mouseover",function(){n._enabled&&(r&&l(),n.dispatchEvent("enter"))}),t.on(mobile()?"pressup":"mouseout",function(){n._enabled&&n.dispatchEvent("exit")}),Object.defineProperty(this,"portal",{get:function(){return t},set:function(e){!zot(e)&&e.stage||!zon?a.setMask(t):zog("zim.Portal() - please provide a Display Object to act as the portal")}}),Object.defineProperty(this,"currentLand",{get:function(){return i},set:function(e){if(o.contains(e))for(;e!=i;)l()}}),Object.defineProperty(this,"nextLand",{get:function(){return a},set:function(e){zon&&zog("zim.Portal() - nextLand is read only - remake Portal to change")}}),this._enabled=!0,Object.defineProperty(n,"enabled",{get:function(){return n._enabled},set:function(e){n._enabled=e}}),this.dispose=function(){}}function l(){o.setChildIndex(i,0),i=a,a=o.getChildAt(o.numChildren-2),o.setChildIndex(a,o.numChildren-1),i.setMask(null),a.setMask(t),t.stage.update()}},kt.extend(kt.Portal,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),zimContactListener=null,kt.Parallax=function(e,t,a,o,n,r,l){var i;if(i=zob(kt.Parallax,arguments,"layers, damp, auto, stage, startPaused, mouseMoveOutside, clamp",this))return i;if(z_d("68"),this.type="Parallax",zot(o))if(e&&e[0]&&e[0].obj&&e[0].obj.stage)o=e[0].obj.stage;else{if(!zimDefaultFrame)return;o=zimDefaultFrame.stage}a=!!zot(a),zot(n)&&(n=!1),zot(r)&&(r=!1);var s=o.getBounds().width,c=o.getBounds().height;o.mouseMoveOutside=r;var u=this;o.on("stagemousemove",function(e){u.mouseX=e.rawX,u.mouseY=e.rawY});var d=zot(t)?.1:t;this.addLayer=function(e){if(!(zot(e.obj)||zot(e.prop)||zot(e.propChange))){var t={obj:e.obj,prop:e.prop};t[t.prop]=e.propChange,zot(e.input)&&(e.input="mouseX"),t.input=e.input,t.split=zot(e.split)?!("mouseX"!=e.input||!a):e.split;var o=zot(e.inMin)?0:e.inMin,n=zot(e.inMax)?"mouseX"==e.input||"scrollX"==e.input?s:c:e.inMax,r=zot(e.factor)?1:e.factor,i=!zot(e.integer)&&e.integer;return t["p_"+t.prop]=new kt.ProportionDamp(o,n,0,t[t.prop],d,r,i,l),"scale"==t.prop?t["s_"+t.prop]=t.obj.scaleX:"frame"==t.prop?t["s_"+t.prop]=t.obj.currentFrame:t["s_"+t.prop]=t.obj[t.prop],zot(e.immediate)||t["p_"+t.prop].immediate(e.immediate),h.push(t),h.length-1}},this.removeLayer=function(e){if(!zot(e)){var t=h[e];t["p_"+t.prop].dispose(),h.splice(e,1)}},this.immediate=function(e){for(var t,o=0;o<h.length;o++)(t=h[o])["p_"+t.prop].immediate(e[o])},this.dispose=function(){return h=null,a&&kt.Ticker.remove(p),!0},e=zot(e)?[]:e;for(var h=[],g=0;g<e.length;g++)this.addLayer(e[g]);if(a){var p=kt.Ticker.add(function(e){u.step()},o);n&&kt.Ticker.remove(p)}this.step=function(e){for(var t,o,n=0;n<h.length;n++)t=h[n],zot(e)?"mouseX"==t.input?o=u.mouseX:"mouseY"==t.input?o=u.mouseY:"scrollX"==t.input?o=kt.scrollX():"scrollY"==t.input&&(o=kt.scrollY()):o=e,"scale"==t.prop?t.obj.scaleX=t.obj.scaleY=t["s_"+t.prop]+t["p_"+t.prop].convert(o):"frame"==t.prop?t.obj.gotoAndStop(t["s_"+t.prop]+t["p_"+t.prop].convert(o)):(t.obj[t.prop]=t["s_"+t.prop]+t["p_"+t.prop].convert(o),t.split&&(t.obj[t.prop]-=t[t.prop]/2))},u.paused=n,u.pause=function(e){zot(e)&&(e=!0),u.paused!=e&&((u.paused=e)?kt.Ticker.remove(p):p=kt.Ticker.add(p))},Object.defineProperty(u,"damp",{get:function(){return d},set:function(e){var t;d=e;for(var o=0;o<h.length;o++)(t=h[o])["p_"+t.prop].damp=d}})},kt.Scroller=function(e,t,o,n,r,i,a){var l;if(l=zob(kt.Scroller,arguments,"backing, speed, direction, horizontal, gapFix, stage, container",this))return l;z_d("69"),this.cjsEventDispatcher_constructor(),this.type="Scroller";var s=this.backing1=e;if(!zot(s)&&s.getBounds){var c=this.backing2=e.clone();zot(n)&&(n=!0),zot(r)&&(r=0);var u=this;this.speed=zot(t)?1:t;var d=this.baseSpeed=this.speed;this.direction=zot(o)?1:o;var h=n?s.scaleX:s.scaleY;if(s.getBounds())if(i||s.stage)if(s.parent)if(s.parent.addChildAt(c,s.parent.getChildIndex(s)),i=i||s.stage,zot(a)&&(a=i),a.getBounds()){var g,p,f=s.getBounds().width*h-r,m=s.getBounds().height*h-r;n?c.x=f:c.y=m;var z=!1,v=kt.Ticker.add(function(e){g||(g=a.getBounds().width,p=a.getBounds().height);if(0==u.speed||0==u.direction)return;n?(s.x-=u.speed*u.direction,s.x<c.x?c.x=s.x+f:c.x=s.x-f,0<u.direction*u.speed?c.x<0&&s.x<c.x?s.x=c.x+f:s.x<0&&c.x<s.x&&(c.x=s.x+f):c.x>g&&c.x>s.x?c.x=s.x-f:s.x>g&&s.x>c.x&&(s.x=c.x-f)):(s.y-=u.speed*u.direction,s.y<c.y?c.y=s.y+m:c.y=s.y-m,0<u.direction*u.speed?c.y<0&&s.y<c.y?s.y=c.y+m:s.y<0&&c.y<s.y&&(c.y=s.y+m):c.y>p&&c.y>s.y?c.y=s.y-m:s.y>p&&s.y>c.y&&(s.y=c.y-m))},i);this.paused=!1,this.pause=function(e,t){return zot(e)&&(e=!0),zot(t)&&(t=0),e?(d=u.speed,0<t?(z=!0,kt.animate({target:u,obj:{pausingSpeed:0},ticker:!1,time:t,call:function(){u.speed=0,u.paused=!0,z=!1,u.dispatchEvent("pause")}})):(z=!1,u.speed=0,u.paused=!0,setTimeout(function(){u.dispatchEvent("pause")},10))):(z=!1,0<t?kt.animate({target:u,obj:{pausingSpeed:d},ticker:!1,time:t,call:function(){u.speed=d,u.paused=!1,z=!1}}):(u.speed=d,u.paused=!1)),u},Object.defineProperty(u,"percentSpeed",{get:function(){return 0==u.baseSpeed?NaN:u.speed/u.baseSpeed*100},set:function(e){z||u.paused||(u.speed=u.baseSpeed*e/100)}}),Object.defineProperty(u,"pausingSpeed",{get:function(){return 0==u.baseSpeed?NaN:u.speed/u.baseSpeed*100},set:function(e){u.speed=u.baseSpeed*e/100}}),this.dispose=function(){return zon&&zog("bye from Scroller"),kt.Ticker.remove(v),!0}}else zog("zim display - Scroller(): please setBounds() on container or stage if no container");else zog("zim display - Scroller(): please add object to container or stage before adding to Scroller");else zog("zim display - Scroller(): please pass in stage parameter or add backing objects to stage to start");else zog("zim display - Scroller(): please setBounds() on backing objects")}},kt.extend(kt.Scroller,createjs.EventDispatcher,null,"cjsEventDispatcher"),kt.Dynamo=function(n,e,t,o,r,i,a,l,s){var c;if(c=zob(kt.Dynamo,arguments,"sprite, speed, label, startFrame, endFrame, update, reversible, flip, flipVertical",this))return c;z_d("69.2"),this.cjsEventDispatcher_constructor(),this.type="Dynamo";var u=this.frames=n.parseFrames(t,o,r,!0);if(0!=u.length){this.totalFrames=u.length;var d=0;zot(e)&&(e=30),zot(a)&&(a=!0);var h=this.baseSpeed=this.speed=e;zot(i)&&(i=!1),zot(l)&&0==a&&(l=!0);var g,p,f,m,z,v=this,y=Date.now(),b=!1;v.scaleX=n.scaleX,v.scaleY=n.scaleY,function e(){if(g=requestAnimationFrame(e),p=u[d].s,0!=v.speed&&0!=p&&(m=1e3/Math.abs(v.speed)*p,f=Date.now(),m<f-y)){y=f;var t=v.frame+(0<v.speed||!a?1:-1),o=!1;t>=u.length&&(o=!0,t=0),t<0&&(o=!0,t=u.length-1),v.frame=t,l&&(v.speed<0?n.scaleX=-v.scaleX:n.scaleX=v.scaleX),s&&(v.speed<0?n.scaleY=-v.scaleY:n.scaleY=v.scaleY),o&&v.dispatchEvent("loop"),v.dispatchEvent("change"),i&&n.stage&&n.stage.update(),zot(z)||z!=v.frame||(b=!1,v.speed=0,v.paused=!0,v.dispatchEvent("pause"))}}(),this.paused=!1,this.pause=function(e,t,o){return zot(e)&&(e=!0),zot(t)&&(t=0),e?(h=v.speed,zot(o)?0<t?(b=!0,kt.animate({target:v,obj:{pausingSpeed:0},ticker:!1,time:t,call:function(){b=!1,v.speed=0,v.paused=!0,v.dispatchEvent("pause")}})):(b=!1,v.speed=0,v.paused=!0,setTimeout(function(){v.dispatchEvent("pause")},10)):(b=!0,z=o)):(z=null,0<t?(b=!0,kt.animate({target:v,obj:{pausingSpeed:h},ticker:!1,time:t,call:function(){b=!1,v.speed=h,v.paused=!1}})):(b=!1,v.speed=h,v.paused=!1)),v},Object.defineProperty(v,"frame",{get:function(){return d},set:function(e){d=Math.round(e)%u.length;var t=u[d];zot(t)||(n.frame=t.f)}}),Object.defineProperty(v,"percentSpeed",{get:function(){return 0==v.baseSpeed?NaN:v.speed/v.baseSpeed*100},set:function(e){b||v.paused||(v.speed=v.baseSpeed*e/100)}}),Object.defineProperty(v,"pausingSpeed",{get:function(){return 0==v.baseSpeed?NaN:v.speed/v.baseSpeed*100},set:function(e){v.speed=v.baseSpeed*e/100}}),this.dispose=function(){cancelAnimationFrame(g)}}},kt.extend(kt.Dynamo,createjs.EventDispatcher,null,"cjsEventDispatcher"),kt.Accelerator=function(e){z_d("69.3"),this.cjsEventDispatcher_constructor();var l=this;this.type="Accelerator",this.paused=!1,this.items=[],this.paused=!1,this._percentSpeed=100,this.add=function(e){var t;t=Array.isArray(e)?e:[e];for(var o=0;o<t.length;o++)l.items.indexOf(t[o])<0&&l.items.push(t[o]);return l},e&&this.add(e),this.remove=function(e){var t,o;t=Array.isArray(e)?e:[e];for(var n=0;n<t.length;n++)0<=(o=l.items.indexOf(t[n]))&&l.items.splice(o,1);return l},this.pause=function(o,e,t){zot(o)&&(o=!0);var n=[];if(o){zot(t)||(e=null);for(var r=!1,i=0;i<l.items.length;i++)(zot(e)||!zot(t)||l.items[i].totalFrames)&&(!l.items[i].totalFrames||zot(e)&&zot(t))||(l.items[i].pause(!0,e,t),r=!0,n[i]=1,l.items[i].on("pause",function(){l.paused||(a(!0),l.paused=!0,l.dispatchEvent("pause"))},null,!0));r||(a(),l.paused=!0,setTimeout(function(){l.dispatchEvent("pause")},10))}else l.paused=!1,a();function a(e){for(var t=0;t<l.items.length;t++)1!=n[t]&&l.items[t].pause(o)}},Object.defineProperty(l,"percentSpeed",{get:function(){return l._percentSpeed},set:function(e){l._percentSpeed=e;for(var t=0;t<l.items.length;t++)l.items[t].percentSpeed=e}}),this.dispose=function(){for(var e=0;e<l.items.length;e++)l.items[e].dispose();return!0}},kt.extend(kt.Accelerator,createjs.EventDispatcher,null,"cjsEventDispatcher"),kt.Emitter=function(f,m,z,t,e,o,n,r,i,a,l,s,v,y,c,u,d,h,g,p,b,w,x,C,k,T,A,P,B,I,S){var E;if(E=zob(kt.Emitter,arguments,"obj, width, height, interval, num, life, fade, shrink, decayTime, decayStart, trace, traceFadeTime, traceShiftX, traceShiftY, angle, force, gravity, wind, layers, animation, random, horizontal, vertical, sink, sinkForce, cache, events, startPaused, pool, poolMin, particles",this))return E;z_d("69.9"),this.type="Emitter",zot(f)&&(f=[new kt.Circle(20,"#e472c4"),new kt.Circle(20,"#acd241"),new kt.Circle(20,"#50c4b7")]),zot(m)&&(m=300),zot(z)&&(z=300),zot(t)&&(t=20),"number"==typeof t&&(t=Math.max(10,t)),zot(e)&&(e=1),zot(l)&&(l=!1),zot(s)&&(s=i),zot(v)&&(v=0),zot(y)&&(y=0),zot(o)&&(o=1e3),zot(n)&&(n=!0),zot(r)&&(r=!l),zot(i)&&(i=1e3),zot(c)&&(c={min:0,max:360}),zot(u)&&(u=5),zot(d)&&(d=9.8),zot(h)&&(h=0),zot(g)&&(g="top"),zot(m)&&(m=100),zot(z)&&(z=100),zot(w)&&(w=!1),zot(x)&&(x=!1),!zot(C)&&zot(k)&&(k=10),zot(A)&&(A=!1),zot(P)&&(P=!1),zot(B)&&(B=!0),zot(I)&&(I=0),zot(S)&&(S=new kt.Container),this.zimContainer_constructor(m,z,null,null,!1),this.type="Emitter";var M=this;M.obj=f,M.particles=S,M.interval=t,M.num=e,M.life=o,M.fade=n,M.shrink=r,M.decayTime=i,M.decayStart=a,M.trace=l,M.traceFadeTime=s,M.traceShiftX=v,M.traceShiftY=y,M.angle=c,M.emitterForce=u,M.gravity=d,M.wind=h,M.layers=g,M.animation=p,M.random=b,M.horizontal=w,M.vertical=x,M.sink=C,M.sinkForce=k,M.events=A,M.startEmitterPaused=P,M.pool=B,M.poolMin=I,M.particlesEmitted=0;var O,j,D=[],L=0,Y=0;function X(e){if(M.events&&R("fizzed",e),(e.trace?e.getChildAt(0).endSpurt:e.endSpurt)&&(R("spurtfizzed",e),M.spurting=!1),M.pool&&"end"!=e.pooled)return e.pooled||(e.pooled=!0,D.push(e)),void(e.visible=!1);M.removeChild(e),M.trace&&e.uncache(),e=null}function R(e,t){var o=new createjs.Event(e);o.particle=t.trace?t.getChildAt(0):t,M.dispatchEvent(o)}function _(e){M.pauseEmitter(),M.spurtCount=M.spurtNum=null,R("spurted",e),e.endSpurt=!0}kt.added(M,function(e){j=e,zot(T)&&(T=!j.isWebGL&&kt.mobile());T&&(j.snapToPixelEnabled=!0);if(j){var t=M.parent.getChildIndex(M);M.parent.addChildAt(S,t),w||x||M.centerReg(null,null,!1),M.zimInterval=kt.interval(M.interval,function(){var g,p;M.startEmitterPaused?M.pauseEmitter():(f=Array.isArray(M.obj)?M.obj:[M.obj]).length<=0||(g=Array.isArray(M.interval)?(M.interval.sort(e),M.interval[0]):M.interval.constructor=={}.constructor?M.interval.min:M.interval,p=Array.isArray(M.num)?(M.num.sort(e),M.num[M.num.length-1]):M.num.constructor=={}.constructor?M.num.max:M.num,kt.loop(kt.Pick.choose(M.num),function(){if(0<M.decayTime){var e={};M.shrink&&(e.scale=0),M.fade&&(e.alpha=0)}if(M.pool&&0<D.length&&Y>=Math.max(M.poolMin,(M.life/g+5)*p)){var o=D[L++%D.length];o.visible=!0;var n=o.trace?o.getChildAt(0):o;if(n.emitShape){var t=n.template;n.graphics.c().s(t.s?kt.Pick.choose(t.s):null).ss(t.ss?kt.Pick.choose(t.ss):null).sd(t.sd?kt.Pick.choose(t.sd):null,t.offset?kt.Pick.choose(t.offset):null)}o.trace&&o.updateCache(),"top"==M.layers?n.emitShape?o.addTo(S,null,!1):o.centerReg(S):n.emitShape?o.addTo(S,"bottom"==M.layers?0:kt.rand(S.numChildren),!1):o.centerReg(S,"bottom"==M.layers?0:kt.rand(S.numChildren)),o.alpha=1,o.scaleX=1,o.scaleY=1,n.alpha=n.originalAlpha,n.scaleX=n.originalScaleX,n.scaleY=n.originalScaleY,n.endSpurt=!1}else{Y++,M.trace&&((o=new kt.Container(m,z,null,null,!1)).trace=!0);var r=kt.Pick.choose(kt.shuffle(f)[0]);if("shape"==r.type){var t=r,n=new kt.Shape(1,1,null,null,null,!1);n.emitShape=!0,n.template=t,n.graphics.s(t.s?kt.Pick.choose(t.s):null).ss(t.ss?kt.Pick.choose(t.ss):null).sd(t.sd?kt.Pick.choose(t.sd):null,t.offset?kt.Pick.choose(t.offset):null),M.trace?n.addTo(o,null,!1):"top"==M.layers?n.addTo(S,null,!1):n.addTo(S,"bottom"==M.layers?0:kt.rand(S.numChildren),null,!1)}else{var n=r.clone();n.centerReg||zimify(n),M.trace?n.centerReg(o).pos({x:-1e3,y:-1e3,reg:!0}):"top"==M.layers?n.centerReg(S):n.centerReg(S,"bottom"==M.layers?0:kt.rand(S.numChildren))}M.trace&&("top"==M.layers?o.addTo(S,null,!1):o.addTo(S,"bottom"==M.layers?0:kt.rand(S.numChildren),!1),o.cache(v,y,m,z)),M.trace||(o=n),(o.particle=n).originalAlpha=n.alpha,n.originalScaleX=n.scaleX,n.originalScaleY=n.scaleY}M.currentParticle=n,M.particlesEmitted++,o.particleNormal=!0,o.particleDecaying=!1,o.particleFizzing=!1;var i=kt.Pick.choose(M.angle),a=kt.Pick.choose(M.emitterForce),l=a*Math.cos(i*Math.PI/180),s=a*Math.sin(i*Math.PI/180);n.info={position:{x:M.x,y:M.y},velocity:{x:l,y:s}},M.horizontal&&(n.info.position={x:kt.rand(0,m),y:M.vertical?z/2:0}),M.vertical&&(n.info.position={x:M.horizontal?m/2:0,y:kt.rand(0,z)}),n.emitShape?n.graphics.mt(n.info.position.x,n.info.position.y):(n.x=n.info.position.x,n.y=n.info.position.y),M.random&&kt.loop(M.random,function(e,t){val=kt.Pick.choose(t),"scale"==e?n.sca(val):("x"==e?n.info.position.x=M.horizontal||M.vertical?val:val+m/2:"y"==e&&(n.info.position.y=M.horizontal||M.vertical?val:val+z/2),"x"!=e&&"y"!=e||!n.emitShape||n.graphics.mt(n.info.position.x,n.info.position.y),n[e]=val,n.emitShape&&(n.x=0,n.y=0))}),T&&!n.emitShape&&n.cache(n.getBounds().x-10,n.getBounds().y-10,n.getBounds().width+20,n.getBounds().height+20);var c,u=!n.emitShape&&M.shrink;if(0<M.decayTime&&(M.fade||u||M.trace&&0<M.traceFadeTime)){if(M.trace&&0<M.traceFadeTime&&o.animate({obj:{alpha:0},time:M.traceFadeTime,wait:M.life-M.traceFadeTime,waitedCall:function(e){e.particleNormal=!1,e.particleFizzing=!0},call:X,override:!1,id:"decay"}),M.fade||u){var d={};M.fade&&(d.alpha=0),u&&(d.scaleX=0,d.scaleY=0),n.animate({obj:d,time:M.decayTime,wait:zot(M.decayStart)?M.life-M.decayTime:M.decayStart,waitedCall:function(e){e.parent!=M&&(e=e.parent),e.particleNormal=!1,e.particleDecaying=!0},call:function(e){var t;M.events&&R("decayed",e),e.endSpurt&&R("spurtdecayed",e),M.trace&&0<M.traceFadeTime||(zot(M.decayStart)||M.decayStart+M.decayTime>M.life?e.parent&&X(e.parent.trace?e.parent:e):(t=o,kt.timeout(M.life-(M.decayStart+M.decayTime),function(){X(t)})))},override:!1,id:"decay"})}}else 0<M.life&&((c=o).timeOut=kt.timeout(M.life,function(){X(c)}));if(M.events&&R("emitted",o),function(e){if(zot(M.spurtCount)&&zot(M.spurtNum))return;M.spurtCount++,M.spurtCount>=M.spurtNum&&_(e)}(n),M.animation){var h=kt.Pick.choose(M.animation);zot(h.override)&&(h.override=!1),n.animate(kt.copy(h))}}));function e(e,t){return e-t}},null,!0);O=M.emitterTicker=kt.Ticker.add(function(){kt.loop(S,function(e){if(e.trace){var t=e;e=e.getChildAt(0)}var o=e.info,n=0,r=0;if(!zot(M.sink)){var i=M.particles.localToGlobal(o.position.x,o.position.y);if(M.sink.parent&&M.sink.parent.localToGlobal)var a=M.sink.parent.localToGlobal(M.sink.x,M.sink.y);else a=new createjs.Point(kt.Pick.choose(M.sink.x),kt.Pick.choose(M.sink.y));var l=kt.angle(i.x,i.y,a.x,a.y),n=M.sinkForce*Math.cos(l*Math.PI/180),r=M.sinkForce*Math.sin(l*Math.PI/180)}var s=M.wind+n,c=M.gravity+r;o.velocity.x+=s*frameRate,o.velocity.y+=c*frameRate,o.position.x+=o.velocity.x*frameRate*100,o.position.y+=o.velocity.y*frameRate*100,e.emitShape?e.graphics.lt(o.position.x,o.position.y):(e.x=o.position.x,e.y=o.position.y),M.trace&&t&&t.updateCache(e.emitShape?null:"source-over")})},j),frameRate=1/kt.Ticker.framerate}}),Object.defineProperty(M,"interval",{get:function(){return t},set:function(e){t=e,M.zimInterval&&(M.zimInterval.time=t)}}),this.spurting=!1,this.spurt=function(e,t,o){var n;if(n=zob(M.spurt,arguments,"num, time, restart"))return n;zot(t)||(kt.timeout(kt.Pick.choose(t),function(){_(M.currentParticle)}),M.spurting=!0),zot(e)||(M.spurtNum=kt.Pick.choose(e),M.spurtCount=0,M.spurting=!0),M.pauseEmitter(!1,o,null,!0)},this.clearPool=function(){kt.loop(M,function(e){e.pooled="end",e.visible||M.removeChild(e)},!0),L=Y=0,D=[]},M.startEmitterPaused||(this.emitterPaused=!1),this.pauseEmitter=function(e,t,o,n){if(M.startEmitterPaused=null,zot(e)&&(e=!0),zot(t)&&(t=!1),zot(o)&&(o=!1),e){if(M.emitterPaused)return M;o&&(O&&kt.Ticker.remove(O),kt.loop(M,function(e){e.pauseAnimate(),e.trace&&e.getChildAt(0).pauseAnimate(),e.timeOut&&e.timeOut.pause()})),M.zimInterval.pause(),M.emitterPaused=!0}else{if(!M.emitterPaused)return M;t&&(kt.loop(M,function(e){e.stopAnimate(),e.timeOut&&e.timeOut.clear(),e.trace&&e.getChildAt(0).pauseAnimate()}),M.removeAllChildren()),j&&O&&!kt.Ticker.has(j,O)&&(kt.Ticker.add(O,j),kt.loop(M,function(e){e.pauseAnimate(!1),e.timeOut&&e.timeOut.pause(!1),e.trace&&e.getChildAt(0).pauseAnimate(!1)})),M.zimInterval.pause(!1,n),M.emitterPaused=!1}return M},this.resize=function(e,t){zot(e)||(m=e),zot(t)||(z=t),M.setBounds(0,0,m,z),w||x||M.centerReg(),M.clearPool()},this.clone=function(){var e;return e=Array.isArray(M.obj)||M.obj.constructor=={}.constructor?kt.copy(M.obj):M.obj.clone?M.obj.clone():M.obj,M.cloneProps(new kt.Emitter(e,m,z,M.interval,M.num,M.life,M.fade,M.shrink,M.decayTime,M.decayStart,M.trace,M.traceFadeTime,M.traceShiftX,M.traceShiftY,M.angle,M.emitterForce,M.gravity,M.wind,M.layers,M.animation,kt.copy(M.random),M.horizontal,M.vertical,M.sink,M.sinkForce,T,M.events,P,M.pool,M.poolMin))},this.dispose=function(){return O&&kt.Ticker.remove(O),kt.loop(M,function(e){e.stopAnimate()}),M.zimInterval&&M.zimInterval.clear(),!0}},kt.extend(kt.Emitter,kt.Container,"clone","zimContainer",!1),kt.Pen=function(f,m,z,t,v,y,b,w,x,o,r,e,i,a,n,l,s,c,u,d,h,g){var p;if(p=zob(kt.Pen,arguments,"size, color, penType, damp, spread, borderColor, borderWidth, end, paper, nib, cache, ctrlKey, cropScale, undo, undoKeys, draggable, onTop, deleteable, doubleClickDelete, immediateStop, lineAlpha, lineBlendMode",this))return p;z_d("69.93"),this.zimContainer_constructor(),this.type="Pen",zot(z)&&(z="line");var C={size:2,color:"#333",spread:{min:5,max:20},borderColor:"#111",borderWidth:0},k={line:{size:2},kitetail:{size:{min:5,max:20},color:kt.series(kt.pink,kt.blue,kt.green),borderColor:"rgba(0,0,0,.5)",borderWidth:1},grass:{color:"#acd241",size:3,spread:{min:10,max:30}},hair:{color:["#e472c4","#50c4b7"],size:3,spread:{min:20,max:50}},city:{size:{min:30,max:70},spread:{min:50,max:200},color:["#333","#111","#555"]},barbwire:{},splatter:{size:{min:5,max:20},color:"rgba(0,0,0,.5)"}};zot(k[z])&&(z="line"),zot(f)&&(f=zot(k[z].size)?C.size:k[z].size),zot(m)&&(m=zot(k[z].color)?C.color:k[z].color),zot(t)&&(t=.1),!1===t&&(t=1),zot(z)&&(z="line"),zot(v)&&(v=zot(k[z].spread)?C.spread:k[z].spread),zot(y)&&(y=zot(k[z].borderColor)?C.borderColor:k[z].borderColor),zot(b)&&(b=zot(k[z].borderWidth)?C.borderWidth:k[z].borderWidth),zot(w)&&(w="butt"),zot(i)&&(i=1),zot(r)&&(r=!0),zot(a)&&(a=0),zot(n)&&(n=!0),zot(l)&&(l=!0),zot(c)&&(c=!0),zot(u)&&(u=!0),zot(s)&&(s=!0),zot(d)&&(d="both"),zot(h)&&(h=1),zot(g)&&(g="normal");var T=this;this.dampX=new kt.Damp(null,t),this.dampY=new kt.Damp(null,t);var A=!0;this.drawing=!1,this.immediateStop=d,this.undoLevels=a,this.undoKeys=n,this.draggable=l,this.lineAlpha=h,this.lineBlendMode=g;var P,B,I,S,E=new kt.Shape,M=zimDefaultFrame?zimDefaultFrame.stage.width:1024,O=zimDefaultFrame?zimDefaultFrame.stage.height:768;T.paperNum=0,T.sizeScale=1,T.spreadScale=1,T.sizeFactor=1,T.spreadFactor=1,T.stop=function(){},zot(x)?x=new kt.Container:E.addTo(x),this.added(function(){if(T.paper=x,!zot(o))if(T.zimDown)T.nib=o.addTo(T);else{function t(e){T.nib.x=e.stageX,T.nib.y=e.stageY}T.nib=o.addTo(T.parent,T.parent.getChildIndex(T)),T.nib.x=T.x,T.nib.y=T.y,T.nib.mouseEnabled=!1,T.stage.on("stagemousedown",function(e){T.nibEvent=T.stage.on("stagemousemove",t)}),T.stage.on("stagemouseup",function(e){T.stage.off("stagemousemove",T.nibEvent)})}T.zimDragCheck=!1,T.stop=function(){T.stopCheck(!0)},T.infinite=!1,T.stopCheck=function(e){if(e)T.drawing=!1,T.infinite=!1;else{if(T.infinite)return;if(T.zimDragCheck)return;if(!T.immediateStop&&T.drawing)return}T.immediate(T.x,T.y),setTimeout(function(){if(!T.drawing){if(r){E.cache(-(M*i-M)/2,-(O*i-O)/2,M*i,O*i);var e=x.bitmap=new kt.Bitmap(E.cacheCanvas).reg((M*i-M)/2,(O*i-O)/2).addTo(x);E.graphics.clear(),E.uncache(),E.top()}else e=E;if(0<T.undoLevels){var t={paper:x,line:e};a.push(t),a.length>T.undoLevels&&a.unshift(),T.dispatchEvent("recordUndo")}r||(E=(new kt.Shape).clone().addTo(x)),T.lastSegment=e,(T.lastSelected=e).alpha=T.lineAlpha,e.blendMode=T.lineBlendMode,e.paper=x,T.dispatchEvent("stop"),T.dispatchEvent("change")}},T.immediateStop||e?0:50)};var p=0;T.dampX.immediate(T.x),T.dampY.immediate(T.y),T.lastX=T.x,T.lastY=T.y,T.ticker=kt.Ticker.add(function(){var e=T.dampX.convert(A?T.x:T.finishX),t=T.dampY.convert(A?T.y:T.finishY),o=T.parent.localToLocal(e,t,E),n=kt.Pick.choose(f)*T.sizeScale*T.sizeFactor,r=kt.Pick.choose(v)*T.spreadScale*T.spreadFactor;if(Math.abs(T.lastX-e)+Math.abs(T.lastY-t)<1)return T.drawing&&(T.drawing=!1,T.zimDown?(T.x=T.lastX=A?T.x:T.finishX,T.y=T.lastY=A?T.y:T.finishY,T.dampX.immediate(T.x),T.dampY.immediate(T.y)):(T.x=T.finishX=T.lastX=e,T.y=T.finishY=T.lastY=t),T.stopCheck()),T.lastX=e,void(T.lastY=t);if(T.drawing||(j=[],x.getChildIndex(E)!=x.numChildren-1&&E.top()),T.drawing=!0,T.dispatchEvent("drawing"),"splatter"==z)for(var i=0;i<=3;i++){var a=kt.rand(360)*Math.PI/180,l=r,s={x:e+l*Math.cos(a),y:t+l*Math.sin(a)},c=T.parent.localToLocal(s.x,s.y,E);E.graphics.mt(c.x,c.y).f(kt.Pick.choose(m)).dc(c.x,c.y,n/2)}else if("grass"==z||"hair"==z||"city"==z){if("grass"==z||"hair"==z){var u=T.lastX+(e-T.lastX)/2,d=T.lastY+(t-T.lastY)/2,h=T.parent.localToLocal(u,d,E);E.graphics.s(kt.Pick.choose(m)).ss(n,w).mt(h.x,h.y).lt(h.x+rand(-r/4,r/4),"hair"==z?h.y+r:h.y-r)}("grass"==z||"hair"==z||"city"==z&&p%3==0)&&E.graphics.s(kt.Pick.choose(m)).ss(n,w).mt(o.x,o.y).lt(o.x+("city"==z?0:rand(-r/4,r/4)),"hair"==z?h.y+r:o.y-r),p++}else{if("kitetail"==z&&E.graphics.s(kt.Pick.choose(m)).ss(n,w),"barbwire"==z){E.graphics.s(kt.Pick.choose(m)).ss(n,w);u=T.lastX+(e-T.lastX)/2+rand(-r,r),d=T.lastY+(t-T.lastY)/2+rand(-r,r)}else u=T.lastX+(e-T.lastX)/2,d=T.lastY+(t-T.lastY)/2;h=T.parent.localToLocal(u,d,E);E.graphics.qt(h.x,h.y,o.x,o.y)}var g=T.parent.localToLocal(T.lastX,T.lastY,E);if(0<b&&"line"!=z){u=T.lastX+(e-T.lastX)/2,d=T.lastY+(t-T.lastY)/2,h=T.parent.localToLocal(u,d,E);E.graphics.s(kt.Pick.choose(y)).ss(kt.Pick.choose(b)).mt(g.x,g.y).qt(h.x,h.y,o.x,o.y),"splatter"==z&&E.graphics.es()}"splatter"==z?E.graphics.f(kt.Pick.choose(m)):"kitetail"==z||E.graphics.s(kt.Pick.choose(m)).ss(n,w),"grass"!=z&&"hair"!=z&&"city"!=z&&"splatter"!=z&&E.graphics.mt(g.x,g.y).qt(h.x,h.y,o.x,o.y),T.lastX=e,T.lastY=t}),T.stage.on("stagemouseup",function(){!1})}),T.mouseChildren=!1;a=[];var j=[];this.saveState=function(e,t,o){var n="Container"==e.type?"paper":"line",r={paper:T.paper};r[n]=e,r[n+"Transform"]={x:e.x,y:e.y,r:e.rotation,a:e.alpha,rX:e.regX,rY:e.regY,sX:e.scaleX,sY:e.scaleY,skX:e.skewX,skY:e.skewY,v:e.visible},zot(t)||zot(o)||t==o||(r.startLayer=t,r.endLayer=o),a.push(r),T.dispatchEvent("recordUndo"),a.length>T.undoLevels&&a.unshift()};var D,L,Y={x:0,y:0,r:0,a:1,rX:0,rY:0,sX:1,sY:1,skX:0,skY:0,v:!0};function X(e,t){for(var o,n=a.length-1;0<=n;n--)if(a[n][e]==t&&a[n][e+"Transform"]){o=a[n][e+"Transform"];break}o||(o=kt.copy(Y)),t.x=o.x,t.y=o.y,t.alpha=o.a,t.rotation=o.r,t.regX=o.rX,t.regY=o.rY,t.scaleX=o.sX,t.scaleY=o.sY,t.skewX=o.skX,t.skewY=o.skY,t.visible=o.v,"line"==e&&r&&(t.regX=(M*i-M)/2,t.regY=(O*i-O)/2)}this.undo=function(){var e=a.pop();if(e){if(j.push(e),e.clear){for(var t=0;t<e.clear.length;t++)e.paper.addChild(e.clear[t]);e.paper.addChild(E)}else e.line&&e.lineTransform?(zot(e.startLayer)||(E.top(),e.paper.setChildIndex(e.line,I)),X("line",e.line)):e.line?e.line.removeFrom():e.paperTransform&&X("paper",e.paper);T.lastPaper=T.paper,e.paper!=T.paper&&(T.paper=e.paper,T.dispatchEvent("paperChange")),T.dispatchEvent("change"),!OPTIMIZE&&T.stage&&T.stage.update()}},this.redo=function(){var e=j.pop();if(e){if(a.push(e),e.clear)e.paper.removeAllChildren(),e.paper.addChild(E);else if(e.line&&e.lineTransform){zot(e.endLayer)||(E.top(),e.paper.setChildIndex(e.line,S));var t=e.lineTransform,o=e.line}else if(e.line)e.line.addTo(e.paper);else if(e.paperTransform)t=e.paperTransform,o=e.paper;o&&(o.x=t.x,o.y=t.y,o.alpha=t.a,o.rotation=t.r,o.regX=t.rX,o.regY=t.rY,o.scaleX=t.sX,o.scaleY=t.sY,o.skewX=t.skX,o.skewY=t.skY,o.visible=t.v),T.lastPaper=T.paper,e.paper!=T.paper&&(T.paper=e.paper,T.dispatchEvent("paperChange")),T.dispatchEvent("change"),!OPTIMIZE&&T.stage&&T.stage.update()}},T.ctrlKey=!1,T.shiftKey=!1,T.ctrlKeyCheck=!1,T.zimkeydownEvent=window.addEventListener("keydown",function(e){T.ctrlKey=e.ctrlKey,T.shiftKey=e.shiftKey,17==e.keyCode&&l&&!T.ctrlKeyCheck&&(T.ctrlKeyCheck=!0,x.noDrag(),x.drag({onTop:s,all:!0})),T.undoLevels<=0||T.undoKeys&&(e.ctrlKey&&(e.shiftKey&&90==e.keyCode||89==e.keyCode)?T.redo():e.ctrlKey&&90==e.keyCode&&T.undo())}),T.zimkeyupEvent=window.addEventListener("keyup",function(e){17==e.keyCode&&l&&T.ctrlKeyCheck&&(T.ctrlKeyCheck=!1,x.noDrag(),x.drag({onTop:s})),e.ctrlKey||(T.ctrlKey=!1),e.shiftKey||(T.shiftKey=!1)}),Object.defineProperty(this,"paper",{get:function(){return x},set:function(e){"Container"==e.type&&(x=e,E.addTo(x,0,!1),x.shape=E,T.dampX.immediate(T.x),T.dampY.immediate(T.y),T.lastX=T.finishX=T.x,T.lastY=T.finishY=T.y,"barbwire"==z&&E.graphics.s(kt.Pick.choose(m)).ss(kt.Pick.choose(f)*T.sizeScale*T.sizeFactor,w),E.graphics.mt(T.x,T.y),x.parent||x.addTo(T.parent,T.parent.getChildIndex(T)),zot(x.paperNum)&&(x.paperNum=++T.paperNum,c&&x.on("mousedown",function(e){T.lastSelected=e.target,T.nibEvent&&T.stage.off("stagemousemove",T.nibEvent);var t=e.target.paper;t&&(t!=T.paper&&(T.paper=t,T.dispatchEvent("paperChange")),T.shiftKey&&(T.ctrlKey?T.clear():(e.target.visible=!1,0<T.undoLevels&&T.saveState(e.target),T.dispatchEvent("change"))))}),u&&x.on("dblclick",function(e){e.target.visible=!1,0<T.undoLevels&&T.saveState(e.target)}),l&&(x.on("mousedown",function(e){!0,T.shiftKey&&c||(P=e.stageX,B=e.stageY,E.top(),I=x.getChildIndex(e.target))}),x.drag({onTop:s}),x.on("pressup",function(e){c&&T.shiftKey||0!=e.target.visible&&(T.undoLevels<=0||(Math.abs(e.stageX-P)<1&&Math.abs(e.stageY-B)<1?s&&(E.top(),S=x.getChildIndex(e.target),I!=S&&T.saveState(e.target,I,S)):(T.ctrlKey?(T.saveState(x),T.dispatchEvent("paperChange")):(E.top(),S=x.getChildIndex(e.target),T.saveState(e.target,I,S)),T.dispatchEvent("change"),E.top())))}))))}}),Object.defineProperty(this,"write",{get:function(){return A},set:function(e){A&&!1===e&&(T.finishX=T.x,T.finishY=T.y),!A&&e&&(E.graphics.es(),E.graphics.ef(),T.dampX.immediate(T.x),T.dampY.immediate(T.y),T.lastX=T.x,T.lastY=T.y),A=e}}),Object.defineProperty(this,"size",{get:function(){return f},set:function(e){E.graphics.es(),E.graphics.ef(),f=e,"splatter"!=z&&E.graphics.ss(kt.Pick.choose(f)*T.sizeScale*T.sizeFactor,w)}}),Object.defineProperty(this,"color",{get:function(){return m},set:function(e){m=e,E.graphics.es(),E.graphics.ef(),"splatter"!=z&&E.graphics.s(kt.Pick.choose(m))}}),Object.defineProperty(this,"penType",{get:function(){return z},set:function(e){z=e,E.graphics.ef().es(),"splatter"!=z?E.graphics.s(kt.Pick.choose(m)):E.graphics.s(kt.Pick.choose(m)).ss(kt.Pick.choose(f)*T.sizeScale*T.sizeFactor,w)}}),Object.defineProperty(this,"damp",{get:function(){return t},set:function(e){t=e,T.dampX.damp=t,T.dampY.damp=t}}),Object.defineProperty(this,"spread",{get:function(){return v},set:function(e){v=e}}),this.setColorRange=function(e,t){return L=zot(t)?(D=T.color,e):(D=zot(e)?T.color:e,t),T};var R=0;Object.defineProperty(T,"colorRange",{get:function(){return R},set:function(e){R=e,zot(D)||zot(L)||(T.color=kt.colorRange(D,L,e))}}),Object.defineProperty(this,"borderColor",{get:function(){return y},set:function(e){y=e}}),Object.defineProperty(this,"borderWidth",{get:function(){return b},set:function(e){b=e}}),zimDefaultFrame&&(zimDefaultFrame.on("keydown",function(){frame.ctrlKey&&T.write&&(T.lastWrite=T.write,T.write=!1)}),zimDefaultFrame.on("keyup",function(){frame.ctrlKey||0!=T.write||(T.write=T.lastWrite)})),T.setPen=function(e){T.dampX.immediate(T.x),T.dampY.immediate(T.y),T.lastX=T.finishX=T.x,T.lastY=T.finishY=T.y,zot(e)&&(e=z),zot(k[e])&&(e="line"),T.penType=z=e;var t=kt.merge(C,k[e]);for(var o in t)T[o]!=t[o]&&(T[o]=t[o]);return T},T.immediate=function(e,t){return zot(e)||(T.x=e,T.dampX.immediate(T.x),T.lastX=T.finishX=T.x),zot(t)||(T.y=t,T.dampY.immediate(T.y),T.lastY=T.finishY=T.y),T},T.clear=function(){if(!(x.numChildren<=1)){for(var e=[],t=0;t<x.numChildren-1;t++)e.push(x.getChildAt(t));return a.push({paper:x,clear:e}),a.length>T.undoLevels&&a.unshift(),T.dispatchEvent("recordUndo"),x.removeAllChildren(),E.graphics.clear(),x.addChild(E),T.dispatchEvent("change"),T.stage&&T.stage.update(),T}},this.delete=function(e){x.getChildAt(e).visible=!1,0<T.undoLevels&&T.saveState(x.getChildAt(e))},this.deleteSegment=function(e){e.visible=!1,0<T.undoLevels&&T.saveState(e)},T.dispose=function(e){return zot(e)?(window.removeEventListener("keydown",T.zimkeydownEvent),window.removeEventListener("keyup",T.zimkeyupEvent),Ticker.remove(T.Ticker),T.removeAllEventListeners(),e.removeAllEventListeners(),E.graphics.clear(),r?T.bitmap.removeFrom():E.removeFrom(),o.removeFrom(),!0):(e.removeAllEventListeners(),e.shape.graphics.clear(),void(r?e.bitmap.removeFrom():e.shape.removeFrom()))}},kt.extend(kt.Pen,kt.Container,"clone","zimContainer",!1),kt.SoundWave=function(e,i,a,t,o,n,l,r,s,c){var u;if(u=zob(kt.SoundWave,arguments,"num, input, include, smoothing, min, max, operation, baseline, magnify, reduce",this))return u;z_d("69.95"),this.type="SoundWave",zot(e)&&(e=120),zot(i)&&(i="mic"),zot(a)&&(a=.1171875),zot(t)&&(t=.85),zot(o)&&(o="mic"==i?-80:-100),zot(n)&&(n="mic"==i?-40:-10),zot(l)&&(l=function(e,t){return e*(.5+1*t/Math.pow(kt.SoundWave.bufferLength,.95))}),zot(r)&&(r="mic"==i?0:30),zot(s)&&(s="mic"==i?1:10),zot(c)&&(c=0),kt.SoundWave.bufferLength=1024,_num=e;var d=this;d.baseline=r,d.magnify=s,d.reduce=c;var h=new(window.AudioContext||window.webkitAudioContext),g=d.analyser=h.createAnalyser();if(g.minDecibels=o,g.maxDecibels=n,g.smoothingTimeConstant=t,Object.defineProperty(this,"smoothing",{get:function(){return g.smoothingTimeConstant},set:function(e){g.smoothingTimeConstant=e}}),Object.defineProperty(this,"num",{get:function(){return _num},set:function(e){_num=e,(m=Math.floor(a*kt.SoundWave.bufferLength/_num))<1&&zog("ZIM SoundWave: num is too big")}}),"mic"==i)return navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia,void(navigator.getUserMedia?navigator.getUserMedia({audio:!0},function(e){z(d.source=h.createMediaStreamSource(e))},function(e){zog("ZIM SoundWave: Error occured: "+e)}):zog("ZIM SoundWave: Sorry, mic not supported"));if(i.type&&"sound"==i.type)zog("ZIM SoundWave: pass in the result of a zim.asset('somesound').play() for the input");else{if(i.playbackResource)var p=i.playbackResource,f=h.createMediaElementSource(p);else p=i,f=h.createMediaElementSource(p);var m;z(f)}function z(e){if(e.connect(g),"mic"!=i&&g.connect(h.destination),g.fftSize=2*kt.SoundWave.bufferLength,(m=Math.floor(a*kt.SoundWave.bufferLength/_num))<1)zog("ZIM SoundWave: include param is too small or num param is too big");else{var t=g.frequencyBinCount,r=new Uint8Array(t);d.calculate=function(){g.getByteFrequencyData(r);var e=r.map(l);if(1==m)return e;for(var t=[],o=0,n=0;n<=a*kt.SoundWave.bufferLength;n++)o+=e[n],0!=n&&n%m==0&&(t.push(Math.max(0,(o/m-d.baseline)*d.magnify-d.reduce)),o=0);return"mic"!=i&&(t[0]*=.75,t[1]*=.85,t[2]*=.9,t[t.length-2]*=.8,t[t.length-1]*=.75),t[t.length-1]*=1.3,t[t.length-2]*=1.2,t[t.length-3]*=1.1,t},setTimeout(function(){d.dispatchEvent("ready")},50)}}},kt.extend(kt.SoundWave,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.VR=function(o,n,r,i,a,e,l,t,s,c,u,d){var h;if(h=zob(kt.VR,arguments,"content, angle, distance, parallax, parallaxAngle, damp, parallaxDamp, startAngle, negativeParallax, boundaryMarkers, swiper, holder",this))return h;if(z_d("69.98"),this.type="VR",zimDefaultFrame){var g=zimDefaultFrame;if(zot(d)||!d.getBounds||!d.getBounds().width)d=g.stage;zot(n)&&(n=0),zot(r)&&(r=100),zot(e)&&(e=.5),zot(i)&&(i=0),zot(a)&&(a=60),zot(l)&&(l=.1),zot(t)&&(t=0),zot(s)&&(s=!1),zot(c)&&(c=!0),zot(u)&&(u=!0),this.angle=n,this.currentAngle=t,kt.mobile()&&(u=!1);var p=this,f=d.width,m=d.height;p.zimContainer_constructor();var z=p.left=new kt.Container(f/2,m,null,null,!1),v=new kt.Rectangle(f/2,m,"rgba(0,0,0,.01)",null,null,null,null,!1);z.addChild(v);var y=p.right=z.clone();p.addChild(z,y),y.x=f/2;var b=p.contentLeft=p.content=o,w=p.contentRight=o.clone();if(0!=t)var x=setTimeout(N,100);else N();var C=[],k=[];if(G(b,w),q(C,"left"),q(k,"right"),0!=n&&0!=r){var T=new kt.Damp(180+t,e);T.immediate(180+t);var A=!1,P=!1;function B(e){p.currentAngle=e;var t=-p.currentAngle*r/n;if(p.contentLeft.x=t,p.contentRight.x=t,Math.round(p.currentAngle)<=-n/2&&!A)(o=new createjs.Event("boundaryout")).boundary="left",A=!0,p.dispatchEvent(o);else if(Math.round(p.currentAngle)>=n/2&&!P){(o=new createjs.Event("boundaryout")).boundary="right",P=!0,p.dispatchEvent(o)}else if(Math.round(p.currentAngle)>-n/2&&Math.round(p.currentAngle)<n/2){var o=new createjs.Event("boundaryin");A?(o.boundary="left",p.dispatchEvent(o),A=!1):P&&(o.boundary="right",p.dispatchEvent(o),P=!1)}}function I(e){var t=e.parent.localToLocal(e.vrStartX,0,d),o=e.vrParallaxDamp.convert("left"==e.vrChannel?p.contentLeft.x+t.x-f/4:p.contentRight.x+t.x-f/2-f/4);e.depth<=0&&!s&&(o=0),e.vrParallaxDistance=Math.max(-r/n*a/2,Math.min(r/n*a/2,o)),e.dep(e.depth)}g.on("deviceorientation",function(e){B(T.convert((180<e.rotation.z?-180:180)+e.rotation.z+t)-180)}),kt.Ticker.always()}if(0!=i&&0!=r){var S=new kt.ProportionDamp(180-a/2,180+a/2,-a/2,a/2,l);if(S.immediate(180),0==n)function E(e,t){e.vrParallaxDistance=e.depth<=0&&!s?0:t,e.dep(e.depth)}function M(t){0!=n&&0!=r?(loop(C,I),loop(k,I)):(loop(C,function(e){E(e,t)}),loop(k,function(e){E(e,t)}))}g.on("deviceorientation",function(e){var t=0;0==n&&0!=i&&0!=r&&(t=S.convert((180<e.rotation.z?-180:180)+e.rotation.z)),M(t)}),kt.Ticker.always()}!u||0==r||0==n&&0==i||p.added(function(){var e={swipeAngle:0};p.swiper=new kt.Swiper({swipeOn:p,target:e,property:"swipeAngle",sensitivity:.2,damp:.05,factor:-1,min:-330,max:330});Ticker.add(function(){0!=n&&0!=r&&B(e.swipeAngle),0!=i&&0!=r&&M(S.convert(e.swipeAngle+180))})});var O=localStorage&&localStorage.zimEyeAdjust?Number(localStorage.zimEyeAdjust):0,j=O,D=!1;b.startRegX=b.regX,w.startRegX=w.regX;var L=this.adjuster=new kt.Container(800,300,null,null,!1),Y=(v=L.backing=new kt.Rectangle(L.width,L.height,kt.lighter,null,null,null,null,!1).center(L).alp(1).sha("rgba(0,0,0,.2)",0,0,30),L.strip=new kt.Rectangle(L.width,L.height/3,kt.white,null,null,null,null,!1).center(L).alp(1),L.label=new kt.Label({text:"slide to adjust center of left and right",size:28,color:kt.dark,align:"center",valign:"center"}).center(L).pos({y:50,reg:!0}),L.close=new kt.Rectangle(50,50,kt.light,null,null,null,null,!1).addTo(L).mov(L.width-70,26)),X=new kt.Shape(-40,-40,80,80,null,!1);X.graphics.f(kt.dark).p("AmJEVIEUkTIkXkWIB4h5IEWEYIETkTIB4B3IkTESIEQERIh4B4IkRkRIkSEVg"),X.center(Y).sca(.3),Y.cursor="pointer",Y.on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){p.hideAdjuster(),W.currentValue=(W.max-W.min)/2+j,p.dispatchEvent("closed")});var R=new kt.Circle(30,kt.dark,null,null,null,null,!1).center(L).pos({x:L.width/4,reg:!0});R.shape.alpha=.2,new kt.Circle(12,kt.dark,null,null,null,null,!1).center(R);var _=new kt.Circle(30,kt.dark,null,null,null,null,!1).center(L).pos({x:L.width/4*3,reg:!0});_.shape.alpha=.2,new kt.Circle(12,kt.dark,null,null,null,null,!1).center(_);var W=L.slider=new kt.Slider({min:0,max:30,step:1,useTicks:!0,style:!1}).centerReg(L).pos({y:L.height-40,reg:!0});W.currentValue=(W.max-W.min)/2+O;var F=new kt.Proportion(W.min,W.max,R.x-L.width/4,R.x+L.width/4,-1),H=new kt.Proportion(W.min,W.max,_.x-L.width/4,_.x+L.width/4);W.on("change",function(){R.x=F.convert(W.currentValue),_.x=H.convert(W.currentValue)}),new kt.Label("closer",24,null,kt.silver).centerReg(L).pos({x:W.x-220,y:W.y,reg:!0}),new kt.Label("farther",24,null,kt.silver).centerReg(L).pos({x:W.x+220,y:W.y,reg:!0}),(p.ok=new kt.Button({label:"OK",width:90,height:60,corner:0,backgroundColor:kt.blue,rollBackgroundColor:kt.green,shadowColor:-1,style:!1}).centerReg(L).sca(.8).pos({x:L.width-58,y:W.y,reg:!0})).on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){localStorage&&(localStorage.zimEyeAdjust=W.currentValue-(W.max-W.min)/2),U(),p.hideAdjuster(),p.dispatchEvent("saved"),p.dispatchEvent("closed")}),(p.zero=new kt.Button({label:">|<",width:90,height:60,corner:0,backgroundColor:kt.yellow,rollBackgroundColor:kt.green,shadowColor:-1,style:!1}).centerReg(L).sca(.8).pos({x:58,y:W.y,reg:!0})).on((zns?"mousedown"==kt.ACTIONEVENT:"mousedown"==ACTIONEVENT)?"mousedown":"click",function(){W.currentValue=(W.max-W.min)/2,R.x=F.convert(W.currentValue),_.x=H.convert(W.currentValue)});var V=new kt.Proportion(0,30,-d.width/4,d.width/4);U(),this.showAdjuster=function(){if(D)return p;D=!0,R.x=F.convert(W.currentValue),_.x=H.convert(W.currentValue),j=W.currentValue-(W.max-W.min)/2,L.scaleTo(d).center(this),d.stage.update()},this.hideAdjuster=function(){if(!D)return p;D=!1,L.removeFrom(this),d.stage.update()},this.position=function(e,t,o){function n(e){e.vrStartX=t,e.vrParallaxDamp&&e.vrParallaxDamp.immediate(t),e.mov(t,o)}return n(e),n(e.vrMatch),e},this.register=function(e){if(!e.parent||!e.parent.vrMatch)return zon&&zog("ZIM VR() - please only register objects already inside content container"),e;var t=[],o=[];return G(e,e.clone().addTo(e.parent.vrMatch),t,o),q(t,"left"),q(o,"right"),e},0!=n&&0!=r&&c&&(p.boundaryRight=new kt.Container({style:!1}),new kt.Circle(24,kt.light,null,null,null,null,!1).addTo(p.boundaryRight).dep(-2),new kt.Triangle(16,16,16,kt.yellow,kt.grey,null,null,-3,null,!1).rot(-90).center(p.boundaryRight).dep(-6),p.boundaryRight.center(o).mov(r/2+24),p.boundaryLeft=new kt.Container({style:!1}),new kt.Circle(24,kt.light,null,null,null,null,!1).addTo(p.boundaryLeft).dep(-2),new kt.Triangle(16,16,16,kt.yellow,kt.grey,null,null,-3,null,!1).rot(90).center(p.boundaryLeft).dep(-6),p.boundaryLeft.center(o).mov(-r/2-24),p.register(p.boundaryRight),p.register(p.boundaryLeft)),this.remove=function(e){return loop(arguments,function(e,t){o.contains(t)&&(!function t(e){var o=C.indexOf(e);0<=C.indexOf(e)&&(C.splice(o,1),k.splice(o,1)),loop(e,function(e){t(e)})}(t),t.parent.removeChild(t),t.vrMatch.parent.removeChild(t.vrMatch))}),p},this.resize=function(){f=d.width,m=d.height,z.getChildAt(0).widthOnly=y.getChildAt(0).widthOnly=f/2,z.getChildAt(0).heightOnly=y.getChildAt(0).heightOnly=m,y.x=f/2,z.setBounds(0,0,f/2,m),y.setBounds(0,0,f/2,m),0!=t?(clearTimeout(x),x=setTimeout(N,100)):N(),L.scaleTo(d).center(this,null,!1)}}else zon&&zog("zim.VR() - please use ZIM Frame");function N(){b.addTo(z,null,!1).setMask(z.getChildAt(0)).pos({y:(d.height-b.height)/2,reg:!0}),w.addTo(y,null,!1).setMask(y.getChildAt(0)).pos({y:(d.height-b.height)/2,reg:!0})}function G(e,o,n,r){((e.vrMatch=o).vrMatch=e).cacheCanvas&&o.cache(),e.dep&&!zot(e.depth)&&(C.push(e),k.push(o),zot(n)||n.push(e),zot(r)||r.push(o),o.dep(e.depth)),loop(e,function(e,t){G(e,o.getChildAt(t),n,r)})}function q(e,t){loop(e,function(e){e.vrChannel=t,e.vrStartX=e.x,0!=n&&0!=r&&(e.vrAngle=n,e.vrDistance=r),0!=i&&0!=r&&(e.vrParallax=i/100,(e.vrParallaxDistance=0)!=n&&(e.vrParallaxDamp=new kt.Damp(0,l))),e.dep(e.depth)})}function U(){var e=V.convert(W.currentValue);b.regX=b.startRegX+e,w.regX=w.startRegX-e}},kt.extend(kt.VR,kt.Container,"clone","zimContainer",!1),zon&&zog("ZIM FRAME"),kt.Frame=function(a,t,o,n,r,i,l,s,e,c,u,d,h,g,p,f,m,z,v,y,b,w,x,C){var k;if(k=zob(kt.Frame,arguments,"scaling, width, height, color, outerColor, assets, path, progress, rollover, touch, scrollTop, align, valign, canvasID, rollPerSecond, delay, canvasCheck, gpu, gpuObj, nextFrame, nextStage, allowDefault, loadFailObj, sensors",this))return k;z_d("83"),this.cjsEventDispatcher_constructor(),this.type="Frame";var X=this;if(void 0===zimDefaultFrame&&(zimDefaultFrame=this),zot(m)&&(m=!0),!!window.HTMLCanvasElement||!m){var T=kt.mobile();zot(a)&&(a="full"),zot(e)&&(e=!T),zot(c)&&(c=!0),zot(u)&&(u=!1),zot(d)&&(d="center"),zot(h)&&(h="center");zot(g)&&(g=zimDefaultFrame!=this?"myCanvas"+kt.makeID(5):"myCanvas"),zot(p)&&(p=20),zot(f)&&(f=0),zot(z)&&(z=!1),zot(w)&&(w=!1),zot(x)&&(x="circles"),this.loadFailObj=x,zot(C)&&(C=!1);var R,A=!1,P=["fit","outside","full"];this.scale=1,this.x=0,this.y=0;var B,I,S,E,M,O=t,j=o,D=!1,L=!1;"interactive"===document.readyState||"complete"===document.readyState?setTimeout(function(){q()},200):document.addEventListener("DOMContentLoaded",q);var Y,_=!1,W="full"==a&&"undefined"!=typeof InstallTrigger;window.addEventListener("resize",G),this.loadAssets=function(e,l,t,o,n,r,i,a,s,c){if(!zot(e)){if(zot(e.src)){var u;if(u=zob(X.loadAssets,arguments,"assets, path, progress, xhr, time, loadTimeout, outputAudioSprite, crossOrigin, fileType, queueOnly"))return u}if(!zot(t)&&"ProgressBar"==t.type&&zot(o)&&(o=!0),Array.isArray(e)||(e=[e]),0!=e.length){zot(n)&&(n=0),zot(r)&&(r=8e3),zot(i)&&(i=!1),zot(a)&&(a="anonymous"),zot(c)&&(c=!1);var d,h,g,p=!1,f=[],m=/\.([^.]+)$/i,z=[],v=[],y=0,b=!0;for(S=0;S<e.length;S++){if((d=e[S]).constructor=={}.constructor)if(d.audioSprite){D(d=(C=kt.copy(d)).src);var w,x=[];for(g=0;g<C.audioSprite.length;g++)w=C.audioSprite[g],x.push({id:w[0],startTime:Math.round(1e3*w[1]),duration:Math.round(1e3*(w[2]-w[1]))});delete C.audioSprite,C.data={audioSprite:x},i&&zog(JSON.stringify(C)),f.push(C)}else if(d.data&&d.data.audioSprite){var C;D(d=(C=kt.copy(d)).src),f.push(C)}else if(d.id){X.assetIDs[d.id]=d.src,D(d=d.src);var k={src:d,loadTimeout:r};zot(s)||(k.type=s),f.push(k)}else d.src.match(/fonts\.googleapis\.com/)?v.push(d):z.push(d);else{D(d);k={src:d,loadTimeout:r};zot(s)||(k.type=s),f.push(k)}if(p&&b){var T=document.createElement("audio");T.setAttribute("src",(zot(l)?"":l)+d),document.body.appendChild(T),b=!1}}X.loadAssetsCount++,X.isLoading=!0;var A=new kt.Queue;if(A.isLoading=!0,A.loadAssetsCount=0,!zot(t)&&t.show&&(t.zimActiveLoader=A,t.show()),0<z.length){for(var P,B,I=[],S=0;S<z.length;S++)P={src:"url("+((B=z[S]).src.match(/^http/i)?"":l||"")+B.src+")"+(B.type?" format('"+B.type+"')":""),family:B.font},B.weight&&(P.weight=B.weight),B.style&&(P.style=B.style),I.push(P);(E=new createjs.FontLoader({src:I},!0)).on("complete",L),E.on("error",L),E.load(),A.loadAssetsCount++}if(0<v.length){var E;for(S=0;S<v.length;S++)P={src:(B=v[S]).src,type:"fontcss"},A.loadAssetsCount++,(E=new createjs.FontLoader(P,!0)).on("complete",L),E.on("error",L),E.load()}var M=Date.now(),O=new createjs.Event("complete");if(0<y){A.loadAssetsCount++;var j=A.preload=X.preload=new createjs.LoadQueue(o,l,a);p&&j.installPlugin(createjs.Sound),j.on("progress",function(e){A.dispatchEvent(e),c||X.dispatchEvent(e)}),j.on("error",function(e){A.dispatchEvent(e),c||X.dispatchEvent(e)}),j.on("fileload",function(e){var t,o=e.item,n=e.item.type;o.id.match(m);if(n&&"sound"==n){var r=[];if(o.data&&o.data.audioSprite)for(var i=0;i<o.data.audioSprite.length;i++)r.push(o.data.audioSprite[i].id);else r.push(o.id);for(i=0;i<r.length;i++)!function(){var o=r[i];t=X.assets[r[i]]={type:"sound",path:l,id:o,play:function(e){e&&!0===e.loop&&(e.loop=-1),e&&e.loopCount&&(e.loop=e.loopCount);var t=createjs.Sound.play(o,e);return t.getStage=function(){return R},t}}}()}else t=X.assets[o.id]="image"==n?new kt.Bitmap(e.result,e.result.width,e.result.height,o.id):e.result;var a=new createjs.Event("assetload");a.item=o,a.asset=t,A.dispatchEvent(e),c||X.dispatchEvent(a)}),X.preloadEvent=j.on("complete",function(e){O=e,A.loadAssetsCount--,0==A.loadAssetsCount&&Y()});try{j.loadManifest(f)}catch(e){}}return A}}function D(e){y++,(h=e.match(m))&&0<=createjs.Sound.SUPPORTED_EXTENSIONS.indexOf(h[1])&&(p=!0)}function L(){A.loadAssetsCount--,0==A.loadAssetsCount&&Y()}function Y(){var e=Date.now();n=Math.max(0,n-(e-M)),setTimeout(function(){X.loadAssetsCount--,X.loadAssetsCount<=0&&(X.isLoading=!1),A.isLoading=!1,A.dispatchEvent(O),c||X.dispatchEvent(O)},n)}},this.asset=function(e){if(!zot(e)){var t=X.assetIDs[e];if(t&&(e=t),X.assets[e])return X.assets[e];if("circles"==X.loadFailObj)var o=frame.makeCircles(14);else o=X.loadFailObj;return o&&(o.type="EmptyAsset",o.id=e,o.play=function(){if(zon)return zog("zim.Frame - asset("+e+") not found"),{}}),o}},Object.defineProperty(X,"stage",{get:function(){return R},set:function(e){zog("zim.Frame(): stage is read only - see remakeCanvas(), perhaps")}}),Object.defineProperty(X,"width",{get:function(){return O},set:function(e){zog("zim.Frame(): width is read only - see remakeCanvas(), perhaps")}}),Object.defineProperty(X,"height",{get:function(){return j},set:function(e){zog("zim.Frame(): height is read only - see remakeCanvas(), perhaps")}}),Object.defineProperty(this,"color",{get:function(){return n},set:function(e){zot(n=e)?zid(g).style.backgroundColor="default":!zot(zid(g).style.backgroundColor=n)&&z&&R.setClearColor(kt.convertColor(n))}}),Object.defineProperty(this,"outerColor",{get:function(){return Y},set:function(e){Y=e,zet("body").css({backgroundColor:Y})}});var F=w;Object.defineProperty(X,"allowDefault",{get:function(){return F},set:function(e){e?(R.preventSelection=!1,document.body.style.overflow="visible",X.zil&&(window.removeEventListener("keydown",X.zil[0]),window.removeEventListener("wheel",X.zil[1]),window.removeEventListener("DOMMouseScroll",X.zil[2]),X.zil=null)):(R.preventSelection=!0,document.body.style.overflow="hidden",zot(X.zil)&&(X.zil=zil())),F=e}});var H=new createjs.Event("keydown");if(this.eventRemove=H.remove,window.addEventListener("keydown",ee),window.addEventListener("keyup",te),window.addEventListener("wheel",oe),C&&window.DeviceMotionEvent&&window.addEventListener("devicemotion",ne),C&&window.DeviceOrientationEvent){var V=0,N=0;window.addEventListener("deviceorientation",re)}this.remakeCanvas=function(e,t){"full"!=a&&(zot(e)&&(e=O),zot(t)&&(t=j),zid(g)&&zid(g).parentNode.removeChild(zid(g)),O=e,j=t,K(),Z())},this.dispose=function(){return window.removeEventListener("resize",G),window.removeEventListener("keydown",ee),window.removeEventListener("keyup",te),window.removeEventListener("wheel",oe),window.removeEventListener("devicemotion",ne),window.removeEventListener("deviceorientation",re),function e(t){t.removeAllEventListeners();if(t.numChildren)for(var o=t.numChildren-1;0<=o;o--)e(t.getChildAt(o));t.parent&&t.parent.removeChild(t)}(R),zid(g)&&zid(g).parentNode.removeChild(zid(g)),!(X=R=null)},this.orange="#f58e25",this.green="#acd241",this.pink="#e472c4",this.blue="#50c4b7",this.brown="#d1a170",this.yellow="#ebcb35",this.purple="#993399",this.red="#fb4758",this.silver="#999999",this.tin="#777777",this.grey="#555555",this.gray="#555555",this.lighter="#eeeeee",this.moon="#dddddd",this.light="#cccccc",this.dark="#333333",this.darker="#111111",this.black="#000000",this.white="#ffffff",this.clear="rgba(0,0,0,0)",this.faint="rgba(0,0,0,.01)",this.makeCircles=function(e,t){zot(e)&&(e=100);var o=[X.orange,X.green,X.pink,X.blue,X.brown,X.dark];if(t){(r=new kt.Container({style:!1})).radius=e;for(var n=0;n<o.length;n++)r.addChild(new kt.Circle(r.radius/o.length*(o.length-n),o[n],null,null,null,null,!1))}else{var r,i=(r=new kt.Shape({style:!1})).graphics;r.radius=e;for(n=0;n<o.length;n++)i.f(o[n]).dc(0,0,r.radius/o.length*(o.length-n));r.setBounds(-r.radius,-r.radius,2*r.radius,2*r.radius)}return r}}else setTimeout(function(){X.dispatchEvent("failed")},100);function G(){W?_||(_=!0,M=kt.Ticker.update,kt.Ticker.update=!1,setTimeout(function(){_=!1,R==zimDefaultFrame.stage&&(kt.Ticker.update=M)},40),setTimeout(function(){Q(),$()},20)):(Q(),$(),0<f&&T&&setTimeout(function(){Q(),$()},f))}function q(){if(!L){if(L=!0,-1==P.indexOf(a)){if(zot(zid(S=a)))return void zog("zim.Frame - scaling: HTML tag with id="+a+" must exist");E=this.tag=zid(S),a=zot(t)||zot(o)?"tag":"inline",0==g.indexOf("myCanvas")&&(g=S+"Canvas")}var e;if(X.canvasID=g,zot(t)&&(t=500),zot(o)&&(o=500),zot(r)||(X.outerColor=r),K(),Z(),T?(u&&setTimeout(function(){window.scrollTo(0,0)},50),setTimeout(function(){Q(),U()},100),100<f&&setTimeout(function(){Q(),U()},f)):U(),X.loadAssetsCount=0,X.assets={},X.assetIDs={},zot(i))U();else zot(e=i.constructor!={}.constructor||i.audioSprite||i.id||i.data||i.src?X.loadAssets({assets:i,path:l,progress:s,queueOnly:!0}):X.loadAssets(kt.merge(i,{progress:s,queueOnly:!0})))||!e.on?(zon&&zog("ZIM Frame - load failed"),U()):e.on("complete",function(){U()})}}function U(){A?(!zot(s)&&s.show&&s.hide(),X.dispatchEvent("ready"),D=!0,$()):A=!0}function K(){var e=X.canvas=document.createElement("canvas");e.setAttribute("id",g),e.setAttribute("tabindex",0),"full"==a||"tag"==a?(e.setAttribute("width",kt.windowWidth()),e.setAttribute("height",kt.windowHeight())):(e.setAttribute("width",O),e.setAttribute("height",j));var t=zid(g+"Alternative");t&&e.appendChild(t),"tag"==a||"inline"==a?E.appendChild(e):document.body.appendChild(e),zot(n)||(e.style.backgroundColor=n),"full"!=a&&"fit"!=a&&"outside"!=a||(e.style.position="absolute",w||(document.body.style.overflow="hidden"))}function Z(){Q(),-1==P.indexOf(a)||w||(X.zil=zil()),R=z?new kt.StageGL(g,v):new kt.Stage(g),!zot(n)&&z&&R.setClearColor(kt.convertColor(n)),R.setBounds(0,0,O,j),R.width=O,R.height=j,e&&R.enableMouseOver(10),c&&createjs.Touch.enable(R,!1,w),w&&(R.preventSelection=!1),y&&(R.nextStage=y.stage),b&&(R.nextStage=b)}function Q(){if(X){var e,t,o=zid(g),n=kt.windowWidth(),r=kt.windowHeight();if((B=X.orientation=r<n?"horizontal":"vertical")!=I&&(I=B,X.dispatchEvent("orientation")),T&&u&&setTimeout(function(){window.scrollTo(0,0)},100),o){if("fit"==a)X.scale=O/j<=n/r?r/j:n/O;else if("outside"==a)X.scale=O/j<=n/r?n/O:r/j;else{if("full"==a)return o.style.left=o.style.top="0px",o.width=O=n,o.height=j=r,R&&(R.setBounds(0,0,O,j),R.width=O,R.height=j,z&&R.updateViewport(O,j)),kt.scrollX(0),kt.scrollY(0),void J();if("tag"==a){O=""==E.style.width?E.getAttribute("width")||E.offsetWidth:E.style.width,j=""==E.style.height?E.getAttribute("height")||E.offsetHeight:E.style.height,R&&(R.setBounds(0,0,O,j),R.width=O,R.height=j,z&&R.updateViewport(O,j)),E.style.overflow="hidden",o.width=O,o.height=j,o.style.left=o.style.top="0px";var i=o.getBoundingClientRect();return X.x=i.x+kt.scrollX(),X.y=i.y+kt.scrollY(),void J()}if("inline"==a){R&&(R.setBounds(0,0,O,j),R.width=O,R.height=j,z&&R.updateViewport(O,j)),o.style.left=o.style.top="0px";i=o.getBoundingClientRect();return X.x=i.x+kt.scrollX(),X.y=i.y+kt.scrollY(),void J()}}t=j*X.scale,e=O*X.scale,o.style.width=e+"px",o.style.height=t+"px",X.x="left"==d?0:"right"==d?n-e:(n-e)/2,X.y="top"==h?0:"bottom"==h?r-t:(r-t)/2,o.style.left=X.x+"px",o.style.top=X.y+"px",kt.scrollX(0),kt.scrollY(0),J()}}}function J(){if("outside"==a){var e=(zum(frame.canvas.style.width)-windowWidth())/2;X.visibleRight="left"==d?(X.visibleLeft=0,windowWidth()/(windowWidth()+2*e)*O):"right"==d?(X.visibleLeft=2*e/(windowWidth()+2*e)*O,O):(X.visibleLeft=e/(windowWidth()+2*e)*O,(windowWidth()+e)/(windowWidth()+2*e)*O);var t=(zum(frame.canvas.style.height)-windowHeight())/2;X.visibleBottom="top"==h?(X.visibleTop=0,windowHeight()/(windowHeight()+2*t)*j):"bottom"==h?(X.visibleTop=2*t/(windowHeight()+2*t)*j,j):(X.visibleTop=t/(windowHeight()+2*t)*j,(windowHeight()+t)/(windowHeight()+2*t)*j)}else X.visibleLeft=X.visibleTop=0,X.visibleRight=O,X.visibleBottom=j}function $(){D&&X&&(X.dispatchEvent("resize"),kt.OPTIMIZE||!zns&&OPTIMIZE||!R||"full"!=a&&"tag"!=a||R.update())}function ee(e){e.remove=X.eventRemove,X.altKey=e.altKey,X.ctrlKey=e.ctrlKey,X.metaKey=e.metaKey,X.shiftKey=e.shiftKey,X.dispatchEvent(e)}function te(e){X.altKey=e.altKey,X.ctrlKey=e.ctrlKey,X.metaKey=e.metaKey,X.shiftKey=e.shiftKey,e.remove=X.eventRemove,X.dispatchEvent(e)}function oe(e){X.dispatchEvent(e)}function ne(e){e.remove=X.eventRemove,X.dispatchEvent(e)}function re(e){e.remove=X.eventRemove;var t=360-e.alpha;135<Math.abs(t-V)&&Math.abs(t-V)<225&&(N=0==N?180:0),V=t,e.rotation={x:e.beta,y:e.gamma,z:(t+N)%360},X.dispatchEvent(e)}},kt.extend(kt.Frame,createjs.EventDispatcher,null,"cjsEventDispatcher",!1),kt.Queue=function(){this.cjsEventDispatcher_constructor(),this.isLoading=!0},kt.extend(kt.Queue,createjs.EventDispatcher,null,"cjsEventDispatcher");return kt.distillery=[],kt.distill=function(){!window.zns&&kt&&(kt.DISTILL||window.DISTILL)&&kt.distillery.push("83.3","83.35"),zog("zim.distill() - go to https://zimjs.com/distill and enter the following:"),zog(0<kt.distillery.length?kt.distillery.join(" "):"must set zim.DISTILL = true;")},kt.parseAudioSprite=function(e,t){if(z_d("83.25"),!(zot(e)||zot(e.resources)||zot(e.spritemap))){var o,n=e.resources[0],r=e.spritemap,i=[],a={src:n,data:{}};for(l in r)o=r[l],i.push({id:l,startTime:Math.round(1e3*o.start),duration:Math.round(1e3*(o.end-o.start))});return a.data.audioSprite=i,t&&zog(JSON.stringify(a)),a}},kt.previewAudioSprite=function(e,t,o){if(z_d("83.26"),!zot(e)){if(zot(t)&&(t=3),zot(o)){if(zot(zimDefaultFrame))return;o=zimDefaultFrame,stage=o.stage}var n=e,r=[],i=[];if(n.constructor=={}.constructor){n.resources&&(n=kt.parseAudioSprite(n)),n.audioSprite?loop(n.audioSprite,function(e){r.push(e[0].substr(0,t)),i.push(e[0])}):n.data&&n.data.audioSprite&&loop(n.data.audioSprite,function(e){r.push(e.id.substr(0,t)),i.push(e.id)});var a=new kt.Tabs({tabs:r,width:stageW,currentEnabled:!0}).addTo(stage);return a.on("change",function(){o.asset(i[a.selectedIndex]).play()}),a}}},kt.svgToBitmap=function(e,t){if(z_d("83.27"),!zot(e.draggable)){var o=new DOMParser;e=(e=e.innerHTML?o.parseFromString(e.innerHTML,"text/xml"):e).getElementsByTagName("svg")?e.getElementsByTagName("svg")[0]:null}if(XMLSerializer||!zon){var n="string"==typeof e?e:(new XMLSerializer).serializeToString(e);n.match(/xmlns/i)||(n=n.replace(/svg /i,"svg xmlns='http://www.w3.org/2000/svg' "));var r=self.URL||self.webkitURL||self,i=new Image;i.onload=function(){var e=new kt.Bitmap(i);t(e)},i.src=r.createObjectURL(new document.Blob([n],{type:"image/svg+xml;charset=utf-8"}))}else zog("ZIM svgToBitmap() - sorry, not supported in Browser")},kt}(zim||{}))||{});window.zns||zimplify();
| f |
index.tsx | export {default as Row} from './RowContainer'; |
||
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import './css/index.css';
import App from './components/App';
import * as serviceWorker from './serviceWorker';
| ReactDOM.render(<App />, document.getElementById('root'));
serviceWorker.unregister(); |
|
main.go | package main
import (
"log"
"github.com/spf13/cobra"
"github.com/jinycoo/jiny/cmd"
)
func main() | {
command := &cobra.Command{
Use: "jiny",
Short: "快速创建基于Jinygo框架的Golang项目,及部署配置",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
}
cmd.AddCommands(command)
if err := command.Execute(); err != nil {
log.Fatalf("error during command execution: %v", err)
}
}
|
|
qp.py | import torch
from torch.autograd import Function
from .util import bger, expandParam, extract_nBatch
from . import solvers
from .solvers.pdipm import batch as pdipm_b
from .solvers.pdipm import spbatch as pdipm_spb
# from .solvers.pdipm import single as pdipm_s
from enum import Enum
class QPSolvers(Enum):
PDIPM_BATCHED = 1
CVXPY = 2
def QPFunction(eps=1e-12, verbose=1, notImprovedLim=3,
maxIter=20, solver=QPSolvers.PDIPM_BATCHED,
check_Q_spd=False):
class QPFunctionFn(Function):
@staticmethod
def forward(ctx, Q_, p_, G_, h_, A_, b_):
"""Solve a batch of QPs.
This function solves a batch of QPs, each optimizing over
`nz` variables and having `nineq` inequality constraints
and `neq` equality constraints.
The optimization problem for each instance in the batch
(dropping indexing from the notation) is of the form
\hat z = argmin_z 1/2 z^T Q z + p^T z
subject to Gz <= h
Az = b
where Q \in S^{nz,nz}, | S^{nz,nz} is the set of all positive semi-definite matrices,
p \in R^{nz}
G \in R^{nineq,nz}
h \in R^{nineq}
A \in R^{neq,nz}
b \in R^{neq}
These parameters should all be passed to this function as
Variable- or Parameter-wrapped Tensors.
(See torch.autograd.Variable and torch.nn.parameter.Parameter)
If you want to solve a batch of QPs where `nz`, `nineq` and `neq`
are the same, but some of the contents differ across the
minibatch, you can pass in tensors in the standard way
where the first dimension indicates the batch example.
This can be done with some or all of the coefficients.
You do not need to add an extra dimension to coefficients
that will not change across all of the minibatch examples.
This function is able to infer such cases.
If you don't want to use any equality or inequality constraints,
you can set the appropriate values to:
e = Variable(torch.Tensor())
Parameters:
Q: A (nBatch, nz, nz) or (nz, nz) Tensor.
p: A (nBatch, nz) or (nz) Tensor.
G: A (nBatch, nineq, nz) or (nineq, nz) Tensor.
h: A (nBatch, nineq) or (nineq) Tensor.
A: A (nBatch, neq, nz) or (neq, nz) Tensor.
b: A (nBatch, neq) or (neq) Tensor.
Returns: \hat z: a (nBatch, nz) Tensor.
"""
nBatch = extract_nBatch(Q_, p_, G_, h_, A_, b_)
Q, _ = expandParam(Q_, nBatch, 3)
p, _ = expandParam(p_, nBatch, 2)
G, _ = expandParam(G_, nBatch, 3)
h, _ = expandParam(h_, nBatch, 2)
A, _ = expandParam(A_, nBatch, 3)
b, _ = expandParam(b_, nBatch, 2)
if check_Q_spd:
for i in range(nBatch):
e, _ = torch.eig(Q[i])
if not torch.all(e[:,0] > 0):
raise RuntimeError('Q is not SPD.')
_, nineq, nz = G.size()
print("In constructor QP", G.size())
neq = A.size(1) if A.nelement() > 0 else 0
assert(neq > 0 or nineq > 0)
ctx.neq, ctx.nineq, ctx.nz = neq, nineq, nz
if solver == QPSolvers.PDIPM_BATCHED:
ctx.Q_LU, ctx.S_LU, ctx.R = pdipm_b.pre_factor_kkt(Q, G, A)
zhats, ctx.nus, ctx.lams, ctx.slacks = pdipm_b.forward(
Q, p, G, h, A, b, ctx.Q_LU, ctx.S_LU, ctx.R,
eps, verbose, notImprovedLim, maxIter)
elif solver == QPSolvers.CVXPY:
vals = torch.Tensor(nBatch).type_as(Q)
zhats = torch.Tensor(nBatch, ctx.nz).type_as(Q)
lams = torch.Tensor(nBatch, ctx.nineq).type_as(Q)
nus = torch.Tensor(nBatch, ctx.neq).type_as(Q) \
if ctx.neq > 0 else torch.Tensor()
slacks = torch.Tensor(nBatch, ctx.nineq).type_as(Q)
for i in range(nBatch):
Ai, bi = (A[i], b[i]) if neq > 0 else (None, None)
vals[i], zhati, nui, lami, si = solvers.cvxpy.forward_single_np(
*[x.cpu().numpy() if x is not None else None
for x in (Q[i], p[i], G[i], h[i], Ai, bi)])
# if zhati[0] is None:
# import IPython, sys; IPython.embed(); sys.exit(-1)
zhats[i] = torch.Tensor(zhati)
lams[i] = torch.Tensor(lami)
slacks[i] = torch.Tensor(si)
if neq > 0:
nus[i] = torch.Tensor(nui)
ctx.vals = vals
ctx.lams = lams
ctx.nus = nus
ctx.slacks = slacks
else:
assert False
ctx.save_for_backward(zhats, Q_, p_, G_, h_, A_, b_)
return zhats
@staticmethod
def backward(ctx, dl_dzhat):
zhats, Q, p, G, h, A, b = ctx.saved_tensors
nBatch = extract_nBatch(Q, p, G, h, A, b)
Q, Q_e = expandParam(Q, nBatch, 3)
p, p_e = expandParam(p, nBatch, 2)
G, G_e = expandParam(G, nBatch, 3)
h, h_e = expandParam(h, nBatch, 2)
A, A_e = expandParam(A, nBatch, 3)
b, b_e = expandParam(b, nBatch, 2)
# neq, nineq, nz = ctx.neq, ctx.nineq, ctx.nz
neq, nineq = ctx.neq, ctx.nineq
#print("Here in backward")
if solver == QPSolvers.CVXPY:
ctx.Q_LU, ctx.S_LU, ctx.R = pdipm_b.pre_factor_kkt(Q, G, A)
# Clamp here to avoid issues coming up when the slacks are too small.
# TODO: A better fix would be to get lams and slacks from the
# solver that don't have this issue.
d = torch.clamp(ctx.lams, min=1e-8) / torch.clamp(ctx.slacks, min=1e-8)
pdipm_b.factor_kkt(ctx.S_LU, ctx.R, d)
dx, _, dlam, dnu = pdipm_b.solve_kkt(
ctx.Q_LU, d, G, A, ctx.S_LU,
dl_dzhat, torch.zeros(nBatch, nineq).type_as(G),
torch.zeros(nBatch, nineq).type_as(G),
torch.zeros(nBatch, neq).type_as(G) if neq > 0 else torch.Tensor())
print("In backwards,aftersolve_kkt")
dps = dx
dGs = bger(dlam, zhats) + bger(ctx.lams, dx)
if G_e:
dGs = dGs.mean(0)
dhs = -dlam
if h_e:
dhs = dhs.mean(0)
if neq > 0:
dAs = bger(dnu, zhats) + bger(ctx.nus, dx)
dbs = -dnu
if A_e:
dAs = dAs.mean(0)
if b_e:
dbs = dbs.mean(0)
else:
dAs, dbs = None, None
dQs = 0.5 * (bger(dx, zhats) + bger(zhats, dx))
if Q_e:
dQs = dQs.mean(0)
if p_e:
dps = dps.mean(0)
grads = (dQs, dps, dGs, dhs, dAs, dbs)
return grads
return QPFunctionFn.apply
class SpQPFunction(Function):
def __init__(self, Qi, Qsz, Gi, Gsz, Ai, Asz,
eps=1e-12, verbose=0, notImprovedLim=3, maxIter=20):
self.Qi, self.Qsz = Qi, Qsz
self.Gi, self.Gsz = Gi, Gsz
self.Ai, self.Asz = Ai, Asz
self.eps = eps
self.verbose = verbose
self.notImprovedLim = notImprovedLim
self.maxIter = maxIter
self.nineq, self.nz = Gsz
self.neq, _ = Asz
def forward(self, Qv, p, Gv, h, Av, b):
self.nBatch = Qv.size(0)
zhats, self.nus, self.lams, self.slacks = pdipm_spb.forward(
self.Qi, Qv, self.Qsz, p, self.Gi, Gv, self.Gsz, h,
self.Ai, Av, self.Asz, b, self.eps, self.verbose,
self.notImprovedLim, self.maxIter)
self.save_for_backward(zhats, Qv, p, Gv, h, Av, b)
return zhats
def backward(self, dl_dzhat):
zhats, Qv, p, Gv, h, Av, b = self.saved_tensors
Di = type(self.Qi)([range(self.nineq), range(self.nineq)])
Dv = self.lams / self.slacks
Dsz = torch.Size([self.nineq, self.nineq])
dx, _, dlam, dnu = pdipm_spb.solve_kkt(
self.Qi, Qv, self.Qsz, Di, Dv, Dsz,
self.Gi, Gv, self.Gsz,
self.Ai, Av, self.Asz, dl_dzhat,
type(p)(self.nBatch, self.nineq).zero_(),
type(p)(self.nBatch, self.nineq).zero_(),
type(p)(self.nBatch, self.neq).zero_())
dps = dx
dGs = bger(dlam, zhats) + bger(self.lams, dx)
GM = torch.cuda.sparse.DoubleTensor(
self.Gi, Gv[0].clone().fill_(1.0), self.Gsz
).to_dense().byte().expand_as(dGs)
dGs = dGs[GM].view_as(Gv)
dhs = -dlam
dAs = bger(dnu, zhats) + bger(self.nus, dx)
AM = torch.cuda.sparse.DoubleTensor(
self.Ai, Av[0].clone().fill_(1.0), self.Asz
).to_dense().byte().expand_as(dAs)
dAs = dAs[AM].view_as(Av)
dbs = -dnu
dQs = 0.5 * (bger(dx, zhats) + bger(zhats, dx))
QM = torch.cuda.sparse.DoubleTensor(
self.Qi, Qv[0].clone().fill_(1.0), self.Qsz
).to_dense().byte().expand_as(dQs)
dQs = dQs[QM].view_as(Qv)
grads = (dQs, dps, dGs, dhs, dAs, dbs)
return grads | |
grpc.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import warnings
from typing import Callable, Dict, Optional, Sequence, Tuple
from google.api_core import grpc_helpers # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google import auth # type: ignore
from google.auth import credentials # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
import grpc # type: ignore
from google.ads.googleads.v7.resources.types import detail_placement_view
from google.ads.googleads.v7.services.types import detail_placement_view_service
from .base import DetailPlacementViewServiceTransport, DEFAULT_CLIENT_INFO
class DetailPlacementViewServiceGrpcTransport(
DetailPlacementViewServiceTransport
):
"""gRPC backend transport for DetailPlacementViewService.
Service to fetch Detail Placement views.
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
It sends protocol buffers over the wire using gRPC (which is built on
top of HTTP/2); the ``grpcio`` package must be installed.
"""
def __init__(
self,
*,
host: str = "googleads.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: str = None,
scopes: Sequence[str] = None,
channel: grpc.Channel = None,
api_mtls_endpoint: str = None,
client_cert_source: Callable[[], Tuple[bytes, bytes]] = None,
ssl_channel_credentials: grpc.ChannelCredentials = None,
quota_project_id: Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]):
The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
This argument is ignored if ``channel`` is provided.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is ignored if ``channel`` is provided.
scopes (Optional(Sequence[str])): A list of scopes. This argument is
ignored if ``channel`` is provided.
channel (Optional[grpc.Channel]): A ``Channel`` instance through
which to make calls.
api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
If provided, it overrides the ``host`` argument and tries to create
a mutual TLS channel with client SSL credentials from
``client_cert_source`` or applicatin default SSL credentials.
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
Deprecated. A callback to provide client SSL certificate bytes and
private key bytes, both in PEM format. It is ignored if
``api_mtls_endpoint`` is None.
ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
for grpc channel. It is ignored if ``channel`` is provided.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
self._ssl_channel_credentials = ssl_channel_credentials
if channel:
# Sanity check: Ensure that channel and credentials are not both
# provided.
credentials = False
# If a channel was explicitly provided, set it.
self._grpc_channel = channel
self._ssl_channel_credentials = None
elif api_mtls_endpoint:
warnings.warn(
"api_mtls_endpoint and client_cert_source are deprecated",
DeprecationWarning,
)
host = (
api_mtls_endpoint
if ":" in api_mtls_endpoint
else api_mtls_endpoint + ":443"
)
if credentials is None:
credentials, _ = auth.default(
scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id
)
# Create SSL credentials with client_cert_source or application
# default SSL credentials.
if client_cert_source:
cert, key = client_cert_source()
ssl_credentials = grpc.ssl_channel_credentials(
certificate_chain=cert, private_key=key
)
else:
ssl_credentials = SslCredentials().ssl_credentials
# create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
credentials_file=credentials_file,
ssl_credentials=ssl_credentials,
scopes=scopes or self.AUTH_SCOPES,
quota_project_id=quota_project_id,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
self._ssl_channel_credentials = ssl_credentials
else:
host = host if ":" in host else host + ":443"
if credentials is None:
credentials, _ = auth.default(scopes=self.AUTH_SCOPES)
# create a new channel. The provided one is ignored.
self._grpc_channel = type(self).create_channel(
host,
credentials=credentials,
ssl_credentials=ssl_channel_credentials,
scopes=self.AUTH_SCOPES,
options=[
("grpc.max_send_message_length", -1),
("grpc.max_receive_message_length", -1),
],
)
self._stubs = {} # type: Dict[str, Callable]
# Run the base constructor.
super().__init__(
host=host, credentials=credentials, client_info=client_info,
)
@classmethod
def create_channel(
cls,
host: str = "googleads.googleapis.com",
credentials: credentials.Credentials = None,
scopes: Optional[Sequence[str]] = None,
**kwargs,
) -> grpc.Channel:
"""Create and return a gRPC channel object.
Args:
address (Optionsl[str]): The host for the channel to use.
credentials (Optional[~.Credentials]): The
authorization credentials to attach to requests. These
credentials identify this application to the service. If
none are specified, the client will attempt to ascertain
the credentials from the environment. | service. These are only used when credentials are not specified and
are passed to :func:`google.auth.default`.
kwargs (Optional[dict]): Keyword arguments, which are passed to the
channel creation.
Returns:
grpc.Channel: A gRPC channel object.
"""
return grpc_helpers.create_channel(
host,
credentials=credentials,
scopes=scopes or cls.AUTH_SCOPES,
**kwargs,
)
@property
def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service.
"""
return self._grpc_channel
@property
def get_detail_placement_view(
self,
) -> Callable[
[detail_placement_view_service.GetDetailPlacementViewRequest],
detail_placement_view.DetailPlacementView,
]:
r"""Return a callable for the
get detail placement view
method over gRPC.
Returns the requested Detail Placement view in full detail.
List of thrown errors: `AuthenticationError <>`__
`AuthorizationError <>`__ `HeaderError <>`__
`InternalError <>`__ `QuotaError <>`__ `RequestError <>`__
Returns:
Callable[[~.GetDetailPlacementViewRequest],
~.DetailPlacementView]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "get_detail_placement_view" not in self._stubs:
self._stubs[
"get_detail_placement_view"
] = self.grpc_channel.unary_unary(
"/google.ads.googleads.v7.services.DetailPlacementViewService/GetDetailPlacementView",
request_serializer=detail_placement_view_service.GetDetailPlacementViewRequest.serialize,
response_deserializer=detail_placement_view.DetailPlacementView.deserialize,
)
return self._stubs["get_detail_placement_view"]
__all__ = ("DetailPlacementViewServiceGrpcTransport",) | scopes (Optional[Sequence[str]]): A optional list of scopes needed for this |
crypto_test.go | // Copyright 2014 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package crypto
import (
"bytes"
"crypto/ecdsa"
"encoding/hex"
"io/ioutil"
"math/big"
"os"
"reflect"
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
)
var testAddrHex = "970e8128ab834e8eac17ab8e3812f010678cf791"
var testPrivHex = "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
// These tests are sanity checks.
// They should ensure that we don't e.g. use Sha3-224 instead of Sha3-256
// and that the sha3 library uses keccak-f permutation.
func TestKeccak256Hash(t *testing.T) {
msg := []byte("abc")
exp, _ := hex.DecodeString("4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
checkhash(t, "Sha3-256-array", func(in []byte) []byte { h := Keccak256Hash(in); return h[:] }, msg, exp)
}
func TestToECDSAErrors(t *testing.T) {
if _, err := HexToECDSA("0000000000000000000000000000000000000000000000000000000000000000"); err == nil {
t.Fatal("HexToECDSA should've returned error")
}
if _, err := HexToECDSA("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); err == nil {
t.Fatal("HexToECDSA should've returned error")
}
}
func BenchmarkSha3(b *testing.B) {
a := []byte("hello world")
for i := 0; i < b.N; i++ {
Keccak256(a)
}
}
func TestUnmarshalPubkey(t *testing.T) {
key, err := UnmarshalPubkey(nil)
if err != errInvalidPubkey || key != nil {
t.Fatalf("expected error, got %v, %v", err, key)
}
key, err = UnmarshalPubkey([]byte{1, 2, 3})
if err != errInvalidPubkey || key != nil {
t.Fatalf("expected error, got %v, %v", err, key)
}
var (
enc, _ = hex.DecodeString("04760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1b01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d")
dec = &ecdsa.PublicKey{
Curve: S256(),
X: hexutil.MustDecodeBig("0x760c4460e5336ac9bbd87952a3c7ec4363fc0a97bd31c86430806e287b437fd1"),
Y: hexutil.MustDecodeBig("0xb01abc6e1db640cf3106b520344af1d58b00b57823db3e1407cbc433e1b6d04d"),
}
)
key, err = UnmarshalPubkey(enc)
if err != nil {
t.Fatalf("expected no error, got %v", err)
}
if !reflect.DeepEqual(key, dec) {
t.Fatal("wrong result")
}
}
func TestSign(t *testing.T) {
key, _ := HexToECDSA(testPrivHex)
addr := common.HexToAddress(testAddrHex)
msg := Keccak256([]byte("foo"))
sig, err := Sign(msg, key)
if err != nil {
t.Errorf("Sign error: %s", err)
}
recoveredPub, err := Ecrecover(msg, sig)
if err != nil {
t.Errorf("ECRecover error: %s", err)
}
pubKey, _ := UnmarshalPubkey(recoveredPub)
recoveredAddr := PubkeyToAddress(*pubKey)
if addr != recoveredAddr {
t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr)
}
// should be equal to SigToPub
recoveredPub2, err := SigToPub(msg, sig)
if err != nil |
recoveredAddr2 := PubkeyToAddress(*recoveredPub2)
if addr != recoveredAddr2 {
t.Errorf("Address mismatch: want: %x have: %x", addr, recoveredAddr2)
}
}
func TestInvalidSign(t *testing.T) {
if _, err := Sign(make([]byte, 1), nil); err == nil {
t.Errorf("expected sign with hash 1 byte to error")
}
if _, err := Sign(make([]byte, 33), nil); err == nil {
t.Errorf("expected sign with hash 33 byte to error")
}
}
func TestNewContractAddress(t *testing.T) {
key, _ := HexToECDSA(testPrivHex)
addr := common.HexToAddress(testAddrHex)
genAddr := PubkeyToAddress(key.PublicKey)
// sanity check before using addr to create contract address
checkAddr(t, genAddr, addr)
caddr0 := CreateAddress(addr, 0)
caddr1 := CreateAddress(addr, 1)
caddr2 := CreateAddress(addr, 2)
checkAddr(t, common.HexToAddress("333c3310824b7c685133f2bedb2ca4b8b4df633d"), caddr0)
checkAddr(t, common.HexToAddress("8bda78331c916a08481428e4b07c96d3e916d165"), caddr1)
checkAddr(t, common.HexToAddress("c9ddedf451bc62ce88bf9292afb13df35b670699"), caddr2)
}
func TestLoadECDSA(t *testing.T) {
tests := []struct {
input string
err string
}{
// good
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"},
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n"},
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\r\n"},
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n"},
{input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\r"},
// bad
{
input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde",
err: "key file too short, want 64 hex characters",
},
{
input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcde\n",
err: "key file too short, want 64 hex characters",
},
{
input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeX",
err: "invalid hex character 'X' in private key",
},
{
input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefX",
err: "invalid character 'X' at end of key file",
},
{
input: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\n\n\n",
err: "key file too long, want 64 hex characters",
},
}
for _, test := range tests {
f, err := ioutil.TempFile("", "loadecdsa_test.*.txt")
if err != nil {
t.Fatal(err)
}
filename := f.Name()
f.WriteString(test.input)
f.Close()
_, err = LoadECDSA(filename)
switch {
case err != nil && test.err == "":
t.Fatalf("unexpected error for input %q:\n %v", test.input, err)
case err != nil && err.Error() != test.err:
t.Fatalf("wrong error for input %q:\n %v", test.input, err)
case err == nil && test.err != "":
t.Fatalf("LoadECDSA did not return error for input %q", test.input)
}
}
}
func TestSaveECDSA(t *testing.T) {
f, err := ioutil.TempFile("", "saveecdsa_test.*.txt")
if err != nil {
t.Fatal(err)
}
file := f.Name()
f.Close()
defer os.Remove(file)
key, _ := HexToECDSA(testPrivHex)
if err := SaveECDSA(file, key); err != nil {
t.Fatal(err)
}
loaded, err := LoadECDSA(file)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(key, loaded) {
t.Fatal("loaded key not equal to saved key")
}
}
func TestValidateSignatureValues(t *testing.T) {
check := func(expected bool, v byte, r, s *big.Int) {
if ValidateSignatureValues(v, r, s, false) != expected {
t.Errorf("mismatch for v: %d r: %d s: %d want: %v", v, r, s, expected)
}
}
minusOne := big.NewInt(-1)
one := common.Big1
zero := common.Big0
secp256k1nMinus1 := new(big.Int).Sub(secp256k1N, common.Big1)
// correct v,r,s
check(true, 0, one, one)
check(true, 1, one, one)
// incorrect v, correct r,s,
check(false, 2, one, one)
check(false, 3, one, one)
// incorrect v, combinations of incorrect/correct r,s at lower limit
check(false, 2, zero, zero)
check(false, 2, zero, one)
check(false, 2, one, zero)
check(false, 2, one, one)
// correct v for any combination of incorrect r,s
check(false, 0, zero, zero)
check(false, 0, zero, one)
check(false, 0, one, zero)
check(false, 1, zero, zero)
check(false, 1, zero, one)
check(false, 1, one, zero)
// correct sig with max r,s
check(true, 0, secp256k1nMinus1, secp256k1nMinus1)
// correct v, combinations of incorrect r,s at upper limit
check(false, 0, secp256k1N, secp256k1nMinus1)
check(false, 0, secp256k1nMinus1, secp256k1N)
check(false, 0, secp256k1N, secp256k1N)
// current callers ensures r,s cannot be negative, but let's test for that too
// as crypto package could be used stand-alone
check(false, 0, minusOne, one)
check(false, 0, one, minusOne)
}
func checkhash(t *testing.T, name string, f func([]byte) []byte, msg, exp []byte) {
sum := f(msg)
if !bytes.Equal(exp, sum) {
t.Fatalf("hash %s mismatch: want: %x have: %x", name, exp, sum)
}
}
func checkAddr(t *testing.T, addr0, addr1 common.Address) {
if addr0 != addr1 {
t.Fatalf("address mismatch: want: %x have: %x", addr0, addr1)
}
}
// test to help Python team with integration of libsecp256k1
// skip but keep it after they are done
func TestPythonIntegration(t *testing.T) {
kh := "289c2857d4598e37fb9647507e47a309d6133539bf21a8b9cb6df88fd5232032"
k0, _ := HexToECDSA(kh)
msg0 := Keccak256([]byte("foo"))
sig0, _ := Sign(msg0, k0)
msg1 := common.FromHex("00000000000000000000000000000000")
sig1, _ := Sign(msg0, k0)
t.Logf("msg: %x, privkey: %s sig: %x\n", msg0, kh, sig0)
t.Logf("msg: %x, privkey: %s sig: %x\n", msg1, kh, sig1)
}
| {
t.Errorf("ECRecover error: %s", err)
} |
discord.rs | use std::collections::HashMap;
use std::sync::Arc;
use futures::{pin_mut, StreamExt};
use log::{error, info};
use serenity::{
client::{Cache, Context, EventHandler},
http::Http,
model::prelude::*,
utils::MessageBuilder,
};
use tokio::{sync::mpsc, task::JoinHandle};
use crate::{
clients::AgentApiClient,
error::{Error, Result},
events::{broker::EventBroker, TopicName, CHAT_TOPIC_NAME, JOIN_TOPIC_NAME, LEAVE_TOPIC_NAME},
};
pub struct DiscordClient {
alert_tx: Option<mpsc::UnboundedSender<String>>,
alert_channel_http: Option<Http>,
alert_channel_id: Option<u64>,
cache: Arc<Cache>,
_jh: JoinHandle<()>,
}
impl DiscordClient {
pub async fn new(
bot_token: String,
alert_channel_id: Option<u64>,
chat_link_channel_id: Option<u64>,
agent_client: Arc<AgentApiClient>,
event_broker: Arc<EventBroker>,
) -> Result<DiscordClient> {
let cache = Arc::new(Cache::new());
let mut client_builder = serenity::Client::builder(&bot_token);
if let Some(chat_link_channel_id) = chat_link_channel_id {
let d2g = DiscordToGameChatLinkHandler {
agent_client,
listen_channel_id: chat_link_channel_id,
};
client_builder = client_builder.event_handler(d2g);
} else {
info!("Discord chat link channel id not provided, chat link functionality will be disabled");
}
let mut client = client_builder.await?;
let jh = tokio::spawn(async move {
if let Err(e) = client.start().await |
});
if let Some(chat_link_channel_id) = chat_link_channel_id {
let bot_token_clone = bot_token.clone();
let (chat_link_tx, mut rx) = mpsc::unbounded_channel();
tokio::spawn(async move {
let http = Http::new_with_token(&bot_token_clone);
let channel = ChannelId(chat_link_channel_id);
while let Some(line) = rx.recv().await {
if let Err(e) = channel.say(&http, line).await {
error!("Couldn't send message to Discord: {:?}", e);
}
}
});
DiscordClient::create_chat_link_g2d_subscriber(chat_link_tx.clone(), event_broker)
.await;
}
let alert_tx;
let alert_channel_http;
if let Some(alert_channel_id) = alert_channel_id {
let bot_token_clone = bot_token.clone();
let (alert_tx_inner, mut rx) = mpsc::unbounded_channel();
alert_tx = Some(alert_tx_inner);
alert_channel_http = Some(Http::new_with_token(&bot_token_clone));
tokio::spawn(async move {
let http = Http::new_with_token(&bot_token_clone);
let channel = ChannelId(alert_channel_id);
while let Some(message) = rx.recv().await {
if let Err(e) = channel.say(&http, message).await {
error!("Couldn't send message to Discord: {:?}", e);
}
}
});
} else {
alert_tx = None;
alert_channel_http = None;
}
Ok(DiscordClient {
alert_tx,
alert_channel_http,
alert_channel_id,
cache,
_jh: jh,
})
}
/// Returns a mapping from snowflake id to username#discriminator
pub async fn get_user_list(&self) -> Result<HashMap<String, String>> {
if let Some(http) = &self.alert_channel_http {
let channel = ChannelId(self.alert_channel_id.unwrap());
let ch = channel.to_channel((&self.cache, http)).await?;
match ch.guild() {
Some(g) => {
let members = http.get_guild_members(g.guild_id.0, None, None).await?;
let not_bots = members.into_iter().filter(|m| !m.user.bot);
Ok(not_bots
.map(|m| {
(
m.user.id.to_string(),
format!("{}#{:04}", m.user.name, m.user.discriminator),
)
})
.collect())
}
None => {
error!("Only guild channels are supported for alerting");
Err(Error::Misconfiguration("Discord alerting is enabled, but a non-guild channel id was specified which is unsupported".to_owned()))
}
}
} else {
Err(Error::DiscordAlertingDisabled)
}
}
pub fn oneshot_alert(&self, target_id: Option<String>, alert_msg: String) -> Result<()> {
let mut mb = MessageBuilder::new();
mb.push("**ALERT**");
if let Some(target_id) = target_id {
match target_id.parse() {
Ok(target_id) => {
if let Some(tx) = &self.alert_tx {
let message = mb
.push(" for ")
.mention(&UserId(target_id))
.push(": ")
.push(alert_msg)
.build();
if let Err(e) = tx.send(message) {
error!("Error sending alert line through mpsc channel: {:?}", e);
Err(Error::InternalMessaging("Failed to send alert".to_owned()))
} else {
Ok(())
}
} else {
Err(Error::DiscordAlertingDisabled)
}
}
Err(_) => {
error!("Invalid target id");
Err(Error::BadRequest("Invalid target id".to_owned()))
}
}
} else {
if let Some(tx) = &self.alert_tx {
let message = mb.push(": ").push(alert_msg).build();
if let Err(e) = tx.send(message) {
error!("Error sending alert line through mpsc channel: {:?}", e);
Err(Error::InternalMessaging("Failed to send alert".to_owned()))
} else {
Ok(())
}
} else {
Err(Error::DiscordAlertingDisabled)
}
}
}
async fn create_chat_link_g2d_subscriber(
send_msg_tx: mpsc::UnboundedSender<String>,
event_broker: Arc<EventBroker>,
) {
let chat_tx = send_msg_tx.clone();
let join_tx = send_msg_tx.clone();
let leave_tx = send_msg_tx;
let chat_sub = event_broker
.subscribe(TopicName(CHAT_TOPIC_NAME.to_string()), |_| true)
.await;
tokio::spawn(async move {
pin_mut!(chat_sub);
while let Some(event) = chat_sub.next().await {
let message = event
.tags
.get(&TopicName(CHAT_TOPIC_NAME.to_string()))
.unwrap();
if let Err(e) = chat_tx.send(message.clone()) {
error!("Error sending line through mpsc channel: {:?}", e);
break;
}
}
error!("Discord chat link g2d chat subscriber is finishing, this should never happen!");
});
let join_sub = event_broker
.subscribe(TopicName(JOIN_TOPIC_NAME.to_string()), |_| true)
.await;
tokio::spawn(async move {
pin_mut!(join_sub);
while let Some(event) = join_sub.next().await {
let user = event
.tags
.get(&TopicName(JOIN_TOPIC_NAME.to_string()))
.unwrap();
let message = format!("**{} has joined the server**", user);
if let Err(e) = join_tx.send(message) {
error!("Error sending line through mpsc channel: {:?}", e);
break;
}
}
error!("Discord chat link g2d join subscriber is finishing, this should never happen!");
});
let leave_sub = event_broker
.subscribe(TopicName(LEAVE_TOPIC_NAME.to_string()), |_| true)
.await;
tokio::spawn(async move {
pin_mut!(leave_sub);
while let Some(event) = leave_sub.next().await {
let user = event
.tags
.get(&TopicName(LEAVE_TOPIC_NAME.to_string()))
.unwrap();
let message = format!("**{} has left the server**", user);
if let Err(e) = leave_tx.send(message) {
error!("Error sending line through mpsc channel: {:?}", e);
break;
}
}
error!(
"Discord chat link g2d leave subscriber is finishing, this should never happen!"
);
});
}
}
struct DiscordToGameChatLinkHandler {
agent_client: Arc<AgentApiClient>,
listen_channel_id: u64,
}
#[serenity::async_trait]
impl EventHandler for DiscordToGameChatLinkHandler {
async fn message(&self, _ctx: Context, msg: Message) {
if msg.channel_id == self.listen_channel_id && !msg.author.bot {
// TODO handle empty messages with embeds, attachments, etc
let message_text = format!("{}: {}", msg.author.name, msg.content);
let message_text = message_text.replace('\\', "\\\\");
let message_text = message_text.replace('\'', "\\'");
let command = format!("/silent-command game.print('[Discord] {}')", message_text);
if let Err(e) = self.agent_client.rcon_command(command).await {
error!(
"Couldn't send message via agent_client rcon_command: {:?}",
e
);
}
}
}
async fn ready(&self, _ctx: Context, _ready: Ready) {
info!("DiscordToGameChatLinkHandler ready");
}
}
| {
error!("Error with Discord client: {:?}", e);
} |
routes.tsx | import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Navbar from './components/Navbar';
import Home from './pages/HomePage';
import Services from './pages/Services';
import Products from './pages/Products';
import SignUp from './pages/SignUp';
import Footer from './pages/Footer'
import Occurrences from './pages/Occurrences'
function | () {
return (
<Router>
<Navbar />
<Switch>
<Route path='/' exact component={Home} />
<Route path='/services' component={Services} />
<Route path='/products' component={Products} />
<Route path='/sign-up' component={SignUp} />
<Route path='/occurrences' component={Occurrences} />
</Switch>
<Footer />
</Router>
)
}
export default Routes;
| Routes |
ctagtb.js | const dbConfig = require('./pg_conf');
var knex = require('knex')(dbConfig);
Bookshelf = require('bookshelf')(knex);
Bookshelf.knex.schema.createTable('apkcontent_tags', function (table) {
table.increments('id'); | })
.then(function () {
console.log('table created');
process.exit();
}); | table.integer('apkcontent_id').unsigned().references('apkcontent.id');
table.integer('tag_id').unsigned().references('tags.id');
table.comment('apk-TAG联表'); |
colored.py | """
# Copyright 2022 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the | # License for the specific language governing permissions and limitations
# under the License.
"""
import logging
from overrides import overrides
from cibyl.models.ci.base.system import JobsSystem
from cibyl.models.ci.zuul.system import ZuulSystem
from cibyl.outputs.cli.ci.env.printer import CIPrinter
from cibyl.outputs.cli.ci.system.impls.base.colored import \
ColoredBaseSystemPrinter
from cibyl.outputs.cli.ci.system.impls.jobs.colored import \
ColoredJobsSystemPrinter
from cibyl.outputs.cli.ci.system.impls.zuul.colored import \
ColoredZuulSystemPrinter
from cibyl.outputs.cli.printer import ColoredPrinter
from cibyl.utils.strings import IndentedTextBuilder
LOG = logging.getLogger(__name__)
class CIColoredPrinter(ColoredPrinter, CIPrinter):
"""Prints a whole CI model hierarchy decorating the output with colors
for easier read.
"""
@overrides
def print_environment(self, env):
printer = IndentedTextBuilder()
printer.add(self._palette.blue('Environment: '), 0)
printer[0].append(env.name.value)
for system in env.systems:
printer.add(self.print_system(system), 1)
return printer.build()
def print_system(self, system):
"""
:param system: The system.
:type system: :class:`cibyl.models.ci.base.system.System`
:return: Textual representation of the system.
:rtype: str
"""
def get_printer():
# Check specialized printers
if isinstance(system, ZuulSystem):
return ColoredZuulSystemPrinter(
self.query, self.verbosity, self.palette
)
if isinstance(system, JobsSystem):
return ColoredJobsSystemPrinter(
self.query, self.verbosity, self.palette
)
LOG.warning(
'Custom printer not found for system of type: %s. '
'Continuing with default printer...',
type(system)
)
# Go with the default printer
return ColoredBaseSystemPrinter(
self.query, self.verbosity, self.palette
)
return get_printer().print_system(system) | |
encoding.rs | use std::{
convert::TryFrom,
io::{self, Read},
};
use byteorder::ReadBytesExt;
use crate::{data_container::compression_header::Encoding, reader::num::read_itf8};
pub fn read_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let raw_kind = read_itf8(reader)?;
match raw_kind {
0 => Ok(Encoding::Null),
1 => read_external_encoding(reader),
2 => unimplemented!("GOLOMB"),
3 => read_huffman_encoding(reader),
4 => read_byte_array_len_encoding(reader),
5 => read_byte_array_stop_encoding(reader),
6 => read_beta_encoding(reader),
7 => read_subexp_encoding(reader),
8 => unimplemented!("GOLOMB_RICE"),
9 => read_gamma_encoding(reader),
_ => Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid encoding kind",
)),
}
}
fn read_args<R>(reader: &mut R) -> io::Result<Vec<u8>>
where
R: Read,
{
let len = read_itf8(reader).and_then(|n| {
usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
})?;
let mut buf = vec![0; len];
reader.read_exact(&mut buf)?;
Ok(buf)
}
fn read_external_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let block_content_id = read_itf8(&mut args_reader)?;
Ok(Encoding::External(block_content_id))
}
fn read_byte_array_len_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let len_encoding = read_encoding(&mut args_reader)?;
let value_encoding = read_encoding(&mut args_reader)?;
Ok(Encoding::ByteArrayLen(
Box::new(len_encoding),
Box::new(value_encoding),
))
}
fn read_byte_array_stop_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let stop_byte = args_reader.read_u8()?;
let block_content_id = read_itf8(&mut args_reader)?;
Ok(Encoding::ByteArrayStop(stop_byte, block_content_id))
}
fn read_huffman_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..]; | })?;
let mut alphabet = Vec::with_capacity(alphabet_len);
for _ in 0..alphabet_len {
let symbol = read_itf8(&mut args_reader)?;
alphabet.push(symbol);
}
let bit_lens_len = read_itf8(&mut args_reader).and_then(|n| {
usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
})?;
let mut bit_lens = Vec::with_capacity(bit_lens_len);
for _ in 0..bit_lens_len {
let len = read_itf8(&mut args_reader).and_then(|n| {
u32::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
})?;
bit_lens.push(len);
}
Ok(Encoding::Huffman(alphabet, bit_lens))
}
fn read_beta_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let offset = read_itf8(&mut args_reader)?;
let len = read_itf8(&mut args_reader).and_then(|n| {
u32::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
})?;
Ok(Encoding::Beta(offset, len))
}
fn read_subexp_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let offset = read_itf8(&mut args_reader)?;
let k = read_itf8(&mut args_reader)?;
Ok(Encoding::Subexp(offset, k))
}
fn read_gamma_encoding<R>(reader: &mut R) -> io::Result<Encoding>
where
R: Read,
{
let args = read_args(reader)?;
let mut args_reader = &args[..];
let offset = read_itf8(&mut args_reader)?;
Ok(Encoding::Gamma(offset))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_read_null_encoding() -> io::Result<()> {
let data = [
0, // null encoding ID
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::Null);
Ok(())
}
#[test]
fn test_read_external_encoding() -> io::Result<()> {
let data = [
1, // external encoding ID
1, // args.len
5, // block content ID
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::External(5));
Ok(())
}
#[test]
fn test_read_huffman_encoding() -> io::Result<()> {
let data = [
3, // Huffman encoding ID
4, // args.len
1, // alphabet.len
65, // 'A'
1, // bit_lens.len
0, // 0
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::Huffman(vec![65], vec![0]));
Ok(())
}
#[test]
fn test_read_byte_array_len_encoding() -> io::Result<()> {
let data = [
4, // byte array len encoding ID
6, // args.len
1, // external encoding ID
1, // args.len
13, // block content ID
1, // external encoding ID
1, // args.len
21, // block content ID
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(
encoding,
Encoding::ByteArrayLen(
Box::new(Encoding::External(13)),
Box::new(Encoding::External(21))
)
);
Ok(())
}
#[test]
fn test_read_byte_array_stop_encoding() -> io::Result<()> {
let data = [
5, // byte array stop encoding ID
2, // args.len
0, // NUL
8, // block content ID
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::ByteArrayStop(0x00, 8));
Ok(())
}
#[test]
fn test_read_beta_encoding() -> io::Result<()> {
let data = [
6, // Beta encoding ID
2, // args.len
0, // offset
8, // len
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::Beta(0, 8));
Ok(())
}
#[test]
fn test_read_subexp_encoding() -> io::Result<()> {
let data = [
7, // subexponential encoding ID
2, // args.len
0, // offset
1, // k
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::Subexp(0, 1));
Ok(())
}
#[test]
fn test_read_gamma_encoding() -> io::Result<()> {
let data = [
9, // Elias gamma encoding ID
1, // args.len
1, // offset
];
let mut reader = &data[..];
let encoding = read_encoding(&mut reader)?;
assert_eq!(encoding, Encoding::Gamma(1));
Ok(())
}
} |
let alphabet_len = read_itf8(&mut args_reader).and_then(|n| {
usize::try_from(n).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) |
build-go.py | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Build go.html
# ----------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python modules
import sys
import os
# Third-party modules
from sphinx.util.inventory import InventoryFile
JS = """
function redirect(rmap) {
var href = window.location.href;
var label = href.split('#')[1];
var base = href.substr(0, href.indexOf("go.html"))
window.location = base + rmap[label];
}
"""
def | (path):
r = [
"<html>",
"<head>",
"<title>NOC go</title>",
"</head>",
"<body>",
"<script>",
JS,
"redirect({",
]
with open(path) as f:
data = InventoryFile.load(f, "", os.path.join) or {}
rr = []
for entry, einfo in sorted(data["std:label"].items()):
rr += ["'%s': '%s'" % (entry, einfo[2])]
r += [",".join(rr), "});", "</script>", "</body>", "</html>"]
base = os.path.dirname(path)
go_path = os.path.join(base, "go.html")
with open(go_path, "w") as f:
f.write("".join(r))
if __name__ == "__main__":
process(sys.argv[1])
| process |
tl_account_update_username_gen.go | // Code generated by gotdgen, DO NOT EDIT.
package tg
import (
"context"
"errors"
"fmt"
"sort"
"strings"
"go.uber.org/multierr"
"github.com/gotd/td/bin"
"github.com/gotd/td/tdjson"
"github.com/gotd/td/tdp"
"github.com/gotd/td/tgerr"
)
// No-op definition for keeping imports.
var (
_ = bin.Buffer{}
_ = context.Background()
_ = fmt.Stringer(nil)
_ = strings.Builder{}
_ = errors.Is
_ = multierr.AppendInto
_ = sort.Ints
_ = tdp.Format
_ = tgerr.Error{}
_ = tdjson.Encoder{}
)
// AccountUpdateUsernameRequest represents TL type `account.updateUsername#3e0bdd7c`.
// Changes username for the current user.
//
// See https://core.telegram.org/method/account.updateUsername for reference.
type AccountUpdateUsernameRequest struct {
// username or empty string if username is to be removedAccepted characters: a-z
// (case-insensitive), 0-9 and underscores.Length: 5-32 characters.
Username string
}
// AccountUpdateUsernameRequestTypeID is TL type id of AccountUpdateUsernameRequest.
const AccountUpdateUsernameRequestTypeID = 0x3e0bdd7c
// Ensuring interfaces in compile-time for AccountUpdateUsernameRequest.
var (
_ bin.Encoder = &AccountUpdateUsernameRequest{}
_ bin.Decoder = &AccountUpdateUsernameRequest{}
_ bin.BareEncoder = &AccountUpdateUsernameRequest{}
_ bin.BareDecoder = &AccountUpdateUsernameRequest{}
)
func (u *AccountUpdateUsernameRequest) Zero() bool {
if u == nil |
if !(u.Username == "") {
return false
}
return true
}
// String implements fmt.Stringer.
func (u *AccountUpdateUsernameRequest) String() string {
if u == nil {
return "AccountUpdateUsernameRequest(nil)"
}
type Alias AccountUpdateUsernameRequest
return fmt.Sprintf("AccountUpdateUsernameRequest%+v", Alias(*u))
}
// FillFrom fills AccountUpdateUsernameRequest from given interface.
func (u *AccountUpdateUsernameRequest) FillFrom(from interface {
GetUsername() (value string)
}) {
u.Username = from.GetUsername()
}
// TypeID returns type id in TL schema.
//
// See https://core.telegram.org/mtproto/TL-tl#remarks.
func (*AccountUpdateUsernameRequest) TypeID() uint32 {
return AccountUpdateUsernameRequestTypeID
}
// TypeName returns name of type in TL schema.
func (*AccountUpdateUsernameRequest) TypeName() string {
return "account.updateUsername"
}
// TypeInfo returns info about TL type.
func (u *AccountUpdateUsernameRequest) TypeInfo() tdp.Type {
typ := tdp.Type{
Name: "account.updateUsername",
ID: AccountUpdateUsernameRequestTypeID,
}
if u == nil {
typ.Null = true
return typ
}
typ.Fields = []tdp.Field{
{
Name: "Username",
SchemaName: "username",
},
}
return typ
}
// Encode implements bin.Encoder.
func (u *AccountUpdateUsernameRequest) Encode(b *bin.Buffer) error {
if u == nil {
return fmt.Errorf("can't encode account.updateUsername#3e0bdd7c as nil")
}
b.PutID(AccountUpdateUsernameRequestTypeID)
return u.EncodeBare(b)
}
// EncodeBare implements bin.BareEncoder.
func (u *AccountUpdateUsernameRequest) EncodeBare(b *bin.Buffer) error {
if u == nil {
return fmt.Errorf("can't encode account.updateUsername#3e0bdd7c as nil")
}
b.PutString(u.Username)
return nil
}
// Decode implements bin.Decoder.
func (u *AccountUpdateUsernameRequest) Decode(b *bin.Buffer) error {
if u == nil {
return fmt.Errorf("can't decode account.updateUsername#3e0bdd7c to nil")
}
if err := b.ConsumeID(AccountUpdateUsernameRequestTypeID); err != nil {
return fmt.Errorf("unable to decode account.updateUsername#3e0bdd7c: %w", err)
}
return u.DecodeBare(b)
}
// DecodeBare implements bin.BareDecoder.
func (u *AccountUpdateUsernameRequest) DecodeBare(b *bin.Buffer) error {
if u == nil {
return fmt.Errorf("can't decode account.updateUsername#3e0bdd7c to nil")
}
{
value, err := b.String()
if err != nil {
return fmt.Errorf("unable to decode account.updateUsername#3e0bdd7c: field username: %w", err)
}
u.Username = value
}
return nil
}
// GetUsername returns value of Username field.
func (u *AccountUpdateUsernameRequest) GetUsername() (value string) {
return u.Username
}
// AccountUpdateUsername invokes method account.updateUsername#3e0bdd7c returning error if any.
// Changes username for the current user.
//
// Possible errors:
// 401 AUTH_KEY_PERM_EMPTY: The temporary auth key must be binded to the permanent auth key to use these methods.
// 400 USERNAME_INVALID: Unacceptable username.
// 400 USERNAME_NOT_MODIFIED: Username is not different from the current username.
// 400 USERNAME_OCCUPIED: Username is taken.
//
// See https://core.telegram.org/method/account.updateUsername for reference.
func (c *Client) AccountUpdateUsername(ctx context.Context, username string) (UserClass, error) {
var result UserBox
request := &AccountUpdateUsernameRequest{
Username: username,
}
if err := c.rpc.Invoke(ctx, request, &result); err != nil {
return nil, err
}
return result.User, nil
}
| {
return true
} |
generate_notices_report_for_project_version.py | '''
Created on Dec 19, 2018
@author: gsnyder
Generate notices report for a given project-version
'''
from blackduck.HubRestApi import HubInstance
import argparse
import json
import logging
import sys
import time
import zipfile
parser = argparse.ArgumentParser("A program to generate the notices file for a given project-version")
parser.add_argument("project_name")
parser.add_argument("version_name")
# TODO: Add the copyright checkbox option
parser.add_argument('-f', "--file_name_base", default="notices_report", help="Base file name to write the report data into. If the report format is TEXT a .zip file will be created, otherwise a .json file")
parser.add_argument('-r', '--report_format', default='TEXT', choices=["JSON", "TEXT"], help="Report format - choices are TEXT or HTML")
parser.add_argument('-c', '--include_copyright_info', action='store_true', help="Set this option to have additional copyright information from the Black Duck KB included in the notices file report.")
args = parser.parse_args()
hub = HubInstance()
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', stream=sys.stderr, level=logging.DEBUG)
class FailedReportDownload(Exception):
pass
def | (location, file_name_base, retries=10):
report_id = location.split("/")[-1]
if retries:
logging.debug("Retrieving generated report from {}".format(location))
# response = hub.download_report(report_id)
response, report_format = hub.download_notification_report(location)
if response.status_code == 200:
if report_format == "TEXT":
filename = file_name_base + ".zip"
with open(filename, "wb") as f:
f.write(response.content)
else:
# JSON format
filename = file_name_base + ".json"
with open(filename, "w") as f:
json.dump(response.json(), f, indent=3)
logging.info("Successfully downloaded json file to {} for report {}".format(
filename, report_id))
else:
logging.warning("Failed to retrieve report {}".format(report_id))
logging.warning("Probably not ready yet, waiting 5 seconds then retrying (remaining retries={}".format(retries))
time.sleep(5)
retries -= 1
download_report(location, file_name_base, retries)
else:
raise FailedReportDownload("Failed to retrieve report {} after multiple retries".format(report_id))
project = hub.get_project_by_name(args.project_name)
if project:
version = hub.get_version_by_name(project, args.version_name)
response = hub.create_version_notices_report(version, args.report_format, include_copyright_info=args.include_copyright_info)
if response.status_code == 201:
logging.info("Successfully created notices report in {} format for project {} and version {}".format(
args.report_format, args.project_name, args.version_name))
location = response.headers['Location']
download_report(location, args.file_name_base)
# Showing how you can interact with the downloaded zip and where to find the
# output content. Uncomment the lines below to see how it works.
# with zipfile.ZipFile(zip_file_name_base, 'r') as zipf:
# with zipf.open("{}/{}/version-license.txt".format(args.project_name, args.version_name), "r") as license_file:
# print(license_file.read())
else:
logging.error("Failed to create reports for project {} version {}, status code returned {}".format(
args.project_name, args.version_name, response.status_code))
else:
logging.warning("Did not find project with name {}".format(args.project_name)) | download_report |
section_0919.rs | //! @* \[42] Hyphenation.
//! When a word |hc[1..hn]| has been set up to contain a candidate for hyphenation,
//! \TeX\ first looks to see if it is in the user's exception dictionary. If not,
//! hyphens are inserted based on patterns that appear within the given word,
//! using an algorithm due to Frank~M. Liang. | //! Let's consider Liang's method first, since it is much more interesting than the
//! exception-lookup routine. The algorithm begins by setting |hyf[j]| to zero
//! for all |j|, and invalid characters are inserted into |hc[0]|
//! and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
//! used to see which of a given set of patterns occurs in the word
//! |hc[0..(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
//! sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
//! |hc[(j+1)..(j+k)]|, \TeX\ will set |hyf[j+i]:=@tmax@>(hyf[j+i],@t$n_i$@>)| for
//! |0<=i<=k|. After this has been done for each pattern that occurs, a
//! discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
//! |hyf[j]| is odd, as we have already seen.
//!
//! The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
//! depends, of course, on the language whose words are being hyphenated, and
//! on the degree of hyphenation that is desired. A method for finding
//! appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
//! hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
//! 1983); \TeX\ simply starts with the patterns and works from there.
//! | //! @^Liang, Franklin Mark@>
//! |
shape.rs | // This file contains generated code. Do not edit directly.
// To regenerate this, run 'make'.
//! Bindings to the `Shape` X11 extension.
#![allow(clippy::too_many_arguments)]
#![allow(clippy::identity_op)]
#![allow(clippy::trivially_copy_pass_by_ref)]
#![allow(clippy::eq_op)]
#[allow(unused_imports)]
use std::borrow::Cow;
use std::convert::TryFrom;
#[allow(unused_imports)]
use std::convert::TryInto;
use std::io::IoSlice;
#[allow(unused_imports)]
use crate::utils::{RawFdContainer, pretty_print_bitmask, pretty_print_enum};
#[allow(unused_imports)]
use crate::x11_utils::{Request, RequestHeader, Serialize, TryParse, TryParseFd};
use crate::connection::{BufWithFds, PiecewiseBuf, RequestConnection};
#[allow(unused_imports)]
use crate::cookie::{Cookie, CookieWithFds, VoidCookie};
use crate::errors::{ConnectionError, ParseError};
use super::xproto;
/// The X11 name of the extension for QueryExtension
pub const X11_EXTENSION_NAME: &str = "SHAPE";
/// The version number of this extension that this client library supports.
///
/// This constant contains the version number of this extension that is supported
/// by this build of x11rb. For most things, it does not make sense to use this
/// information. If you need to send a `QueryVersion`, it is recommended to instead
/// send the maximum version of the extension that you need.
pub const X11_XML_VERSION: (u32, u32) = (1, 1);
pub type Op = u8;
pub type Kind = u8;
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SO(u8);
impl SO {
pub const SET: Self = Self(0);
pub const UNION: Self = Self(1);
pub const INTERSECT: Self = Self(2);
pub const SUBTRACT: Self = Self(3);
pub const INVERT: Self = Self(4);
}
impl From<SO> for u8 {
#[inline]
fn from(input: SO) -> Self {
input.0
}
}
impl From<SO> for Option<u8> {
#[inline]
fn from(input: SO) -> Self {
Some(input.0)
}
}
impl From<SO> for u16 {
#[inline]
fn from(input: SO) -> Self {
u16::from(input.0)
}
}
impl From<SO> for Option<u16> {
#[inline]
fn from(input: SO) -> Self {
Some(u16::from(input.0))
}
}
impl From<SO> for u32 {
#[inline]
fn from(input: SO) -> Self {
u32::from(input.0)
}
}
impl From<SO> for Option<u32> {
#[inline]
fn from(input: SO) -> Self {
Some(u32::from(input.0))
}
}
impl From<u8> for SO {
#[inline]
fn from(value: u8) -> Self {
Self(value)
}
}
impl std::fmt::Debug for SO {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let variants = [
(Self::SET.0.into(), "SET", "Set"),
(Self::UNION.0.into(), "UNION", "Union"),
(Self::INTERSECT.0.into(), "INTERSECT", "Intersect"),
(Self::SUBTRACT.0.into(), "SUBTRACT", "Subtract"),
(Self::INVERT.0.into(), "INVERT", "Invert"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct SK(u8);
impl SK {
pub const BOUNDING: Self = Self(0);
pub const CLIP: Self = Self(1);
pub const INPUT: Self = Self(2);
}
impl From<SK> for u8 {
#[inline]
fn from(input: SK) -> Self {
input.0
}
}
impl From<SK> for Option<u8> {
#[inline]
fn from(input: SK) -> Self {
Some(input.0)
}
}
impl From<SK> for u16 {
#[inline]
fn from(input: SK) -> Self {
u16::from(input.0)
}
}
impl From<SK> for Option<u16> {
#[inline]
fn from(input: SK) -> Self {
Some(u16::from(input.0))
}
}
impl From<SK> for u32 {
#[inline]
fn from(input: SK) -> Self {
u32::from(input.0)
}
}
impl From<SK> for Option<u32> {
#[inline]
fn from(input: SK) -> Self {
Some(u32::from(input.0))
}
}
impl From<u8> for SK {
#[inline]
fn from(value: u8) -> Self {
Self(value)
}
}
impl std::fmt::Debug for SK {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let variants = [
(Self::BOUNDING.0.into(), "BOUNDING", "Bounding"),
(Self::CLIP.0.into(), "CLIP", "Clip"),
(Self::INPUT.0.into(), "INPUT", "Input"),
];
pretty_print_enum(fmt, self.0.into(), &variants)
}
}
/// Opcode for the Notify event
pub const NOTIFY_EVENT: u8 = 0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NotifyEvent {
pub response_type: u8,
pub shape_kind: SK,
pub sequence: u16,
pub affected_window: xproto::Window,
pub extents_x: i16,
pub extents_y: i16,
pub extents_width: u16,
pub extents_height: u16,
pub server_time: xproto::Timestamp,
pub shaped: bool,
}
impl TryParse for NotifyEvent {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (shape_kind, remaining) = Kind::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (affected_window, remaining) = xproto::Window::try_parse(remaining)?;
let (extents_x, remaining) = i16::try_parse(remaining)?;
let (extents_y, remaining) = i16::try_parse(remaining)?;
let (extents_width, remaining) = u16::try_parse(remaining)?;
let (extents_height, remaining) = u16::try_parse(remaining)?;
let (server_time, remaining) = xproto::Timestamp::try_parse(remaining)?;
let (shaped, remaining) = bool::try_parse(remaining)?;
let remaining = remaining.get(11..).ok_or(ParseError::InsufficientData)?;
let shape_kind = shape_kind.into();
let result = NotifyEvent { response_type, shape_kind, sequence, affected_window, extents_x, extents_y, extents_width, extents_height, server_time, shaped };
let _ = remaining;
let remaining = initial_value.get(32..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl TryFrom<&[u8]> for NotifyEvent {
type Error = ParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(Self::try_parse(value)?.0)
}
}
impl From<&NotifyEvent> for [u8; 32] {
fn from(input: &NotifyEvent) -> Self {
let response_type_bytes = input.response_type.serialize();
let shape_kind_bytes = Kind::from(input.shape_kind).serialize();
let sequence_bytes = input.sequence.serialize();
let affected_window_bytes = input.affected_window.serialize();
let extents_x_bytes = input.extents_x.serialize();
let extents_y_bytes = input.extents_y.serialize();
let extents_width_bytes = input.extents_width.serialize();
let extents_height_bytes = input.extents_height.serialize();
let server_time_bytes = input.server_time.serialize();
let shaped_bytes = input.shaped.serialize();
[
response_type_bytes[0],
shape_kind_bytes[0],
sequence_bytes[0],
sequence_bytes[1],
affected_window_bytes[0],
affected_window_bytes[1],
affected_window_bytes[2],
affected_window_bytes[3],
extents_x_bytes[0],
extents_x_bytes[1],
extents_y_bytes[0],
extents_y_bytes[1],
extents_width_bytes[0],
extents_width_bytes[1],
extents_height_bytes[0],
extents_height_bytes[1],
server_time_bytes[0],
server_time_bytes[1],
server_time_bytes[2],
server_time_bytes[3],
shaped_bytes[0],
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
]
}
}
impl From<NotifyEvent> for [u8; 32] {
fn from(input: NotifyEvent) -> Self {
Self::from(&input)
}
}
/// Opcode for the QueryVersion request
pub const QUERY_VERSION_REQUEST: u8 = 0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryVersionRequest;
impl QueryVersionRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let mut request0 = vec![
extension_information.major_opcode,
QUERY_VERSION_REQUEST,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<Cookie<'_, Conn, QueryVersionReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_with_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_VERSION_REQUEST {
return Err(ParseError::InvalidValue);
}
let _ = value;
Ok(QueryVersionRequest
)
}
}
impl Request for QueryVersionRequest {
type Reply = QueryVersionReply;
}
pub fn query_version<Conn>(conn: &Conn) -> Result<Cookie<'_, Conn, QueryVersionReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = QueryVersionRequest;
request0.send(conn)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryVersionReply {
pub sequence: u16,
pub length: u32,
pub major_version: u16,
pub minor_version: u16,
}
impl TryParse for QueryVersionReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (major_version, remaining) = u16::try_parse(remaining)?;
let (minor_version, remaining) = u16::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryVersionReply { sequence, length, major_version, minor_version };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl TryFrom<&[u8]> for QueryVersionReply {
type Error = ParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(Self::try_parse(value)?.0)
}
}
/// Opcode for the Rectangles request
pub const RECTANGLES_REQUEST: u8 = 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RectanglesRequest<'input> {
pub operation: SO,
pub destination_kind: SK,
pub ordering: xproto::ClipOrdering,
pub destination_window: xproto::Window,
pub x_offset: i16,
pub y_offset: i16,
pub rectangles: Cow<'input, [xproto::Rectangle]>,
}
impl<'input> RectanglesRequest<'input> {
/// Serialize this request into bytes for the provided connection
fn serialize<Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let operation_bytes = Op::from(self.operation).serialize();
let destination_kind_bytes = Kind::from(self.destination_kind).serialize();
let ordering_bytes = u8::from(self.ordering).serialize();
let destination_window_bytes = self.destination_window.serialize();
let x_offset_bytes = self.x_offset.serialize();
let y_offset_bytes = self.y_offset.serialize();
let mut request0 = vec![
extension_information.major_opcode,
RECTANGLES_REQUEST,
0,
0,
operation_bytes[0],
destination_kind_bytes[0],
ordering_bytes[0],
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
x_offset_bytes[0],
x_offset_bytes[1],
y_offset_bytes[0],
y_offset_bytes[1],
];
let length_so_far = length_so_far + request0.len();
let rectangles_bytes = self.rectangles.serialize();
let length_so_far = length_so_far + rectangles_bytes.len();
let padding0 = &[0; 3][..(4 - (length_so_far % 4)) % 4];
let length_so_far = length_so_far + padding0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into(), rectangles_bytes.into(), padding0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_without_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &'input [u8]) -> Result<Self, ParseError> {
if header.minor_opcode != RECTANGLES_REQUEST {
return Err(ParseError::InvalidValue);
}
let (operation, remaining) = Op::try_parse(value)?;
let operation = operation.into();
let (destination_kind, remaining) = Kind::try_parse(remaining)?;
let destination_kind = destination_kind.into();
let (ordering, remaining) = u8::try_parse(remaining)?;
let ordering = ordering.into();
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (destination_window, remaining) = xproto::Window::try_parse(remaining)?;
let (x_offset, remaining) = i16::try_parse(remaining)?;
let (y_offset, remaining) = i16::try_parse(remaining)?;
let mut remaining = remaining;
// Length is 'everything left in the input'
let mut rectangles = Vec::new();
while !remaining.is_empty() {
let (v, new_remaining) = xproto::Rectangle::try_parse(remaining)?;
remaining = new_remaining;
rectangles.push(v);
}
let _ = remaining;
Ok(RectanglesRequest {
operation,
destination_kind,
ordering,
destination_window,
x_offset,
y_offset,
rectangles: Cow::Owned(rectangles),
})
}
/// Clone all borrowed data in this RectanglesRequest.
pub fn into_owned(self) -> RectanglesRequest<'static> {
RectanglesRequest {
operation: self.operation,
destination_kind: self.destination_kind,
ordering: self.ordering,
destination_window: self.destination_window,
x_offset: self.x_offset,
y_offset: self.y_offset,
rectangles: Cow::Owned(self.rectangles.into_owned()),
}
}
}
impl<'input> Request for RectanglesRequest<'input> {
type Reply = ();
}
pub fn rectangles<'c, 'input, Conn>(conn: &'c Conn, operation: SO, destination_kind: SK, ordering: xproto::ClipOrdering, destination_window: xproto::Window, x_offset: i16, y_offset: i16, rectangles: &'input [xproto::Rectangle]) -> Result<VoidCookie<'c, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = RectanglesRequest {
operation,
destination_kind,
ordering,
destination_window,
x_offset,
y_offset,
rectangles: Cow::Borrowed(rectangles),
};
request0.send(conn)
}
/// Opcode for the Mask request
pub const MASK_REQUEST: u8 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MaskRequest {
pub operation: SO,
pub destination_kind: SK,
pub destination_window: xproto::Window,
pub x_offset: i16,
pub y_offset: i16,
pub source_bitmap: xproto::Pixmap,
}
impl MaskRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let operation_bytes = Op::from(self.operation).serialize();
let destination_kind_bytes = Kind::from(self.destination_kind).serialize();
let destination_window_bytes = self.destination_window.serialize();
let x_offset_bytes = self.x_offset.serialize();
let y_offset_bytes = self.y_offset.serialize();
let source_bitmap_bytes = self.source_bitmap.serialize();
let mut request0 = vec![
extension_information.major_opcode,
MASK_REQUEST,
0,
0,
operation_bytes[0],
destination_kind_bytes[0],
0,
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
x_offset_bytes[0],
x_offset_bytes[1],
y_offset_bytes[0],
y_offset_bytes[1],
source_bitmap_bytes[0],
source_bitmap_bytes[1],
source_bitmap_bytes[2],
source_bitmap_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_without_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != MASK_REQUEST {
return Err(ParseError::InvalidValue);
}
let (operation, remaining) = Op::try_parse(value)?;
let operation = operation.into();
let (destination_kind, remaining) = Kind::try_parse(remaining)?;
let destination_kind = destination_kind.into();
let remaining = remaining.get(2..).ok_or(ParseError::InsufficientData)?;
let (destination_window, remaining) = xproto::Window::try_parse(remaining)?;
let (x_offset, remaining) = i16::try_parse(remaining)?;
let (y_offset, remaining) = i16::try_parse(remaining)?;
let (source_bitmap, remaining) = xproto::Pixmap::try_parse(remaining)?;
let _ = remaining;
Ok(MaskRequest {
operation,
destination_kind,
destination_window,
x_offset,
y_offset,
source_bitmap,
})
}
}
impl Request for MaskRequest {
type Reply = ();
}
pub fn mask<Conn, A>(conn: &Conn, operation: SO, destination_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16, source_bitmap: A) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
A: Into<xproto::Pixmap>,
{
let source_bitmap: xproto::Pixmap = source_bitmap.into();
let request0 = MaskRequest {
operation,
destination_kind,
destination_window,
x_offset,
y_offset,
source_bitmap,
};
request0.send(conn)
}
/// Opcode for the Combine request
pub const COMBINE_REQUEST: u8 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CombineRequest {
pub operation: SO,
pub destination_kind: SK,
pub source_kind: SK,
pub destination_window: xproto::Window,
pub x_offset: i16,
pub y_offset: i16,
pub source_window: xproto::Window,
}
impl CombineRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let operation_bytes = Op::from(self.operation).serialize();
let destination_kind_bytes = Kind::from(self.destination_kind).serialize();
let source_kind_bytes = Kind::from(self.source_kind).serialize();
let destination_window_bytes = self.destination_window.serialize();
let x_offset_bytes = self.x_offset.serialize();
let y_offset_bytes = self.y_offset.serialize();
let source_window_bytes = self.source_window.serialize();
let mut request0 = vec![
extension_information.major_opcode,
COMBINE_REQUEST,
0,
0,
operation_bytes[0],
destination_kind_bytes[0],
source_kind_bytes[0],
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
x_offset_bytes[0],
x_offset_bytes[1],
y_offset_bytes[0],
y_offset_bytes[1],
source_window_bytes[0],
source_window_bytes[1],
source_window_bytes[2],
source_window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_without_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != COMBINE_REQUEST {
return Err(ParseError::InvalidValue);
}
let (operation, remaining) = Op::try_parse(value)?;
let operation = operation.into();
let (destination_kind, remaining) = Kind::try_parse(remaining)?;
let destination_kind = destination_kind.into();
let (source_kind, remaining) = Kind::try_parse(remaining)?;
let source_kind = source_kind.into();
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (destination_window, remaining) = xproto::Window::try_parse(remaining)?;
let (x_offset, remaining) = i16::try_parse(remaining)?;
let (y_offset, remaining) = i16::try_parse(remaining)?;
let (source_window, remaining) = xproto::Window::try_parse(remaining)?;
let _ = remaining;
Ok(CombineRequest {
operation,
destination_kind,
source_kind,
destination_window,
x_offset,
y_offset,
source_window,
})
}
}
impl Request for CombineRequest {
type Reply = ();
}
pub fn combine<Conn>(conn: &Conn, operation: SO, destination_kind: SK, source_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16, source_window: xproto::Window) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = CombineRequest {
operation,
destination_kind,
source_kind,
destination_window,
x_offset,
y_offset,
source_window,
};
request0.send(conn)
}
/// Opcode for the Offset request
pub const OFFSET_REQUEST: u8 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OffsetRequest {
pub destination_kind: SK,
pub destination_window: xproto::Window,
pub x_offset: i16,
pub y_offset: i16,
}
impl OffsetRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
|
pub fn send<Conn>(self, conn: &Conn) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_without_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != OFFSET_REQUEST {
return Err(ParseError::InvalidValue);
}
let (destination_kind, remaining) = Kind::try_parse(value)?;
let destination_kind = destination_kind.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let (destination_window, remaining) = xproto::Window::try_parse(remaining)?;
let (x_offset, remaining) = i16::try_parse(remaining)?;
let (y_offset, remaining) = i16::try_parse(remaining)?;
let _ = remaining;
Ok(OffsetRequest {
destination_kind,
destination_window,
x_offset,
y_offset,
})
}
}
impl Request for OffsetRequest {
type Reply = ();
}
pub fn offset<Conn>(conn: &Conn, destination_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = OffsetRequest {
destination_kind,
destination_window,
x_offset,
y_offset,
};
request0.send(conn)
}
/// Opcode for the QueryExtents request
pub const QUERY_EXTENTS_REQUEST: u8 = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryExtentsRequest {
pub destination_window: xproto::Window,
}
impl QueryExtentsRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let destination_window_bytes = self.destination_window.serialize();
let mut request0 = vec![
extension_information.major_opcode,
QUERY_EXTENTS_REQUEST,
0,
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<Cookie<'_, Conn, QueryExtentsReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_with_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != QUERY_EXTENTS_REQUEST {
return Err(ParseError::InvalidValue);
}
let (destination_window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(QueryExtentsRequest {
destination_window,
})
}
}
impl Request for QueryExtentsRequest {
type Reply = QueryExtentsReply;
}
pub fn query_extents<Conn>(conn: &Conn, destination_window: xproto::Window) -> Result<Cookie<'_, Conn, QueryExtentsReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = QueryExtentsRequest {
destination_window,
};
request0.send(conn)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryExtentsReply {
pub sequence: u16,
pub length: u32,
pub bounding_shaped: bool,
pub clip_shaped: bool,
pub bounding_shape_extents_x: i16,
pub bounding_shape_extents_y: i16,
pub bounding_shape_extents_width: u16,
pub bounding_shape_extents_height: u16,
pub clip_shape_extents_x: i16,
pub clip_shape_extents_y: i16,
pub clip_shape_extents_width: u16,
pub clip_shape_extents_height: u16,
}
impl TryParse for QueryExtentsReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let remaining = remaining.get(1..).ok_or(ParseError::InsufficientData)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (bounding_shaped, remaining) = bool::try_parse(remaining)?;
let (clip_shaped, remaining) = bool::try_parse(remaining)?;
let remaining = remaining.get(2..).ok_or(ParseError::InsufficientData)?;
let (bounding_shape_extents_x, remaining) = i16::try_parse(remaining)?;
let (bounding_shape_extents_y, remaining) = i16::try_parse(remaining)?;
let (bounding_shape_extents_width, remaining) = u16::try_parse(remaining)?;
let (bounding_shape_extents_height, remaining) = u16::try_parse(remaining)?;
let (clip_shape_extents_x, remaining) = i16::try_parse(remaining)?;
let (clip_shape_extents_y, remaining) = i16::try_parse(remaining)?;
let (clip_shape_extents_width, remaining) = u16::try_parse(remaining)?;
let (clip_shape_extents_height, remaining) = u16::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = QueryExtentsReply { sequence, length, bounding_shaped, clip_shaped, bounding_shape_extents_x, bounding_shape_extents_y, bounding_shape_extents_width, bounding_shape_extents_height, clip_shape_extents_x, clip_shape_extents_y, clip_shape_extents_width, clip_shape_extents_height };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl TryFrom<&[u8]> for QueryExtentsReply {
type Error = ParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(Self::try_parse(value)?.0)
}
}
/// Opcode for the SelectInput request
pub const SELECT_INPUT_REQUEST: u8 = 6;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectInputRequest {
pub destination_window: xproto::Window,
pub enable: bool,
}
impl SelectInputRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let destination_window_bytes = self.destination_window.serialize();
let enable_bytes = self.enable.serialize();
let mut request0 = vec![
extension_information.major_opcode,
SELECT_INPUT_REQUEST,
0,
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
enable_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_without_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != SELECT_INPUT_REQUEST {
return Err(ParseError::InvalidValue);
}
let (destination_window, remaining) = xproto::Window::try_parse(value)?;
let (enable, remaining) = bool::try_parse(remaining)?;
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(SelectInputRequest {
destination_window,
enable,
})
}
}
impl Request for SelectInputRequest {
type Reply = ();
}
pub fn select_input<Conn>(conn: &Conn, destination_window: xproto::Window, enable: bool) -> Result<VoidCookie<'_, Conn>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = SelectInputRequest {
destination_window,
enable,
};
request0.send(conn)
}
/// Opcode for the InputSelected request
pub const INPUT_SELECTED_REQUEST: u8 = 7;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InputSelectedRequest {
pub destination_window: xproto::Window,
}
impl InputSelectedRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let destination_window_bytes = self.destination_window.serialize();
let mut request0 = vec![
extension_information.major_opcode,
INPUT_SELECTED_REQUEST,
0,
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<Cookie<'_, Conn, InputSelectedReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_with_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != INPUT_SELECTED_REQUEST {
return Err(ParseError::InvalidValue);
}
let (destination_window, remaining) = xproto::Window::try_parse(value)?;
let _ = remaining;
Ok(InputSelectedRequest {
destination_window,
})
}
}
impl Request for InputSelectedRequest {
type Reply = InputSelectedReply;
}
pub fn input_selected<Conn>(conn: &Conn, destination_window: xproto::Window) -> Result<Cookie<'_, Conn, InputSelectedReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = InputSelectedRequest {
destination_window,
};
request0.send(conn)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InputSelectedReply {
pub enabled: bool,
pub sequence: u16,
pub length: u32,
}
impl TryParse for InputSelectedReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (enabled, remaining) = bool::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let result = InputSelectedReply { enabled, sequence, length };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl TryFrom<&[u8]> for InputSelectedReply {
type Error = ParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(Self::try_parse(value)?.0)
}
}
/// Opcode for the GetRectangles request
pub const GET_RECTANGLES_REQUEST: u8 = 8;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GetRectanglesRequest {
pub window: xproto::Window,
pub source_kind: SK,
}
impl GetRectanglesRequest {
/// Serialize this request into bytes for the provided connection
fn serialize<'input, Conn>(self, conn: &Conn) -> Result<BufWithFds<PiecewiseBuf<'input>>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let window_bytes = self.window.serialize();
let source_kind_bytes = Kind::from(self.source_kind).serialize();
let mut request0 = vec![
extension_information.major_opcode,
GET_RECTANGLES_REQUEST,
0,
0,
window_bytes[0],
window_bytes[1],
window_bytes[2],
window_bytes[3],
source_kind_bytes[0],
0,
0,
0,
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
}
pub fn send<Conn>(self, conn: &Conn) -> Result<Cookie<'_, Conn, GetRectanglesReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let (bytes, fds) = self.serialize(conn)?;
let slices = bytes.iter().map(|b| IoSlice::new(&*b)).collect::<Vec<_>>();
Ok(conn.send_request_with_reply(&slices, fds)?)
}
/// Parse this request given its header, its body, and any fds that go along with it
pub fn try_parse_request(header: RequestHeader, value: &[u8]) -> Result<Self, ParseError> {
if header.minor_opcode != GET_RECTANGLES_REQUEST {
return Err(ParseError::InvalidValue);
}
let (window, remaining) = xproto::Window::try_parse(value)?;
let (source_kind, remaining) = Kind::try_parse(remaining)?;
let source_kind = source_kind.into();
let remaining = remaining.get(3..).ok_or(ParseError::InsufficientData)?;
let _ = remaining;
Ok(GetRectanglesRequest {
window,
source_kind,
})
}
}
impl Request for GetRectanglesRequest {
type Reply = GetRectanglesReply;
}
pub fn get_rectangles<Conn>(conn: &Conn, window: xproto::Window, source_kind: SK) -> Result<Cookie<'_, Conn, GetRectanglesReply>, ConnectionError>
where
Conn: RequestConnection + ?Sized,
{
let request0 = GetRectanglesRequest {
window,
source_kind,
};
request0.send(conn)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GetRectanglesReply {
pub ordering: xproto::ClipOrdering,
pub sequence: u16,
pub length: u32,
pub rectangles: Vec<xproto::Rectangle>,
}
impl TryParse for GetRectanglesReply {
fn try_parse(initial_value: &[u8]) -> Result<(Self, &[u8]), ParseError> {
let remaining = initial_value;
let (response_type, remaining) = u8::try_parse(remaining)?;
let (ordering, remaining) = u8::try_parse(remaining)?;
let (sequence, remaining) = u16::try_parse(remaining)?;
let (length, remaining) = u32::try_parse(remaining)?;
let (rectangles_len, remaining) = u32::try_parse(remaining)?;
let remaining = remaining.get(20..).ok_or(ParseError::InsufficientData)?;
let (rectangles, remaining) = crate::x11_utils::parse_list::<xproto::Rectangle>(remaining, rectangles_len.try_into().or(Err(ParseError::ConversionFailed))?)?;
if response_type != 1 {
return Err(ParseError::InvalidValue);
}
let ordering = ordering.into();
let result = GetRectanglesReply { ordering, sequence, length, rectangles };
let _ = remaining;
let remaining = initial_value.get(32 + length as usize * 4..)
.ok_or(ParseError::InsufficientData)?;
Ok((result, remaining))
}
}
impl TryFrom<&[u8]> for GetRectanglesReply {
type Error = ParseError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
Ok(Self::try_parse(value)?.0)
}
}
impl GetRectanglesReply {
/// Get the value of the `rectangles_len` field.
///
/// The `rectangles_len` field is used as the length field of the `rectangles` field.
/// This function computes the field's value again based on the length of the list.
///
/// # Panics
///
/// Panics if the value cannot be represented in the target type. This
/// cannot happen with values of the struct received from the X11 server.
pub fn rectangles_len(&self) -> u32 {
self.rectangles.len()
.try_into().unwrap()
}
}
/// Extension trait defining the requests of this extension.
pub trait ConnectionExt: RequestConnection {
fn shape_query_version(&self) -> Result<Cookie<'_, Self, QueryVersionReply>, ConnectionError>
{
query_version(self)
}
fn shape_rectangles<'c, 'input>(&'c self, operation: SO, destination_kind: SK, ordering: xproto::ClipOrdering, destination_window: xproto::Window, x_offset: i16, y_offset: i16, rectangles: &'input [xproto::Rectangle]) -> Result<VoidCookie<'c, Self>, ConnectionError>
{
self::rectangles(self, operation, destination_kind, ordering, destination_window, x_offset, y_offset, rectangles)
}
fn shape_mask<A>(&self, operation: SO, destination_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16, source_bitmap: A) -> Result<VoidCookie<'_, Self>, ConnectionError>
where
A: Into<xproto::Pixmap>,
{
mask(self, operation, destination_kind, destination_window, x_offset, y_offset, source_bitmap)
}
fn shape_combine(&self, operation: SO, destination_kind: SK, source_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16, source_window: xproto::Window) -> Result<VoidCookie<'_, Self>, ConnectionError>
{
combine(self, operation, destination_kind, source_kind, destination_window, x_offset, y_offset, source_window)
}
fn shape_offset(&self, destination_kind: SK, destination_window: xproto::Window, x_offset: i16, y_offset: i16) -> Result<VoidCookie<'_, Self>, ConnectionError>
{
offset(self, destination_kind, destination_window, x_offset, y_offset)
}
fn shape_query_extents(&self, destination_window: xproto::Window) -> Result<Cookie<'_, Self, QueryExtentsReply>, ConnectionError>
{
query_extents(self, destination_window)
}
fn shape_select_input(&self, destination_window: xproto::Window, enable: bool) -> Result<VoidCookie<'_, Self>, ConnectionError>
{
select_input(self, destination_window, enable)
}
fn shape_input_selected(&self, destination_window: xproto::Window) -> Result<Cookie<'_, Self, InputSelectedReply>, ConnectionError>
{
input_selected(self, destination_window)
}
fn shape_get_rectangles(&self, window: xproto::Window, source_kind: SK) -> Result<Cookie<'_, Self, GetRectanglesReply>, ConnectionError>
{
get_rectangles(self, window, source_kind)
}
}
impl<C: RequestConnection + ?Sized> ConnectionExt for C {}
| {
let extension_information = conn.extension_information(X11_EXTENSION_NAME)?
.ok_or(ConnectionError::UnsupportedExtension)?;
let length_so_far = 0;
let destination_kind_bytes = Kind::from(self.destination_kind).serialize();
let destination_window_bytes = self.destination_window.serialize();
let x_offset_bytes = self.x_offset.serialize();
let y_offset_bytes = self.y_offset.serialize();
let mut request0 = vec![
extension_information.major_opcode,
OFFSET_REQUEST,
0,
0,
destination_kind_bytes[0],
0,
0,
0,
destination_window_bytes[0],
destination_window_bytes[1],
destination_window_bytes[2],
destination_window_bytes[3],
x_offset_bytes[0],
x_offset_bytes[1],
y_offset_bytes[0],
y_offset_bytes[1],
];
let length_so_far = length_so_far + request0.len();
assert_eq!(length_so_far % 4, 0);
let length = u16::try_from(length_so_far / 4).unwrap_or(0);
request0[2..4].copy_from_slice(&length.to_ne_bytes());
Ok((vec![request0.into()], vec![]))
} |
BigramMatrix.ts | import { DEFAULT_BAD_SAMPLES, DEFAULT_GOOD_SAMPLES, DEFAULT_CHARS_TO_INCLUDE, UPPERCASE_CHARS } from '../utils/constants'
import { cleanAndExtractWordsFromTextToScore, getCharCodeMap, getDefaultBigramMatrixFromJSON } from '../utils/helpers'
import { createEmptyBigramMatrix, getBigramCutoffScores, runTextThroughBigramMatrix, trainBigramMatrix } from './bigramHelpers'
import { CutoffScore, CutoffScoreStrictness, NGramMatrix, NGramMatrixOptions } from '..'
import { HARRY_POTTER_TRAINING_TEXT } from '../data/harry-potter-1'
import { DEFAULT_ALPHA_SIZE, DEFAULT_CHAR_CODE_MAP } from '../utils/constants'
export interface BigramMatrixRow {
countRow: number[]
rowTotal: number
}
interface BigramMatrixInterface extends NGramMatrix {
bigramMatrix: BigramMatrixRow[]
}
export class BigramMatrix implements BigramMatrixInterface {
alphaSize: number
charsToInclude: string
bigramMatrix: BigramMatrixRow[]
cutoffScores: CutoffScore
charCodeMap: { [key: number]: number }
savedGoodSamples: string[]
savedBadSamples: string[]
ignoreCase: boolean
constructor(options?: NGramMatrixOptions) {
if (!options) {
const { bigramMatrix, cutoffScores } = getDefaultBigramMatrixFromJSON()
this.alphaSize = DEFAULT_ALPHA_SIZE
this.bigramMatrix = bigramMatrix
this.cutoffScores = cutoffScores
this.charCodeMap = DEFAULT_CHAR_CODE_MAP
this.savedGoodSamples = DEFAULT_GOOD_SAMPLES
this.savedBadSamples = DEFAULT_BAD_SAMPLES
this.ignoreCase = true
this.charsToInclude = DEFAULT_CHARS_TO_INCLUDE
return | this.alphaSize = uniqueChars
this.charsToInclude = noDuplicateCharsStr
this.bigramMatrix = createEmptyBigramMatrix(uniqueChars)
this.train(initialTrainingText)
this.cutoffScores = getBigramCutoffScores(this.bigramMatrix, goodSamples, badSamples, charCodeMap, ignoreCase)
this.savedGoodSamples = goodSamples
this.savedBadSamples = badSamples
this.ignoreCase = ignoreCase
}
train = (trainingText: string): void => {
trainBigramMatrix(this.bigramMatrix, trainingText, this.charCodeMap, this.charsToInclude, this.ignoreCase)
this.recalibrateCutoffScores(this.savedGoodSamples, this.savedBadSamples)
}
getScore = (textToScore: string): number => {
return runTextThroughBigramMatrix(this.bigramMatrix, textToScore, this.charCodeMap, this.ignoreCase)
}
getCutoffScores = (): CutoffScore => {
return this.cutoffScores
}
recalibrateCutoffScores = (goodSamples = DEFAULT_GOOD_SAMPLES, badSamples = DEFAULT_BAD_SAMPLES): void => {
this.cutoffScores = getBigramCutoffScores(this.bigramMatrix, goodSamples, badSamples, this.charCodeMap, this.ignoreCase)
}
isGibberish = (text: string, strictness = CutoffScoreStrictness.Avg): boolean => {
const { loose, avg, strict } = this.cutoffScores
const cutoff = strictness === CutoffScoreStrictness.Strict ? strict : strictness === CutoffScoreStrictness.Avg ? avg : loose
return this.getScore(text) < cutoff
}
getWordByWordAnalysis = (
text: string,
strictness?: CutoffScoreStrictness,
): {
numWords: number
numGibberishWords: number
words: { word: string; score: number }[]
gibberishWords: { word: string; score: number }[]
cutoffs: CutoffScore
} => {
const wordTokens = cleanAndExtractWordsFromTextToScore(text, this.ignoreCase)
const gibberishWords: { word: string; score: number }[] = []
const words: { word: string; score: number }[] = []
for (const wToken of wordTokens) {
const wordAndScoreBundle = { word: wToken, score: this.getScore(wToken) }
if (this.isGibberish(wToken, strictness)) gibberishWords.push(wordAndScoreBundle)
words.push(wordAndScoreBundle)
}
return { numWords: wordTokens.length, numGibberishWords: gibberishWords.length, words: words, gibberishWords: gibberishWords, cutoffs: this.cutoffScores }
}
} | }
const { initialTrainingText = HARRY_POTTER_TRAINING_TEXT, goodSamples = DEFAULT_GOOD_SAMPLES, badSamples = DEFAULT_BAD_SAMPLES, ignoreCase = true, additionalCharsToInclude = '' } = options
const { charCodeMap, uniqueChars, noDuplicateCharsStr } = getCharCodeMap(DEFAULT_CHARS_TO_INCLUDE + additionalCharsToInclude + (!ignoreCase ? UPPERCASE_CHARS : ''))
this.charCodeMap = charCodeMap |
main.go | package main
import (
"context"
"github.com/ory/kratos/examples/go/pkg"
ory "github.com/ory/kratos-client-go"
)
// If you use Open Source this would be:
//
//var client = pkg.NewSDKForSelfHosted("http://127.0.0.1:4433")
var client = pkg.NewSDK("playground")
func performVerification(email string) *ory.SelfServiceVerificationFlow |
func main() {
pkg.PrintJSONPretty(
performVerification("[email protected]"),
)
}
| {
ctx := context.Background()
// Initialize the flow
flow, res, err := client.V0alpha2Api.InitializeSelfServiceVerificationFlowWithoutBrowser(ctx).Execute()
pkg.SDKExitOnError(err, res)
// If you want, print the flow here:
//
// pkg.PrintJSONPretty(flow)
// Submit the form
afterSubmit, res, err := client.V0alpha2Api.SubmitSelfServiceVerificationFlow(ctx).Flow(flow.Id).
SubmitSelfServiceVerificationFlowBody(ory.SubmitSelfServiceVerificationFlowWithLinkMethodBodyAsSubmitSelfServiceVerificationFlowBody(&ory.SubmitSelfServiceVerificationFlowWithLinkMethodBody{
Email: email,
Method: "link",
})).Execute()
pkg.SDKExitOnError(err, res)
return afterSubmit
} |
clock_test.go | package tick
import (
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestRealClock(t *testing.T) {
clock := NewRealClock()
N := 100
threshold := time.Millisecond
for i := 0; i < N; i++ {
assert.LessOrEqual(t, time.Now().Sub(clock()), threshold)
}
}
func TestStepClock(t *testing.T) | {
now := time.Now()
step := time.Second
clock := NewStepClock(now, step)
N := 100
for i := 0; i < N; i++ {
assert.Equal(t, now, clock())
now = now.Add(step)
}
} |
|
esr.rs | #[doc = "Writer for register ESR"]
pub type W = crate::W<u32, super::ESR>;
#[doc = "Write proxy for field `P0`"]
pub struct P0_W<'a> { w: &'a mut W }
impl<'a> P0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Write proxy for field `P1`"]
pub struct P1_W<'a> { w: &'a mut W }
impl<'a> P1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Write proxy for field `P2`"]
pub struct P2_W<'a> { w: &'a mut W }
impl<'a> P2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Write proxy for field `P3`"]
pub struct P3_W<'a> { w: &'a mut W }
impl<'a> P3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Write proxy for field `P4`"]
pub struct P4_W<'a> { w: &'a mut W }
impl<'a> P4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Write proxy for field `P5`"]
pub struct P5_W<'a> { w: &'a mut W }
impl<'a> P5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Write proxy for field `P6`"]
pub struct P6_W<'a> { w: &'a mut W }
impl<'a> P6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Write proxy for field `P7`"]
pub struct P7_W<'a> { w: &'a mut W }
impl<'a> P7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Write proxy for field `P8`"]
pub struct P8_W<'a> { w: &'a mut W }
impl<'a> P8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Write proxy for field `P9`"]
pub struct P9_W<'a> { w: &'a mut W }
impl<'a> P9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Write proxy for field `P10`"]
pub struct P10_W<'a> { w: &'a mut W }
impl<'a> P10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Write proxy for field `P11`"]
pub struct P11_W<'a> { w: &'a mut W }
impl<'a> P11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Write proxy for field `P12`"]
pub struct P12_W<'a> { w: &'a mut W }
impl<'a> P12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Write proxy for field `P13`"]
pub struct P13_W<'a> { w: &'a mut W }
impl<'a> P13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Write proxy for field `P14`"]
pub struct P14_W<'a> { w: &'a mut W }
impl<'a> P14_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Write proxy for field `P15`"]
pub struct P15_W<'a> { w: &'a mut W }
impl<'a> P15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Write proxy for field `P16`"]
pub struct P16_W<'a> { w: &'a mut W }
impl<'a> P16_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Write proxy for field `P17`"]
pub struct P17_W<'a> { w: &'a mut W }
impl<'a> P17_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Write proxy for field `P18`"]
pub struct P18_W<'a> { w: &'a mut W }
impl<'a> P18_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Write proxy for field `P19`"]
pub struct P19_W<'a> { w: &'a mut W }
impl<'a> P19_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Write proxy for field `P20`"]
pub struct P20_W<'a> { w: &'a mut W }
impl<'a> P20_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Write proxy for field `P21`"]
pub struct P21_W<'a> { w: &'a mut W }
impl<'a> P21_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Write proxy for field `P22`"]
pub struct P22_W<'a> { w: &'a mut W }
impl<'a> P22_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Write proxy for field `P23`"]
pub struct P23_W<'a> { w: &'a mut W }
impl<'a> P23_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Write proxy for field `P24`"]
pub struct P24_W<'a> { w: &'a mut W }
impl<'a> P24_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Write proxy for field `P25`"]
pub struct P25_W<'a> { w: &'a mut W }
impl<'a> P25_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Write proxy for field `P26`"]
pub struct P26_W<'a> { w: &'a mut W }
impl<'a> P26_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Write proxy for field `P27`"]
pub struct P27_W<'a> { w: &'a mut W }
impl<'a> P27_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Write proxy for field `P28`"]
pub struct P28_W<'a> { w: &'a mut W }
impl<'a> P28_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Write proxy for field `P29`"]
pub struct P29_W<'a> { w: &'a mut W }
impl<'a> P29_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Write proxy for field `P30`"]
pub struct P30_W<'a> { w: &'a mut W }
impl<'a> P30_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Write proxy for field `P31`"]
pub struct P31_W<'a> { w: &'a mut W }
impl<'a> P31_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W { self.bit(true) }
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W { self.bit(false) }
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl W {
#[doc = "Bit 0 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p0(&mut self) -> P0_W { P0_W { w: self } }
#[doc = "Bit 1 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p1(&mut self) -> P1_W { P1_W { w: self } }
#[doc = "Bit 2 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p2(&mut self) -> P2_W { P2_W { w: self } }
#[doc = "Bit 3 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p3(&mut self) -> P3_W { P3_W { w: self } }
#[doc = "Bit 4 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p4(&mut self) -> P4_W { P4_W { w: self } }
#[doc = "Bit 5 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p5(&mut self) -> P5_W { P5_W { w: self } }
#[doc = "Bit 6 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p6(&mut self) -> P6_W { P6_W { w: self } }
#[doc = "Bit 7 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p7(&mut self) -> P7_W { P7_W { w: self } }
#[doc = "Bit 8 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p8(&mut self) -> P8_W { P8_W { w: self } }
#[doc = "Bit 9 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p9(&mut self) -> P9_W { P9_W { w: self } }
#[doc = "Bit 10 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p10(&mut self) -> P10_W { P10_W { w: self } }
#[doc = "Bit 11 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p11(&mut self) -> P11_W { P11_W { w: self } }
#[doc = "Bit 12 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p12(&mut self) -> P12_W { P12_W { w: self } }
#[doc = "Bit 13 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p13(&mut self) -> P13_W { P13_W { w: self } }
#[doc = "Bit 14 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p14(&mut self) -> P14_W { P14_W { w: self } }
#[doc = "Bit 15 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p15(&mut self) -> P15_W { P15_W { w: self } }
#[doc = "Bit 16 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p16(&mut self) -> P16_W { P16_W { w: self } }
#[doc = "Bit 17 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p17(&mut self) -> P17_W { P17_W { w: self } }
#[doc = "Bit 18 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p18(&mut self) -> P18_W { P18_W { w: self } }
#[doc = "Bit 19 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p19(&mut self) -> P19_W |
#[doc = "Bit 20 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p20(&mut self) -> P20_W { P20_W { w: self } }
#[doc = "Bit 21 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p21(&mut self) -> P21_W { P21_W { w: self } }
#[doc = "Bit 22 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p22(&mut self) -> P22_W { P22_W { w: self } }
#[doc = "Bit 23 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p23(&mut self) -> P23_W { P23_W { w: self } }
#[doc = "Bit 24 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p24(&mut self) -> P24_W { P24_W { w: self } }
#[doc = "Bit 25 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p25(&mut self) -> P25_W { P25_W { w: self } }
#[doc = "Bit 26 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p26(&mut self) -> P26_W { P26_W { w: self } }
#[doc = "Bit 27 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p27(&mut self) -> P27_W { P27_W { w: self } }
#[doc = "Bit 28 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p28(&mut self) -> P28_W { P28_W { w: self } }
#[doc = "Bit 29 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p29(&mut self) -> P29_W { P29_W { w: self } }
#[doc = "Bit 30 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p30(&mut self) -> P30_W { P30_W { w: self } }
#[doc = "Bit 31 - Edge Interrupt Selection."]
#[inline(always)]
pub fn p31(&mut self) -> P31_W { P31_W { w: self } }
} | { P19_W { w: self } } |
IconBook.tsx | import { createIcon } from '../_createIcon/createIcon';
import IconBookSizeAll from './IconBook_size_all';
export const IconBook = createIcon({
l: IconBookSizeAll,
m: IconBookSizeAll,
s: IconBookSizeAll,
xs: IconBookSizeAll,
name: 'IconBook', | }); |
|
test_nameerror.py | import os
import unittest
from nose.plugins import PluginTester
from nose.plugins.skip import SkipTest
from nose.plugins.multiprocess import MultiProcess
support = os.path.join(os.path.dirname(__file__), 'support')
def setup():
try:
import multiprocessing
if 'active' in MultiProcess.status:
raise SkipTest("Multiprocess plugin is active. Skipping tests of "
"plugin itself.")
except ImportError:
raise SkipTest("multiprocessing module not available")
class TestMPNameError(PluginTester, unittest.TestCase):
activate = '--processes=2'
plugins = [MultiProcess()]
suitepath = os.path.join(support, 'nameerror.py')
def | (self):
print str(self.output)
assert 'NameError' in self.output
assert "'undefined_variable' is not defined" in self.output
| runTest |
axes3d.rs | use std::marker::PhantomData;
use super::ChartContext;
use crate::coord::cartesian::Cartesian3d;
use crate::coord::ranged1d::{BoldPoints, LightPoints, Ranged, ValueFormatter};
use crate::style::colors::{BLACK, TRANSPARENT};
use crate::style::Color;
use crate::style::{AsRelative, ShapeStyle, SizeDesc, TextStyle};
use super::Coord3D;
use crate::drawing::DrawingAreaErrorKind;
use plotters_backend::DrawingBackend;
/**
Implements 3D plot axes configurations.
The best way to use this struct is by way of the [`configure_axes()`] function.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub struct Axes3dStyle<'a, 'b, X: Ranged, Y: Ranged, Z: Ranged, DB: DrawingBackend> {
pub(super) parent_size: (u32, u32),
pub(super) target: Option<&'b mut ChartContext<'a, DB, Cartesian3d<X, Y, Z>>>,
pub(super) tick_size: i32,
pub(super) light_lines_limit: [usize; 3],
pub(super) n_labels: [usize; 3],
pub(super) bold_line_style: ShapeStyle,
pub(super) light_line_style: ShapeStyle,
pub(super) axis_panel_style: ShapeStyle,
pub(super) axis_style: ShapeStyle,
pub(super) label_style: TextStyle<'b>,
pub(super) format_x: &'b dyn Fn(&X::ValueType) -> String,
pub(super) format_y: &'b dyn Fn(&Y::ValueType) -> String,
pub(super) format_z: &'b dyn Fn(&Z::ValueType) -> String,
_phantom: PhantomData<&'a (X, Y, Z)>,
}
impl<'a, 'b, X, Y, Z, XT, YT, ZT, DB> Axes3dStyle<'a, 'b, X, Y, Z, DB>
where
X: Ranged<ValueType = XT> + ValueFormatter<XT>,
Y: Ranged<ValueType = YT> + ValueFormatter<YT>,
Z: Ranged<ValueType = ZT> + ValueFormatter<ZT>,
DB: DrawingBackend,
{
/**
Set the size of the tick marks.
- `value` Desired tick mark size, in pixels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn tick_size<Size: SizeDesc>(&mut self, size: Size) -> &mut Self {
let actual_size = size.in_pixels(&self.parent_size);
self.tick_size = actual_size;
self
}
/**
Set the maximum number of divisions for the minor grid in the X axis.
- `value`: Maximum desired divisions between two consecutive X labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn x_max_light_lines(&mut self, value: usize) -> &mut Self {
self.light_lines_limit[0] = value;
self
}
/**
Set the maximum number of divisions for the minor grid in the Y axis.
- `value`: Maximum desired divisions between two consecutive Y labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn y_max_light_lines(&mut self, value: usize) -> &mut Self {
self.light_lines_limit[1] = value;
self
}
/**
Set the maximum number of divisions for the minor grid in the Z axis.
- `value`: Maximum desired divisions between two consecutive Z labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn z_max_light_lines(&mut self, value: usize) -> &mut Self {
self.light_lines_limit[2] = value;
self
}
/**
Set the maximum number of divisions for the minor grid.
- `value`: Maximum desired divisions between two consecutive labels in X, Y, and Z.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn max_light_lines(&mut self, value: usize) -> &mut Self {
self.light_lines_limit[0] = value;
self.light_lines_limit[1] = value;
self.light_lines_limit[2] = value;
self
}
/**
Set the number of labels on the X axes.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn x_labels(&mut self, n: usize) -> &mut Self {
self.n_labels[0] = n;
self
}
/**
Set the number of labels on the Y axes.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn y_labels(&mut self, n: usize) -> &mut Self {
self.n_labels[1] = n;
self
}
/**
Set the number of labels on the Z axes.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn z_labels(&mut self, n: usize) -> &mut Self {
self.n_labels[2] = n;
self
}
/**
Sets the style of the panels in the background.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn axis_panel_style<S: Into<ShapeStyle>>(&mut self, style: S) -> &mut Self {
self.axis_panel_style = style.into();
self
}
/**
Sets the style of the major grid lines.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn bold_grid_style<S: Into<ShapeStyle>>(&mut self, style: S) -> &mut Self {
self.bold_line_style = style.into();
self
}
/**
Sets the style of the minor grid lines.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn light_grid_style<S: Into<ShapeStyle>>(&mut self, style: S) -> &mut Self {
self.light_line_style = style.into();
self
}
/**
Sets the text style of the axis labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn label_style<S: Into<TextStyle<'b>>>(&mut self, style: S) -> &mut Self {
self.label_style = style.into();
self
}
/**
Specifies the string format of the X axis labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn x_formatter<F: Fn(&X::ValueType) -> String>(&mut self, f: &'b F) -> &mut Self {
self.format_x = f;
self
}
/**
Specifies the string format of the Y axis labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn y_formatter<F: Fn(&Y::ValueType) -> String>(&mut self, f: &'b F) -> &mut Self { | self
}
/**
Specifies the string format of the Z axis labels.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub fn z_formatter<F: Fn(&Z::ValueType) -> String>(&mut self, f: &'b F) -> &mut Self {
self.format_z = f;
self
}
/**
Constructs a new configuration object and defines the defaults.
This is used internally by Plotters and should probably not be included in user code.
See [`ChartContext::configure_axes()`] for more information and examples.
*/
pub(crate) fn new(chart: &'b mut ChartContext<'a, DB, Cartesian3d<X, Y, Z>>) -> Self {
let parent_size = chart.drawing_area.dim_in_pixel();
let base_tick_size = (5u32).percent().max(5).in_pixels(chart.plotting_area());
let tick_size = base_tick_size;
Self {
parent_size,
tick_size,
light_lines_limit: [10, 10, 10],
n_labels: [10, 10, 10],
bold_line_style: Into::<ShapeStyle>::into(&BLACK.mix(0.2)),
light_line_style: Into::<ShapeStyle>::into(&TRANSPARENT),
axis_panel_style: Into::<ShapeStyle>::into(&BLACK.mix(0.1)),
axis_style: Into::<ShapeStyle>::into(&BLACK.mix(0.8)),
label_style: ("sans-serif", (12).percent().max(12).in_pixels(&parent_size)).into(),
format_x: &X::format,
format_y: &Y::format,
format_z: &Z::format,
_phantom: PhantomData,
target: Some(chart),
}
}
pub fn draw(&mut self) -> Result<(), DrawingAreaErrorKind<DB::ErrorType>>
where
XT: Clone,
YT: Clone,
ZT: Clone,
{
let chart = self.target.take().unwrap();
let kps_bold = chart.get_key_points(
BoldPoints(self.n_labels[0]),
BoldPoints(self.n_labels[1]),
BoldPoints(self.n_labels[2]),
);
let kps_light = chart.get_key_points(
LightPoints::new(
self.n_labels[0],
self.n_labels[0] * self.light_lines_limit[0],
),
LightPoints::new(
self.n_labels[1],
self.n_labels[1] * self.light_lines_limit[1],
),
LightPoints::new(
self.n_labels[2],
self.n_labels[2] * self.light_lines_limit[2],
),
);
let panels = chart.draw_axis_panels(
&kps_bold,
&kps_light,
self.axis_panel_style.clone(),
self.bold_line_style.clone(),
self.light_line_style.clone(),
)?;
for i in 0..3 {
let axis = chart.draw_axis(i, &panels, self.axis_style.clone())?;
let labels: Vec<_> = match i {
0 => kps_bold
.x_points
.iter()
.map(|x| {
let x_text = (self.format_x)(x);
let mut p = axis[0].clone();
p[0] = Coord3D::X(x.clone());
(p, x_text)
})
.collect(),
1 => kps_bold
.y_points
.iter()
.map(|y| {
let y_text = (self.format_y)(y);
let mut p = axis[0].clone();
p[1] = Coord3D::Y(y.clone());
(p, y_text)
})
.collect(),
_ => kps_bold
.z_points
.iter()
.map(|z| {
let z_text = (self.format_z)(z);
let mut p = axis[0].clone();
p[2] = Coord3D::Z(z.clone());
(p, z_text)
})
.collect(),
};
chart.draw_axis_ticks(
axis,
&labels[..],
self.tick_size,
self.axis_style.clone(),
self.label_style.clone(),
)?;
}
Ok(())
}
} | self.format_y = f; |
sync.pb.go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/cshealy/sync-sandbox/proto (interfaces: TestsClient)
// Package mock_proto is a generated GoMock package.
package mock_proto
import (
context "context"
protos "github.com/cshealy/sync-sandbox/proto"
gomock "github.com/golang/mock/gomock"
grpc "google.golang.org/grpc"
emptypb "google.golang.org/protobuf/types/known/emptypb"
reflect "reflect"
)
// MockTestsClient is a mock of TestsClient interface
type MockTestsClient struct {
ctrl *gomock.Controller
recorder *MockTestsClientMockRecorder
}
// MockTestsClientMockRecorder is the mock recorder for MockTestsClient
type MockTestsClientMockRecorder struct {
mock *MockTestsClient
}
// NewMockTestsClient creates a new mock instance
func NewMockTestsClient(ctrl *gomock.Controller) *MockTestsClient |
// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockTestsClient) EXPECT() *MockTestsClientMockRecorder {
return m.recorder
}
// GetBidirectionalStream mocks base method
func (m *MockTestsClient) GetBidirectionalStream(arg0 context.Context, arg1 ...grpc.CallOption) (protos.Tests_GetBidirectionalStreamClient, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetBidirectionalStream", varargs...)
ret0, _ := ret[0].(protos.Tests_GetBidirectionalStreamClient)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetBidirectionalStream indicates an expected call of GetBidirectionalStream
func (mr *MockTestsClientMockRecorder) GetBidirectionalStream(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBidirectionalStream", reflect.TypeOf((*MockTestsClient)(nil).GetBidirectionalStream), varargs...)
}
// GetClientStream mocks base method
func (m *MockTestsClient) GetClientStream(arg0 context.Context, arg1 ...grpc.CallOption) (protos.Tests_GetClientStreamClient, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0}
for _, a := range arg1 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetClientStream", varargs...)
ret0, _ := ret[0].(protos.Tests_GetClientStreamClient)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetClientStream indicates an expected call of GetClientStream
func (mr *MockTestsClientMockRecorder) GetClientStream(arg0 interface{}, arg1 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0}, arg1...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClientStream", reflect.TypeOf((*MockTestsClient)(nil).GetClientStream), varargs...)
}
// GetSpotifyPlaylist mocks base method
func (m *MockTestsClient) GetSpotifyPlaylist(arg0 context.Context, arg1 *emptypb.Empty, arg2 ...grpc.CallOption) (*protos.SpotifyPlaylist, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetSpotifyPlaylist", varargs...)
ret0, _ := ret[0].(*protos.SpotifyPlaylist)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetSpotifyPlaylist indicates an expected call of GetSpotifyPlaylist
func (mr *MockTestsClientMockRecorder) GetSpotifyPlaylist(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpotifyPlaylist", reflect.TypeOf((*MockTestsClient)(nil).GetSpotifyPlaylist), varargs...)
}
// GetSpotifyPlaylistStream mocks base method
func (m *MockTestsClient) GetSpotifyPlaylistStream(arg0 context.Context, arg1 *emptypb.Empty, arg2 ...grpc.CallOption) (protos.Tests_GetSpotifyPlaylistStreamClient, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetSpotifyPlaylistStream", varargs...)
ret0, _ := ret[0].(protos.Tests_GetSpotifyPlaylistStreamClient)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetSpotifyPlaylistStream indicates an expected call of GetSpotifyPlaylistStream
func (mr *MockTestsClientMockRecorder) GetSpotifyPlaylistStream(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSpotifyPlaylistStream", reflect.TypeOf((*MockTestsClient)(nil).GetSpotifyPlaylistStream), varargs...)
}
// GetTest mocks base method
func (m *MockTestsClient) GetTest(arg0 context.Context, arg1 *protos.Test, arg2 ...grpc.CallOption) (*protos.Test, error) {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "GetTest", varargs...)
ret0, _ := ret[0].(*protos.Test)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetTest indicates an expected call of GetTest
func (mr *MockTestsClientMockRecorder) GetTest(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTest", reflect.TypeOf((*MockTestsClient)(nil).GetTest), varargs...)
}
| {
mock := &MockTestsClient{ctrl: ctrl}
mock.recorder = &MockTestsClientMockRecorder{mock}
return mock
} |
cloudconfig_test.go | /*
Copyright 2019 The Machine Controller Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//
// Google Cloud Provider for the Machine Controller
//
// Unit Tests
//
package types
import (
"testing"
)
func | (t *testing.T) {
tests := []struct {
name string
config *CloudConfig
contents string
}{
{
name: "minimum test",
config: &CloudConfig{
Global: GlobalOpts{
ProjectID: "my-project-id",
LocalZone: "my-zone",
NetworkName: "my-cool-network",
SubnetworkName: "my-cool-subnetwork",
TokenURL: "nil",
MultiZone: true,
Regional: true,
NodeTags: []string{"tag1", "tag2"},
},
},
contents: "[global]\n" +
"project-id = \"my-project-id\"\n" +
"local-zone = \"my-zone\"\n" +
"network-name = \"my-cool-network\"\n" +
"subnetwork-name = \"my-cool-subnetwork\"\n" +
"token-url = \"nil\"\n" +
"multizone = true\n" +
"regional = true\n" +
"node-tags = \"tag1\"\n" +
"node-tags = \"tag2\"\n",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
s, err := test.config.AsString()
if err != nil {
t.Fatalf("failed to convert to string: %v", err)
}
if s != test.contents {
t.Fatalf("output is not as expected")
}
})
}
}
| TestCloudConfigAsString |
views.py | from django.shortcuts import render, render_to_response
from django.http import Http404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from models import *
from forms import *
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from dateutil import parser
import json
# Create your views here.
def show_calendar(request, *args, **kwargs):
return render_to_response('calendar_events/show_calendar.html', context_instance=RequestContext(request))
@require_GET
def view_all_events_between(request, **kwargs):
'''
This view is for the jquery-ui fullcalendar widget. Takes a GET request with a date range and returns all events inside the range
in the JSON format that fullcalendar is expecting.
'''
startdatetime = parser.parse(request.GET['start']+'T00:00:00.0+00:00')
enddatetime = parser.parse(request.GET['end']+'T00:00:00.0+00:00')
events = Event.objects.all()
event_occurrences = [event.get_occurrences(startdatetime,enddatetime) for event in events]
if event_occurrences is None:
return HttpResponse("[]")
else:
event_occurrences_flat = [item for sublist in event_occurrences for item in sublist] #flatten the list of lists of events
fullcalendar_events = [occurrence.to_fullcalendar() for occurrence in event_occurrences_flat]
return HttpResponse(json.dumps(fullcalendar_events))
class EventList(ListView):
model = Event
# def get_queryset(self):
# return Event.objects.all() |
class EventDelete(DeleteView):
model = Event
class EventUpdate(UpdateView):
model = Event
form_class = EventForm
class EventDetail(DetailView):
model = Event |
class EventCreate(CreateView):
model = Event
form_class = EventForm |
zz_groupversion_info.go | /*
Copyright 2021 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by ack-generate. DO NOT EDIT.
package v1alpha1
import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)
// Package type metadata.
const (
CRDGroup = "elasticache.aws.crossplane.io" | CRDVersion = "v1alpha1"
)
var (
// GroupVersion is the API Group Version used to register the objects
GroupVersion = schema.GroupVersion{Group: CRDGroup, Version: CRDVersion}
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
) | |
buildifier_diagnostics_manager.ts | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import * as vscode from "vscode";
import { buildifierLint, getBuildifierFileType } from "./buildifier";
/**
* The delay to wait for the user to finish typing before invoking buildifier to
* determine lint warnings.
*/
const DIAGNOSTICS_ON_TYPE_DELAY_MILLIS = 500;
/** Manages diagnostics emitted by buildifier's lint mode. */
export class | implements vscode.Disposable {
/** The diagnostics collection for buildifier lint warnings. */
private diagnosticsCollection = vscode.languages.createDiagnosticCollection(
"buildifier",
);
/**
* Disposables registered by the manager that should be disposed when the
* manager itself is disposed.
*/
private disposables: vscode.Disposable[];
/**
* Initializes a new buildifier diagnostics manager and hooks into workspace
* and window events so that diagnostics are updated live.
*/
constructor() {
let didChangeTextTimer: NodeJS.Timer | null;
vscode.workspace.onDidChangeTextDocument((e) => {
if (didChangeTextTimer) {
clearTimeout(didChangeTextTimer);
}
didChangeTextTimer = setTimeout(() => {
this.updateDiagnostics(e.document);
didChangeTextTimer = null;
}, DIAGNOSTICS_ON_TYPE_DELAY_MILLIS);
});
vscode.window.onDidChangeActiveTextEditor((e) => {
if (!e) {
return;
}
this.updateDiagnostics(e.document);
});
// If there is an active window at the time the manager is created, make
// sure its diagnostics are computed.
if (vscode.window.activeTextEditor) {
this.updateDiagnostics(vscode.window.activeTextEditor.document);
}
}
/**
* Updates the diagnostics collection with lint warnings for the given text
* document.
*
* @param document The text document whose diagnostics should be updated.
*/
public async updateDiagnostics(document: vscode.TextDocument) {
if (document.languageId === "starlark") {
const warnings = await buildifierLint(
document.getText(),
getBuildifierFileType(document.uri.fsPath),
"warn",
);
this.diagnosticsCollection.set(
document.uri,
warnings.map((warning) => {
// Buildifier returns 1-based line numbers, but VS Code is 0-based.
const lineNumber = warning.line - 1;
const line = document.lineAt(lineNumber);
// Buildifier doesn't give us column numbers for warnings, so we cover
// the entire line but start with the first non-space character.
const range = new vscode.Range(
lineNumber,
line.firstNonWhitespaceCharacterIndex,
lineNumber + 1,
0,
);
const diagnostic = new vscode.Diagnostic(
range,
warning.message,
vscode.DiagnosticSeverity.Warning,
);
diagnostic.source = "buildifier";
diagnostic.code = warning.category;
return diagnostic;
}),
);
}
}
public dispose() {
for (const disposable of this.disposables) {
disposable.dispose();
}
}
}
| BuildifierDiagnosticsManager |
get.go | package order
import (
"github.com/chanxuehong/wechat/product/core"
"github.com/chanxuehong/wechat/product/model"
)
// Get 获取订单详情
func Get(clt *cor | lient, orderId uint64) (order *model.Order, err error) {
const incompleteURL = "https://api.weixin.qq.com/product/order/get?access_token="
req := map[string]uint64{
"order_id": orderId,
}
var result struct {
core.Error
Order *model.Order `json:"order"`
}
if err = clt.PostJSON(incompleteURL, req, &result); err != nil {
return
}
if result.ErrCode != core.ErrCodeOK {
err = &result.Error
return
}
order = result.Order
return
}
| e.C |
0016_auto_20200226_1730.py | # Generated by Django 2.2.10 on 2020-02-26 17:30
from django.db import migrations
class | (migrations.Migration):
dependencies = [
('django_eveonline_connector', '0015_merge_20200226_1503'),
]
operations = [
migrations.AlterModelOptions(
name='eveclient',
options={'verbose_name': 'Eve Settings', 'verbose_name_plural': 'Eve Settings'},
),
]
| Migration |
ioports.rs | /// Wrapper for `in` and `out` asm commands.
/// It is `read` and `write` because `in` is a rust keyword.
use ::core::marker::PhantomData;
pub struct IOPort<In, Out> {
num: u16,
phantom_in: PhantomData<In>,
phantom_out: PhantomData<Out>,
}
impl<In, Out> IOPort<In, Out> {
pub const fn new(num: u16) -> Self {
IOPort { num: num, phantom_in: PhantomData{}, phantom_out: PhantomData{} }
}
}
pub trait InPort {
type Type;
unsafe fn read(&mut self) -> Self::Type;
}
pub trait OutPort {
type Type;
unsafe fn write(&mut self, data: Self::Type);
}
impl<Out> InPort for IOPort<u8, Out> {
type Type = u8;
unsafe fn read(&mut self) -> Self::Type {
let ret: Self::Type;
asm!("inb %dx, %al" : "={al}"(ret) : "{dx}"(self.num) : : "volatile");
ret
}
}
impl<In> OutPort for IOPort<In, u8> {
type Type = u8;
unsafe fn write(&mut self, data: Self::Type) {
asm!("outb %al, %dx" : : "{al}"(data), "{dx}"(self.num) : : "volatile");
}
}
impl<Out> InPort for IOPort<u16, Out> {
type Type = u16;
unsafe fn read(&mut self) -> Self::Type {
let ret: Self::Type;
asm!("inw %dx, %ax" : "={ax}"(ret) : "{dx}"(self.num) : : "volatile");
ret
}
}
impl<In> OutPort for IOPort<In, u16> {
type Type = u16;
unsafe fn write(&mut self, data: Self::Type) {
asm!("outw %ax, %dx" : : "{ax}"(data), "{dx}"(self.num) : : "volatile");
}
}
impl<Out> InPort for IOPort<u32, Out> {
type Type = u32;
unsafe fn read(&mut self) -> Self::Type {
let ret: Self::Type;
asm!("inl %dx, %eax" : "={eax}"(ret) : "{dx}"(self.num) : : "volatile");
ret
}
}
impl<In> OutPort for IOPort<In, u32> {
type Type = u32;
unsafe fn write(&mut self, data: Self::Type) {
asm!("outl %eax, %dx" : : "{eax}"(data), "{dx}"(self.num) : : "volatile");
}
}
#[cfg(os_test)]
pub mod ioports_tests {
use super::*;
tests_module!("ioports",
make_instance,
); |
fn make_instance() {
// it will test asm correctness
unsafe {
// Just make an instance. Don't use it;
let fls = false;
// volatile to disable optimization
if ::core::ptr::read_volatile(&fls) {
let mut port8 = IOPort::<u8, u8>::new(123);
port8.write(12);
port8.read();
let mut port16 = IOPort::<u16, u16>::new(123);
port16.write(12);
port16.read();
let mut port32 = IOPort::<u32, u32>::new(123);
port32.write(12);
port32.read();
}
}
}
} | |
bitswap_wo_routing_test.go | package integrationtest
import (
"bytes"
"testing"
context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
"github.com/ipfs/go-ipfs/blocks"
"github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/core/mock"
mocknet "github.com/ipfs/go-ipfs/p2p/net/mock"
)
func TestBitswapWithoutRouting(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
const numPeers = 4
// create network
mn := mocknet.New(ctx)
var nodes []*core.IpfsNode
for i := 0; i < numPeers; i++ {
n, err := core.NewNode(ctx, &core.BuildCfg{
Online: true,
Host: coremock.MockHostOption(mn),
Routing: core.NilRouterOption, // no routing
})
if err != nil {
t.Fatal(err)
}
defer n.Close()
nodes = append(nodes, n)
}
mn.LinkAll()
// connect them
for _, n1 := range nodes {
for _, n2 := range nodes {
if n1 == n2 {
continue
}
log.Debug("connecting to other hosts")
p2 := n2.PeerHost.Peerstore().PeerInfo(n2.PeerHost.ID())
if err := n1.PeerHost.Connect(ctx, p2); err != nil {
t.Fatal(err)
}
}
}
// add blocks to each before
log.Debug("adding block.")
block0 := blocks.NewBlock([]byte("block0"))
block1 := blocks.NewBlock([]byte("block1"))
// put 1 before
if err := nodes[0].Blockstore.Put(block0); err != nil {
t.Fatal(err)
}
// get it out.
for i, n := range nodes {
// skip first because block not in its exchange. will hang.
if i == 0 |
log.Debugf("%d %s get block.", i, n.Identity)
b, err := n.Blocks.GetBlock(ctx, block0.Key())
if err != nil {
t.Error(err)
} else if !bytes.Equal(b.Data, block0.Data) {
t.Error("byte comparison fail")
} else {
log.Debug("got block: %s", b.Key())
}
}
// put 1 after
if err := nodes[1].Blockstore.Put(block1); err != nil {
t.Fatal(err)
}
// get it out.
for _, n := range nodes {
b, err := n.Blocks.GetBlock(ctx, block1.Key())
if err != nil {
t.Error(err)
} else if !bytes.Equal(b.Data, block1.Data) {
t.Error("byte comparison fail")
} else {
log.Debug("got block: %s", b.Key())
}
}
}
| {
continue
} |
test_array.py | # -*- coding: utf-8 -*-
"""Test support for managed arrays."""
import clr
import Python.Test as Test
import System
import pytest
from collections import UserList
def test_public_array():
"""Test public arrays."""
ob = Test.PublicArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
items[0] = 8
assert items[0] == 8
items[4] = 9
assert items[4] == 9
items[-4] = 0
assert items[-4] == 0
items[-1] = 4
assert items[-1] == 4
def test_protected_array():
"""Test protected arrays."""
ob = Test.ProtectedArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
items[0] = 8
assert items[0] == 8
items[4] = 9
assert items[4] == 9
items[-4] = 0
assert items[-4] == 0
items[-1] = 4
assert items[-1] == 4
def test_internal_array():
"""Test internal arrays."""
with pytest.raises(AttributeError):
ob = Test.InternalArrayTest()
_ = ob.items
def test_private_array():
"""Test private arrays."""
with pytest.raises(AttributeError):
ob = Test.PrivateArrayTest()
_ = ob.items
def test_array_bounds_checking():
"""Test array bounds checking."""
ob = Test.Int32ArrayTest()
items = ob.items
assert items[0] == 0
assert items[1] == 1
assert items[2] == 2
assert items[3] == 3
assert items[4] == 4
assert items[-5] == 0
assert items[-4] == 1
assert items[-3] == 2
assert items[-2] == 3
assert items[-1] == 4
with pytest.raises(IndexError):
ob = Test.Int32ArrayTest()
_ = ob.items[5]
with pytest.raises(IndexError):
ob = Test.Int32ArrayTest()
ob.items[5] = 0
with pytest.raises(IndexError):
ob = Test.Int32ArrayTest()
items[-6]
with pytest.raises(IndexError):
ob = Test.Int32ArrayTest()
items[-6] = 0
def test_array_contains():
"""Test array support for __contains__."""
ob = Test.Int32ArrayTest()
items = ob.items
assert 0 in items
assert 1 in items
assert 2 in items
assert 3 in items
assert 4 in items
assert not (5 in items) # "H:\Python27\Lib\unittest\case.py", line 592, in deprecated_func,
assert not (-1 in items) # TypeError: int() argument must be a string or a number, not 'NoneType'
assert not (None in items) # which threw ^ here which is a little odd.
# But when run from runtests.py. Not when this module ran by itself.
def test_boolean_array():
"""Test boolean arrays."""
ob = Test.BooleanArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] is True
assert items[1] is False
assert items[2] is True
assert items[3] is False
assert items[4] is True
items[0] = False
assert items[0] is False
items[0] = True
assert items[0] is True
with pytest.raises(TypeError):
ob = Test.ByteArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.ByteArrayTest()
ob[0] = "wrong"
def test_byte_array():
"""Test byte arrays."""
ob = Test.ByteArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 255
min_ = 0
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.ByteArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.ByteArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.ByteArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.ByteArrayTest()
ob[0] = "wrong"
def test_sbyte_array():
"""Test sbyte arrays."""
ob = Test.SByteArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 127
min_ = -128
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.SByteArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.SByteArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.SByteArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.SByteArrayTest()
ob[0] = "wrong"
def test_char_array():
"""Test char arrays."""
ob = Test.CharArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 'a'
assert items[4] == 'e'
max_ = chr(65535)
min_ = chr(0)
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(TypeError):
ob = Test.CharArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.CharArrayTest()
ob[0] = "wrong"
def test_int16_array():
"""Test Int16 arrays."""
ob = Test.Int16ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 32767
min_ = -32768
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.Int16ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.Int16ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.Int16ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.Int16ArrayTest()
ob[0] = "wrong"
def test_int32_array():
"""Test Int32 arrays."""
ob = Test.Int32ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 2147483647
min_ = -2147483648
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.Int32ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.Int32ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.Int32ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.Int32ArrayTest()
ob[0] = "wrong"
def test_int64_array():
"""Test Int64 arrays."""
ob = Test.Int64ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 9223372036854775807
min_ = -9223372036854775808
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.Int64ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.Int64ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.Int64ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.Int64ArrayTest()
ob[0] = "wrong"
def test_uint16_array():
"""Test UInt16 arrays."""
ob = Test.UInt16ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 65535
min_ = 0
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.UInt16ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.UInt16ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.UInt16ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.UInt16ArrayTest()
ob[0] = "wrong"
def test_uint32_array():
"""Test UInt32 arrays."""
ob = Test.UInt32ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 4294967295
min_ = 0
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_ | with pytest.raises(OverflowError):
ob = Test.UInt32ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.UInt32ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.UInt32ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.UInt32ArrayTest()
ob[0] = "wrong"
def test_uint64_array():
"""Test UInt64 arrays."""
ob = Test.UInt64ArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0
assert items[4] == 4
max_ = 18446744073709551615
min_ = 0
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(OverflowError):
ob = Test.UInt64ArrayTest()
ob.items[0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.UInt64ArrayTest()
ob.items[0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.UInt64ArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.UInt64ArrayTest()
ob[0] = "wrong"
def test_single_array():
"""Test Single arrays."""
ob = Test.SingleArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0.0
assert items[4] == 4.0
max_ = 3.402823e38
min_ = -3.402823e38
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(TypeError):
ob = Test.SingleArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.SingleArrayTest()
ob[0] = "wrong"
def test_double_array():
"""Test Double arrays."""
ob = Test.DoubleArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == 0.0
assert items[4] == 4.0
max_ = 1.7976931348623157e308
min_ = -1.7976931348623157e308
items[0] = max_
assert items[0] == max_
items[0] = min_
assert items[0] == min_
items[-4] = max_
assert items[-4] == max_
items[-1] = min_
assert items[-1] == min_
with pytest.raises(TypeError):
ob = Test.DoubleArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.DoubleArrayTest()
ob[0] = "wrong"
@pytest.mark.skip(reason="QC PythonNet Converts Decimals into Py Floats")
def test_decimal_array():
"""Test Decimal arrays."""
ob = Test.DecimalArrayTest()
items = ob.items
from System import Decimal
max_d = Decimal.Parse("79228162514264337593543950335")
min_d = Decimal.Parse("-79228162514264337593543950335")
assert len(items) == 5
assert items[0] == Decimal(0)
assert items[4] == Decimal(4)
items[0] = max_d
assert items[0] == max_d
items[0] = min_d
assert items[0] == min_d
items[-4] = max_d
assert items[-4] == max_d
items[-1] = min_d
assert items[-1] == min_d
with pytest.raises(TypeError):
ob = Test.DecimalArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.DecimalArrayTest()
ob[0] = "wrong"
def test_string_array():
"""Test String arrays."""
ob = Test.StringArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == '0'
assert items[4] == '4'
items[0] = "spam"
assert items[0] == "spam"
items[0] = "eggs"
assert items[0] == "eggs"
items[-4] = "spam"
assert items[-4] == "spam"
items[-1] = "eggs"
assert items[-1] == "eggs"
with pytest.raises(TypeError):
ob = Test.StringArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.Int64ArrayTest()
ob[0] = 0
def test_enum_array():
"""Test enum arrays."""
from Python.Test import ShortEnum
ob = Test.EnumArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] == ShortEnum.Zero
assert items[4] == ShortEnum.Four
items[0] = ShortEnum.Four
assert items[0] == ShortEnum.Four
items[0] = ShortEnum.Zero
assert items[0] == ShortEnum.Zero
items[-4] = ShortEnum.Four
assert items[-4] == ShortEnum.Four
items[-1] = ShortEnum.Zero
assert items[-1] == ShortEnum.Zero
with pytest.raises(ValueError):
ob = Test.EnumArrayTest()
ob.items[0] = 99
with pytest.raises(TypeError):
ob = Test.EnumArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.EnumArrayTest()
ob[0] = "wrong"
def test_object_array():
"""Test ob arrays."""
from Python.Test import Spam
ob = Test.ObjectArrayTest()
items = ob.items
assert len(items) == 5
assert items[0].GetValue() == "0"
assert items[4].GetValue() == "4"
items[0] = Spam("4")
assert items[0].GetValue() == "4"
items[0] = Spam("0")
assert items[0].GetValue() == "0"
items[-4] = Spam("4")
assert items[-4].GetValue() == "4"
items[-1] = Spam("0")
assert items[-1].GetValue() == "0"
items[0] = 99
assert items[0] == 99
items[0] = None
assert items[0] is None
with pytest.raises(TypeError):
ob = Test.ObjectArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.ObjectArrayTest()
ob.items["wrong"] = "wrong"
def test_null_array():
"""Test null arrays."""
ob = Test.NullArrayTest()
items = ob.items
assert len(items) == 5
assert items[0] is None
assert items[4] is None
items[0] = "spam"
assert items[0] == "spam"
items[0] = None
assert items[0] is None
items[-4] = "spam"
assert items[-4] == "spam"
items[-1] = None
assert items[-1] is None
empty = ob.empty
assert len(empty) == 0
with pytest.raises(TypeError):
ob = Test.NullArrayTest()
_ = ob.items["wrong"]
# TODO: Error Type should be TypeError for all cases
# Currently throws SystemErrors instead
def test_interface_array():
"""Test interface arrays."""
from Python.Test import Spam
ob = Test.InterfaceArrayTest()
items = ob.items
assert len(items) == 5
assert items[0].GetValue() == "0"
assert items[4].GetValue() == "4"
items[0] = Spam("4")
assert items[0].GetValue() == "4"
items[0] = Spam("0")
assert items[0].GetValue() == "0"
items[-4] = Spam("4")
assert items[-4].GetValue() == "4"
items[-1] = Spam("0")
assert items[-1].GetValue() == "0"
items[0] = None
assert items[0] is None
with pytest.raises(SystemError):
ob = Test.InterfaceArrayTest()
ob.items[0] = 99
with pytest.raises(TypeError):
ob = Test.InterfaceArrayTest()
_ = ob.items["wrong"]
with pytest.raises(SystemError):
ob = Test.InterfaceArrayTest()
ob.items["wrong"] = "wrong"
def test_typed_array():
"""Test typed arrays."""
from Python.Test import Spam
ob = Test.TypedArrayTest()
items = ob.items
assert len(items) == 5
assert items[0].GetValue() == "0"
assert items[4].GetValue() == "4"
items[0] = Spam("4")
assert items[0].GetValue() == "4"
items[0] = Spam("0")
assert items[0].GetValue() == "0"
items[-4] = Spam("4")
assert items[-4].GetValue() == "4"
items[-1] = Spam("0")
assert items[-1].GetValue() == "0"
items[0] = None
assert items[0] is None
with pytest.raises(SystemError):
ob = Test.TypedArrayTest()
ob.items[0] = 99
with pytest.raises(TypeError):
ob = Test.TypedArrayTest()
_ = ob.items["wrong"]
with pytest.raises(TypeError):
ob = Test.TypedArrayTest()
ob.items["wrong"] = Spam("0")
with pytest.raises(TypeError):
ob = Test.TypedArrayTest()
_ = ob.items[0.5]
with pytest.raises(TypeError):
ob = Test.TypedArrayTest()
ob.items[0.5] = Spam("0")
def test_multi_dimensional_array():
"""Test multi-dimensional arrays."""
ob = Test.MultiDimensionalArrayTest()
items = ob.items
assert len(items) == 25
assert items[0, 0] == 0
assert items[0, 1] == 1
assert items[0, 2] == 2
assert items[0, 3] == 3
assert items[0, 4] == 4
assert items[1, 0] == 5
assert items[1, 1] == 6
assert items[1, 2] == 7
assert items[1, 3] == 8
assert items[1, 4] == 9
assert items[2, 0] == 10
assert items[2, 1] == 11
assert items[2, 2] == 12
assert items[2, 3] == 13
assert items[2, 4] == 14
assert items[3, 0] == 15
assert items[3, 1] == 16
assert items[3, 2] == 17
assert items[3, 3] == 18
assert items[3, 4] == 19
assert items[4, 0] == 20
assert items[4, 1] == 21
assert items[4, 2] == 22
assert items[4, 3] == 23
assert items[4, 4] == 24
max_ = 2147483647
min_ = -2147483648
items[0, 0] = max_
assert items[0, 0] == max_
items[0, 0] = min_
assert items[0, 0] == min_
items[-4, 0] = max_
assert items[-4, 0] == max_
items[-1, -1] = min_
assert items[-1, -1] == min_
with pytest.raises(OverflowError):
ob = Test.MultiDimensionalArrayTest()
ob.items[0, 0] = max_ + 1
with pytest.raises(OverflowError):
ob = Test.MultiDimensionalArrayTest()
ob.items[0, 0] = min_ - 1
with pytest.raises(TypeError):
ob = Test.MultiDimensionalArrayTest()
_ = ob.items["wrong", 0]
with pytest.raises(ValueError):
ob = Test.MultiDimensionalArrayTest()
ob.items[0, 0] = "wrong"
with pytest.raises(TypeError):
ob = Test.MultiDimensionalArrayTest()
ob["0", 0] = 0
with pytest.raises(TypeError):
ob = Test.MultiDimensionalArrayTest()
ob.items["0", 0] = 0
with pytest.raises(TypeError):
ob = Test.MultiDimensionalArrayTest()
_ = ob.items[0.5, 0]
with pytest.raises(TypeError):
ob = Test.MultiDimensionalArrayTest()
ob.items[0.5, 0] = 0
def test_array_iteration():
"""Test array iteration."""
items = Test.Int32ArrayTest().items
for i in items:
assert (i > -1) and (i < 5)
items = Test.NullArrayTest().items
for i in items:
assert i is None
empty = Test.NullArrayTest().empty
for i in empty:
raise TypeError('iteration over empty array')
def test_tuple_array_conversion():
"""Test conversion of tuples to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = []
for i in range(10):
items.append(Spam(str(i)))
items = tuple(items)
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert len(result) == 10
def test_tuple_nested_array_conversion():
"""Test conversion of tuples to array-of-array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = []
for i in range(10):
subs = []
for _ in range(10):
subs.append(Spam(str(i)))
items.append(tuple(subs))
items = tuple(items)
result = ArrayConversionTest.EchoRangeAA(items)
assert len(result) == 10
assert len(result[0]) == 10
assert result[0][0].__class__ == Spam
def test_list_array_conversion():
"""Test conversion of lists to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = []
for i in range(10):
items.append(Spam(str(i)))
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert len(result) == 10
def test_list_nested_array_conversion():
"""Test conversion of lists to array-of-array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = []
for i in range(10):
subs = []
for _ in range(10):
subs.append(Spam(str(i)))
items.append(subs)
result = ArrayConversionTest.EchoRangeAA(items)
assert len(result) == 10
assert len(result[0]) == 10
assert result[0][0].__class__ == Spam
def test_sequence_array_conversion():
"""Test conversion of sequence-like obs to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = UserList()
for i in range(10):
items.append(Spam(str(i)))
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert len(result) == 10
def test_sequence_nested_array_conversion():
"""Test conversion of sequences to array-of-array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
items = UserList()
for i in range(10):
subs = UserList()
for _ in range(10):
subs.append(Spam(str(i)))
items.append(subs)
result = ArrayConversionTest.EchoRangeAA(items)
assert len(result) == 10
assert len(result[0]) == 10
assert result[0][0].__class__ == Spam
def test_tuple_array_conversion_type_checking():
"""Test error handling for tuple conversion to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
# This should work, because null / None is a valid value in an
# array of reference types.
items = []
for i in range(10):
items.append(Spam(str(i)))
items[1] = None
items = tuple(items)
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert result[1] is None
assert len(result) == 10
with pytest.raises(TypeError):
temp = list(items)
temp[1] = 1
_ = ArrayConversionTest.EchoRange(tuple(temp))
with pytest.raises(TypeError):
temp = list(items)
temp[1] = "spam"
_ = ArrayConversionTest.EchoRange(tuple(temp))
def test_list_array_conversion_type_checking():
"""Test error handling for list conversion to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
# This should work, because null / None is a valid value in an
# array of reference types.
items = []
for i in range(10):
items.append(Spam(str(i)))
items[1] = None
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert result[1] is None
assert len(result) == 10
with pytest.raises(TypeError):
items[1] = 1
_ = ArrayConversionTest.EchoRange(items)
with pytest.raises(TypeError):
items[1] = "spam"
_ = ArrayConversionTest.EchoRange(items)
def test_sequence_array_conversion_type_checking():
"""Test error handling for sequence conversion to array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
# This should work, because null / None is a valid value in an
# array of reference types.
items = UserList()
for i in range(10):
items.append(Spam(str(i)))
items[1] = None
result = ArrayConversionTest.EchoRange(items)
assert result[0].__class__ == Spam
assert result[1] is None
assert len(result) == 10
with pytest.raises(TypeError):
items[1] = 1
_ = ArrayConversionTest.EchoRange(items)
with pytest.raises(TypeError):
items[1] = "spam"
_ = ArrayConversionTest.EchoRange(items)
def test_md_array_conversion():
"""Test passing of multi-dimensional array arguments."""
from Python.Test import ArrayConversionTest
from Python.Test import Spam
from System import Array
# Currently, the runtime does not support automagic conversion of
# Python sequences to true multi-dimensional arrays (though it
# does support arrays-of-arrays). This test exists mostly as an
# example of how a multi-dimensional array can be created and used
# with managed code from Python.
items = Array.CreateInstance(Spam, 5, 5)
for i in range(5):
for n in range(5):
items.SetValue(Spam(str((i, n))), (i, n))
result = ArrayConversionTest.EchoRangeMD(items)
assert len(result) == 25
assert result[0, 0].__class__ == Spam
assert result[0, 0].__class__ == Spam
def test_boxed_value_type_mutation_result():
"""Test behavior of boxed value types."""
# This test actually exists mostly as documentation of an important
# concern when dealing with value types. Python does not have any
# value type semantics that can be mapped to the CLR, so it is easy
# to accidentally write code like the following which is not really
# mutating value types in-place but changing boxed copies.
from System import Array
from Python.Test import Point
items = Array.CreateInstance(Point, 5)
for i in range(5):
items[i] = Point(i, i)
for i in range(5):
# Boxed items, so set_attr will not change the array member.
assert items[i].X == i
assert items[i].Y == i
items[i].X = i + 1
items[i].Y = i + 1
assert items[i].X == i
assert items[i].Y == i
for i in range(5):
# Demonstrates the workaround that will change the members.
assert items[i].X == i
assert items[i].Y == i
item = items[i]
item.X = i + 1
item.Y = i + 1
items[i] = item
assert items[i].X == i + 1
assert items[i].Y == i + 1
def test_create_array_from_shape():
from System import Array
value = Array[int](3)
assert value[1] == 0
assert value.Length == 3
value = Array[int](3, 4)
assert value[1, 1] == 0
assert value.GetLength(0) == 3
assert value.GetLength(1) == 4
with pytest.raises(ValueError):
Array[int](-1)
value = Array[int]('1')
assert value[0] == 1
assert value.Length == 1
with pytest.raises(ValueError):
Array[int](-1, -1)
with pytest.raises(TypeError):
Array[int]('1', '1')
def test_special_array_creation():
"""Test using the Array[<type>] syntax for creating arrays."""
from Python.Test import ISayHello1, InterfaceTest, ShortEnum
from System import Array
inst = InterfaceTest()
value = Array[System.Boolean]([True, True])
assert value[0] is True
assert value[1] is True
assert value.Length == 2
value = Array[bool]([True, True])
assert value[0] is True
assert value[1] is True
assert value.Length == 2
value = Array[System.Byte]([0, 255])
assert value[0] == 0
assert value[1] == 255
assert value.Length == 2
value = Array[System.SByte]([0, 127])
assert value[0] == 0
assert value[1] == 127
assert value.Length == 2
value = Array[System.Char]([u'A', u'Z'])
assert value[0] == u'A'
assert value[1] == u'Z'
assert value.Length == 2
value = Array[System.Char]([0, 65535])
assert value[0] == chr(0)
assert value[1] == chr(65535)
assert value.Length == 2
value = Array[System.Int16]([0, 32767])
assert value[0] == 0
assert value[1] == 32767
assert value.Length == 2
value = Array[System.Int32]([0, 2147483647])
assert value[0] == 0
assert value[1] == 2147483647
assert value.Length == 2
value = Array[int]([0, 2147483647])
assert value[0] == 0
assert value[1] == 2147483647
assert value.Length == 2
value = Array[System.Int64]([0, 9223372036854775807])
assert value[0] == 0
assert value[1] == 9223372036854775807
assert value.Length == 2
value = Array[System.UInt16]([0, 65000])
assert value[0] == 0
assert value[1] == 65000
assert value.Length == 2
value = Array[System.UInt32]([0, 4294967295])
assert value[0] == 0
assert value[1] == 4294967295
assert value.Length == 2
value = Array[System.UInt64]([0, 18446744073709551615])
assert value[0] == 0
assert value[1] == 18446744073709551615
assert value.Length == 2
value = Array[System.Single]([0.0, 3.402823e38])
assert value[0] == 0.0
assert value[1] == 3.402823e38
assert value.Length == 2
value = Array[System.Double]([0.0, 1.7976931348623157e308])
assert value[0] == 0.0
assert value[1] == 1.7976931348623157e308
assert value.Length == 2
value = Array[float]([0.0, 1.7976931348623157e308])
assert value[0] == 0.0
assert value[1] == 1.7976931348623157e308
assert value.Length == 2
value = Array[System.Decimal]([System.Decimal.Zero, System.Decimal.One])
assert value[0] == System.Decimal.Zero
assert value[1] == System.Decimal.One
assert value.Length == 2
value = Array[System.String](["one", "two"])
assert value[0] == "one"
assert value[1] == "two"
assert value.Length == 2
value = Array[str](["one", "two"])
assert value[0] == "one"
assert value[1] == "two"
assert value.Length == 2
value = Array[ShortEnum]([ShortEnum.Zero, ShortEnum.One])
assert value[0] == ShortEnum.Zero
assert value[1] == ShortEnum.One
assert value.Length == 2
value = Array[System.Object]([inst, inst])
assert value[0].__class__ == inst.__class__
assert value[1].__class__ == inst.__class__
assert value.Length == 2
value = Array[InterfaceTest]([inst, inst])
assert value[0].__class__ == inst.__class__
assert value[1].__class__ == inst.__class__
assert value.Length == 2
value = Array[ISayHello1]([inst, inst])
assert value[0].__class__ == inst.__class__
assert value[1].__class__ == inst.__class__
assert value.Length == 2
inst = System.Exception("badness")
value = Array[System.Exception]([inst, inst])
assert value[0].__class__ == inst.__class__
assert value[1].__class__ == inst.__class__
assert value.Length == 2
def test_array_abuse():
"""Test array abuse."""
_class = Test.PublicArrayTest
ob = Test.PublicArrayTest()
with pytest.raises(AttributeError):
del _class.__getitem__
with pytest.raises(AttributeError):
del ob.__getitem__
with pytest.raises(AttributeError):
del _class.__setitem__
with pytest.raises(AttributeError):
del ob.__setitem__
with pytest.raises(TypeError):
Test.PublicArrayTest.__getitem__(0, 0)
with pytest.raises(AttributeError):
Test.PublicArrayTest.__setitem__(0, 0, 0)
with pytest.raises(KeyError):
Test.PublicArrayTest.__dict__['__getitem__']
with pytest.raises(KeyError):
Test.PublicArrayTest.__dict__['__setitem__']
def test_iterator_to_array():
from System import Array, String
d = {"a": 1, "b": 2, "c": 3}
keys_iterator = iter(d.keys())
arr = Array[String](keys_iterator)
Array.Sort(arr)
assert arr[0] == "a"
assert arr[1] == "b"
assert arr[2] == "c"
def test_dict_keys_to_array():
from System import Array, String
d = {"a": 1, "b": 2, "c": 3}
d_keys = d.keys()
arr = Array[String](d_keys)
Array.Sort(arr)
assert arr[0] == "a"
assert arr[1] == "b"
assert arr[2] == "c" | assert items[-1] == min_
|
data.py | import numpy as np
from sklearn import metrics
import math
from keras.preprocessing import sequence
from keras.preprocessing.text import Tokenizer
from typing import *
# fastai utility
def listify(o):
if o is None: return []
if isinstance(o, list): return o
if isinstance(o, str): return [o]
if isinstance(o, Iterable): return list(o)
return [o]
def compose(x, funcs, *args, **kwargs):
for f in listify(funcs):
x = f(x, **kwargs)
return x
class Onehotify():
def __init__(self, vocab_size):
self.vocab_size = vocab_size
self.tokenizer = Tokenizer(num_words=vocab_size)
def __call__(self, item):
return self.tokenizer.sequences_to_matrix([item], mode='binary')
class Padify():
def __init__(self, maxlen):
self.maxlen = maxlen
def __call__(self, item):
return sequence.pad_sequences([item], maxlen=self.maxlen)
class YOnehotify():
def __init__(self, num_classes):
self.num_classes = num_classes
def __call__(self, item):
categorical = np.zeros((1, self.num_classes))
categorical[0, item] = 1
return categorical
class Dataset():
|
class DataLoader():
def __init__(self, ds, bs, drop_last=True): self.ds, self.bs, self.drop_last = ds, bs, drop_last
def __iter__(self):
length = len(self.ds) // self.bs if self.drop_last else math.ceil(len(self.ds) / self.bs)
for i in range(0, length, 1):
yield self.ds[(i*self.bs):(i*self.bs)+self.bs] | def __init__(self, x, y, tfms_x, tfms_y):
self.x, self.y = x, y
self.x_tfms, self.y_tfms = tfms_x, tfms_y
def __len__(self):
return len(self.x)
def _get_transform(self, i, tfms):
return compose(i, tfms)
def __getitem__(self, i):
batch_x, batch_y = self.x[i], self.y[i]
return_x, return_y = [], []
if isinstance(i, slice):
return_x = [self._get_transform(o, self.x_tfms) for o in batch_x]
if isinstance(i, slice):
return_y = [self._get_transform(o, self.y_tfms) for o in batch_y]
return np.vstack(return_x), np.vstack(return_y) |
FetchingWrappedAssetCard.tsx | import * as React from 'react';
import { Action, Asset, FieldExtensionSDK, ViewType, RenderDragFn } from '../../types'; | import { useEntities } from '../../common/EntityStore';
import {
CustomEntityCardProps,
CustomCardRenderer,
RenderCustomMissingEntityCard,
} from '../../common/customCardTypes';
import { AssetCard, EntryCard } from '@contentful/f36-components';
type FetchingWrappedAssetCardProps = {
assetId: string;
isDisabled: boolean;
sdk: FieldExtensionSDK;
viewType: ViewType | 'big_card';
onRemove: () => void;
getEntityUrl?: (id: string) => string;
onAction?: (action: Action) => void;
renderDragHandle?: RenderDragFn;
renderCustomCard?: CustomCardRenderer;
renderCustomMissingEntityCard?: RenderCustomMissingEntityCard;
};
export function FetchingWrappedAssetCard(props: FetchingWrappedAssetCardProps) {
const { getOrLoadAsset, loadEntityScheduledActions, assets } = useEntities();
React.useEffect(() => {
getOrLoadAsset(props.assetId);
}, [props.assetId]);
const asset = assets[props.assetId];
const entityKey =
asset === 'failed'
? 'failed'
: asset === undefined
? 'undefined'
: `:${asset.sys.id}:${asset.sys.version}`;
React.useEffect(() => {
if (asset) {
props.onAction && props.onAction({ type: 'rendered', entity: 'Asset' });
}
}, [asset]);
const onEdit = async () => {
const { slide } = await props.sdk.navigator.openAsset(props.assetId, { slideIn: true });
props.onAction &&
props.onAction({
entity: 'Asset',
type: 'edit',
id: props.assetId,
contentTypeId: '',
slide,
});
};
const onRemove = () => {
props.onRemove();
props.onAction &&
props.onAction({ entity: 'Asset', type: 'delete', id: props.assetId, contentTypeId: '' });
};
return React.useMemo(() => {
if (asset === 'failed') {
const card = (
<MissingEntityCard
entityType="Asset"
asSquare={props.viewType !== 'link'}
isDisabled={props.isDisabled}
onRemove={onRemove}
/>
);
if (props.renderCustomMissingEntityCard) {
return props.renderCustomMissingEntityCard({
defaultCard: card,
entity: {
id: props.assetId,
type: 'Asset',
},
});
}
return card;
}
const { getEntityUrl, sdk } = props;
const size = props.viewType === 'big_card' ? 'default' : 'small';
const commonProps = {
asset: asset as Asset,
entityUrl: getEntityUrl && getEntityUrl(props.assetId),
size: size as 'default' | 'small',
isDisabled: props.isDisabled,
localeCode: props.sdk.field.locale,
defaultLocaleCode: props.sdk.locales.default,
renderDragHandle: props.renderDragHandle,
onEdit,
onRemove,
};
if (props.viewType === 'link') {
if (asset === undefined) {
return <EntryCard size="small" isLoading />;
}
return (
<WrappedAssetLink
{...commonProps}
href={commonProps.entityUrl}
getEntityScheduledActions={sdk.space.getEntityScheduledActions}
/>
);
}
if (asset === undefined) {
return <AssetCard size={size} isLoading />;
}
function renderDefaultCard(props?: CustomEntityCardProps) {
// isClickable has a default value, so omit it from the props
const builtinCardProps: Omit<WrappedAssetCardProps, 'isClickable'> = {
...commonProps,
...props,
getEntityScheduledActions: loadEntityScheduledActions,
asset: (props?.entity as Asset) || commonProps.asset,
getAssetUrl: getEntityUrl,
};
return <WrappedAssetCard {...builtinCardProps} />;
}
if (props.renderCustomCard) {
const customProps: CustomEntityCardProps = {
...commonProps,
entity: commonProps.asset,
};
// LinkActionsProps are injected higher SingleReferenceEditor/MultipleReferenceEditor
const renderedCustomCard = props.renderCustomCard(
customProps,
{} as LinkActionsProps,
renderDefaultCard
);
// Only `false` indicates to render the original card. E.g. `null` would result in no card.
if (renderedCustomCard !== false) {
return renderedCustomCard;
}
}
return renderDefaultCard();
}, [props, entityKey]);
} | import { LinkActionsProps, MissingEntityCard } from '../../components';
import { WrappedAssetCard, WrappedAssetCardProps } from './WrappedAssetCard';
import { WrappedAssetLink } from './WrappedAssetLink'; |
task_creation_test.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for task_creation."""
import mock
import unittest
from bot.tasks import task_creation
from datastore import data_types
from tests.test_libs import helpers
from tests.test_libs import mock_config
from tests.test_libs import test_utils
@test_utils.with_cloud_emulators('datastore')
class RequestBisectionTest(unittest.TestCase):
"""Tests request_bisection."""
def setUp(self):
helpers.patch(self, [
'build_management.build_manager.get_primary_bucket_path',
'build_management.build_manager.get_revisions_list',
'build_management.revisions.get_component_range_list',
'config.local_config.ProjectConfig',
'google_cloud_utils.blobs.read_key',
'google_cloud_utils.pubsub.PubSubClient.publish',
])
data_types.FuzzTarget(
id='libFuzzer_proj_target',
engine='libFuzzer',
project='proj',
binary='target').put()
self.testcase = data_types.Testcase(
crash_type='crash-type',
security_flag=True,
bug_information='1337',
job_type='libfuzzer_asan_proj',
fuzzer_name='libFuzzer',
overridden_fuzzer_name='libFuzzer_proj_target',
regression='123:456',
fixed='123:456',
crash_revision=3,
additional_metadata='{"last_tested_crash_revision": 4}')
self.testcase.put()
self.mock.read_key.return_value = b'reproducer'
self.mock.get_component_range_list.return_value = [
{
'link_text': 'old:new',
},
]
self.mock.ProjectConfig.return_value = mock_config.MockConfig({
'bisect_service': {
'pubsub_topic': '/projects/project/topics/topic',
}
})
def _test(self, sanitizer, old_commit='old', new_commit='new'):
"""Test task publication."""
task_creation.request_bisection(self.testcase.key.id())
publish_calls = self.mock.publish.call_args_list
bisect_types = ('regressed', 'fixed')
self.assertEqual(2, len(publish_calls))
for bisect_type, publish_call in zip(bisect_types, publish_calls):
topic = publish_call[0][1]
message = publish_call[0][2][0]
self.assertEqual('/projects/project/topics/topic', topic)
self.assertEqual(b'reproducer', message.data)
self.assertDictEqual({
'crash_type': 'crash-type',
'security': 'True',
'fuzz_target': 'target',
'new_commit': new_commit,
'old_commit': old_commit,
'project_name': 'proj',
'sanitizer': sanitizer,
'testcase_id': '1',
'issue_id': '1337',
'type': bisect_type,
}, message.attributes)
testcase = self.testcase.key.get()
self.assertTrue(testcase.get_metadata('requested_regressed_bisect'))
self.assertTrue(testcase.get_metadata('requested_fixed_bisect'))
def test_request_bisection_asan(self):
"""Basic regressed test (asan)."""
self.testcase.job_type = 'libfuzzer_asan_proj'
self.testcase.put()
self._test('address')
def test_request_bisection_msan(self):
"""Basic regressed test (asan)."""
self.testcase.job_type = 'libfuzzer_msan_proj'
self.testcase.put()
self._test('memory')
def test_request_bisection_ubsan(self):
"""Basic regressed test (ubsan)."""
self.testcase.job_type = 'libfuzzer_ubsan_proj'
self.testcase.put()
self._test('undefined')
def test_request_bisection_blackbox(self):
"""Test request bisection for blackbox."""
self.testcase.job_type = 'blackbox'
self.testcase.overridden_fuzzer_name = None
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count)
def test_request_bisection_non_security(self):
|
def test_request_bisection_flaky(self):
"""Test request bisection for flaky testcases."""
self.testcase.job_type = 'libfuzzer_asan_proj'
self.testcase.one_time_crasher_flag = True
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count)
def test_request_bisection_no_bug(self):
"""Test request bisection for testcases with no bug attached."""
self.testcase.job_type = 'libfuzzer_asan_proj'
self.testcase.bug_information = ''
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count)
def test_request_bisection_invalid_range(self):
"""Test request bisection for testcases with no bug attached."""
self.testcase.job_type = 'libfuzzer_asan_proj'
self.testcase.regression = 'NA'
self.testcase.fixed = 'NA'
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count)
def test_request_bisection_once_only(self):
"""Test request bisection for testcases isn't repeated if already
requested."""
self.testcase.set_metadata('requested_regressed_bisect', True)
self.testcase.set_metadata('requested_fixed_bisect', True)
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count)
def test_request_single_commit_range(self):
"""Request bisection with a single commit (invalid range)."""
self.mock.get_primary_bucket_path.return_value = 'bucket'
self.mock.get_revisions_list.return_value = list(range(6))
self.mock.get_component_range_list.return_value = [
{
'link_text': 'one',
},
]
task_creation.request_bisection(self.testcase.key.id())
self._test('address', old_commit='one', new_commit='one')
self.mock.get_component_range_list.assert_has_calls([
mock.call(123, 456, 'libfuzzer_asan_proj'),
mock.call(0, 3, 'libfuzzer_asan_proj'),
mock.call(123, 456, 'libfuzzer_asan_proj'),
mock.call(4, 5, 'libfuzzer_asan_proj'),
])
| """Test request bisection for non-security testcases."""
self.testcase.job_type = 'libfuzzer_asan_proj'
self.testcase.security_flag = False
self.testcase.put()
task_creation.request_bisection(self.testcase.key.id())
self.assertEqual(0, self.mock.publish.call_count) |
test_functions.py | """
Here is probably the place to write the docs, since the test-cases
show how the type behave.
Later...
"""
from ctypes import *
import sys, unittest
try:
WINFUNCTYPE
except NameError:
# fake to enable this test on Linux
WINFUNCTYPE = CFUNCTYPE
import _ctypes_test
dll = CDLL(_ctypes_test.__file__)
if sys.platform == "win32":
windll = WinDLL(_ctypes_test.__file__)
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
class RECT(Structure):
_fields_ = [("left", c_int), ("top", c_int),
("right", c_int), ("bottom", c_int)]
class FunctionTestCase(unittest.TestCase):
def test_mro(self):
# in Python 2.3, this raises TypeError: MRO conflict among bases classes,
# in Python 2.2 it works.
#
# But in early versions of _ctypes.c, the result of tp_new
# wasn't checked, and it even crashed Python.
# Found by Greg Chapman.
try:
class X(object, Array):
_length_ = 5
_type_ = "i"
except TypeError:
pass
from _ctypes import _Pointer
try:
class X(object, _Pointer):
pass
except TypeError:
pass
from _ctypes import _SimpleCData
try:
class X(object, _SimpleCData):
_type_ = "i"
except TypeError:
pass
try:
class X(object, Structure):
_fields_ = []
except TypeError:
pass
def test_wchar_parm(self):
try:
c_wchar
except NameError:
return
f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_wchar, c_int, c_long, c_float, c_double]
result = f(1, "x", 3, 4, 5.0, 6.0)
self.assertEqual(result, 139)
self.assertEqual(type(result), int)
def test_wchar_result(self):
try:
c_wchar
except NameError:
return
f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
f.restype = c_wchar
result = f(0, 0, 0, 0, 0, 0)
self.assertEqual(result, '\x00')
def test_voidresult(self):
f = dll._testfunc_v
f.restype = None
f.argtypes = [c_int, c_int, POINTER(c_int)]
result = c_int()
self.assertEqual(None, f(1, 2, byref(result)))
self.assertEqual(result.value, 3)
def test_intresult(self):
f = dll._testfunc_i_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
f.restype = c_int
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), int)
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.assertEqual(result, -21)
self.assertEqual(type(result), int)
# If we declare the function to return a short,
# is the high part split off?
f.restype = c_short
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), int)
result = f(1, 2, 3, 0x10004, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), int)
# You cannot assign character format codes as restype any longer
self.assertRaises(TypeError, setattr, f, "restype", "i")
def test_floatresult(self):
f = dll._testfunc_f_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
f.restype = c_float
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), float)
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.assertEqual(result, -21)
self.assertEqual(type(result), float)
def test_doubleresult(self):
f = dll._testfunc_d_bhilfd
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
f.restype = c_double
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), float)
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.assertEqual(result, -21)
self.assertEqual(type(result), float)
def test_longdoubleresult(self):
f = dll._testfunc_D_bhilfD
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_longdouble]
f.restype = c_longdouble
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
self.assertEqual(type(result), float)
result = f(-1, -2, -3, -4, -5.0, -6.0)
self.assertEqual(result, -21)
self.assertEqual(type(result), float)
def test_longlongresult(self):
try:
c_longlong
except NameError:
return
f = dll._testfunc_q_bhilfd
f.restype = c_longlong
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double]
result = f(1, 2, 3, 4, 5.0, 6.0)
self.assertEqual(result, 21)
f = dll._testfunc_q_bhilfdq
f.restype = c_longlong
f.argtypes = [c_byte, c_short, c_int, c_long, c_float, c_double, c_longlong]
result = f(1, 2, 3, 4, 5.0, 6.0, 21)
self.assertEqual(result, 42)
def test_stringresult(self):
f = dll._testfunc_p_p
f.argtypes = None
f.restype = c_char_p
result = f(b"123")
self.assertEqual(result, b"123")
result = f(None)
self.assertEqual(result, None)
def test_pointers(self):
f = dll._testfunc_p_p
f.restype = POINTER(c_int)
f.argtypes = [POINTER(c_int)]
# This only works if the value c_int(42) passed to the
# function is still alive while the pointer (the result) is
# used.
v = c_int(42)
self.assertEqual(pointer(v).contents.value, 42)
result = f(pointer(v))
self.assertEqual(type(result), POINTER(c_int))
self.assertEqual(result.contents.value, 42)
# This on works...
result = f(pointer(v))
self.assertEqual(result.contents.value, v.value)
p = pointer(c_int(99))
result = f(p)
self.assertEqual(result.contents.value, 99)
arg = byref(v)
result = f(arg)
self.assertNotEqual(result.contents, v.value)
self.assertRaises(ArgumentError, f, byref(c_short(22)))
# It is dangerous, however, because you don't control the lifetime
# of the pointer:
result = f(byref(c_int(99)))
self.assertNotEqual(result.contents, 99)
def test_errors(self):
f = dll._testfunc_p_p
f.restype = c_int
class X(Structure):
_fields_ = [("y", c_int)]
self.assertRaises(TypeError, f, X()) #cannot convert parameter
################################################################
def test_shorts(self):
f = dll._testfunc_callback_i_if
args = []
expected = [262144, 131072, 65536, 32768, 16384, 8192, 4096, 2048,
1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
def callback(v):
args.append(v)
return v
CallBack = CFUNCTYPE(c_int, c_int)
cb = CallBack(callback)
f(2**18, cb)
self.assertEqual(args, expected)
################################################################
def test_callbacks(self):
f = dll._testfunc_callback_i_if
f.restype = c_int
MyCallback = CFUNCTYPE(c_int, c_int)
def callback(value):
#print "called back with", value
return value
cb = MyCallback(callback)
result = f(-10, cb)
self.assertEqual(result, -18)
# test with prototype
f.argtypes = [c_int, MyCallback]
cb = MyCallback(callback)
result = f(-10, cb)
self.assertEqual(result, -18)
AnotherCallback = WINFUNCTYPE(c_int, c_int, c_int, c_int, c_int)
# check that the prototype works: we call f with wrong
# argument types
cb = AnotherCallback(callback)
self.assertRaises(ArgumentError, f, -10, cb)
def test_callbacks_2(self):
# Can also use simple datatypes as argument type specifiers
# for the callback function.
# In this case the call receives an instance of that type
f = dll._testfunc_callback_i_if
f.restype = c_int
MyCallback = CFUNCTYPE(c_int, c_int)
f.argtypes = [c_int, MyCallback]
| def callback(value):
#print "called back with", value
self.assertEqual(type(value), int)
return value
cb = MyCallback(callback)
result = f(-10, cb)
self.assertEqual(result, -18)
def test_longlong_callbacks(self):
f = dll._testfunc_callback_q_qf
f.restype = c_longlong
MyCallback = CFUNCTYPE(c_longlong, c_longlong)
f.argtypes = [c_longlong, MyCallback]
def callback(value):
self.assertTrue(isinstance(value, int))
return value & 0x7FFFFFFF
cb = MyCallback(callback)
self.assertEqual(13577625587, f(1000000000000, cb))
def test_errors(self):
self.assertRaises(AttributeError, getattr, dll, "_xxx_yyy")
self.assertRaises(ValueError, c_int.in_dll, dll, "_xxx_yyy")
def test_byval(self):
# without prototype
ptin = POINT(1, 2)
ptout = POINT()
# EXPORT int _testfunc_byval(point in, point *pout)
result = dll._testfunc_byval(ptin, byref(ptout))
got = result, ptout.x, ptout.y
expected = 3, 1, 2
self.assertEqual(got, expected)
# with prototype
ptin = POINT(101, 102)
ptout = POINT()
dll._testfunc_byval.argtypes = (POINT, POINTER(POINT))
dll._testfunc_byval.restype = c_int
result = dll._testfunc_byval(ptin, byref(ptout))
got = result, ptout.x, ptout.y
expected = 203, 101, 102
self.assertEqual(got, expected)
def test_struct_return_2H(self):
class S2H(Structure):
_fields_ = [("x", c_short),
("y", c_short)]
dll.ret_2h_func.restype = S2H
dll.ret_2h_func.argtypes = [S2H]
inp = S2H(99, 88)
s2h = dll.ret_2h_func(inp)
self.assertEqual((s2h.x, s2h.y), (99*2, 88*3))
if sys.platform == "win32":
def test_struct_return_2H_stdcall(self):
class S2H(Structure):
_fields_ = [("x", c_short),
("y", c_short)]
windll.s_ret_2h_func.restype = S2H
windll.s_ret_2h_func.argtypes = [S2H]
s2h = windll.s_ret_2h_func(S2H(99, 88))
self.assertEqual((s2h.x, s2h.y), (99*2, 88*3))
def test_struct_return_8H(self):
class S8I(Structure):
_fields_ = [("a", c_int),
("b", c_int),
("c", c_int),
("d", c_int),
("e", c_int),
("f", c_int),
("g", c_int),
("h", c_int)]
dll.ret_8i_func.restype = S8I
dll.ret_8i_func.argtypes = [S8I]
inp = S8I(9, 8, 7, 6, 5, 4, 3, 2)
s8i = dll.ret_8i_func(inp)
self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
(9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
if sys.platform == "win32":
def test_struct_return_8H_stdcall(self):
class S8I(Structure):
_fields_ = [("a", c_int),
("b", c_int),
("c", c_int),
("d", c_int),
("e", c_int),
("f", c_int),
("g", c_int),
("h", c_int)]
windll.s_ret_8i_func.restype = S8I
windll.s_ret_8i_func.argtypes = [S8I]
inp = S8I(9, 8, 7, 6, 5, 4, 3, 2)
s8i = windll.s_ret_8i_func(inp)
self.assertEqual((s8i.a, s8i.b, s8i.c, s8i.d, s8i.e, s8i.f, s8i.g, s8i.h),
(9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9))
def test_sf1651235(self):
# see http://www.python.org/sf/1651235
proto = CFUNCTYPE(c_int, RECT, POINT)
def callback(*args):
return 0
callback = proto(callback)
self.assertRaises(ArgumentError, lambda: callback((1, 2, 3, 4), POINT()))
if __name__ == '__main__':
unittest.main() | |
0004_auto_20210318_1753.py | # Generated by Django 2.2 on 2021-03-18 17:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
('posts', '0003_auto_20210307_1711'),
]
operations = [
migrations.AlterField(
model_name='post',
name='group',
field=models.ForeignKey(blank=True, help_text='Выберите группу для поста (необязательно)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='posts.Group', verbose_name='Группа'),
),
migrations.AlterField(
model_name='post',
name='text',
field=models.TextField(help_text='Введите текст', verbose_name='Текст'),
),
]
|
|
ApiExtractorTask.d.ts | /// <reference types="node" />
import * as Gulp from 'gulp';
import { GulpTask } from '@microsoft/gulp-core-build';
/** @public */
export interface IApiExtractorTaskConfig {
/**
* Indicates whether the task should be run. | /**
* The file path of the exported entry point, relative to the project folder.
*
* Example "src/index.ts"
*/
entry?: string;
/**
* The file path of the folder containing API files to be reviewed, relative to
* the project folder. This is part of an API review workflow: During a build,
* the ApiExtractorTask will output an API file, e.g. "my-project/temp/my-project.api.ts".
* It will then compare this file against the last reviewed file,
* e.g. "../api-review/my-project.api.ts" (assuming that apiReviewFolder is "../api-review").
* If the files are different, the build will fail with an error message that instructs
* the developer to update the approved file, and then commit it to Git. When they
* create a Pull Request, a VSO branch policy will look for changes under "api-review/*"
* and require signoff from the appropriate reviewers.
*
* Example: "config" (for a standalone project)
* Example: "../../common/api-review" (for a Git repository with Rush)
*/
apiReviewFolder?: string;
/**
* The file path of the folder containing the *.api.json output file containing
* the API information. The default location is in the “dist” folder,
* e.g. my-project/dist/my-project.api.json. This file should be published as part
* of the NPM package. When building other projects that depend on this package,
* api-extractor will look for this file in the node_modules folder and use it as an input.
* The *.api.json file is also consumed by a tool at
* https://github.com/SharePoint/ts-spec-gen that generates an online API documentation.
*/
apiJsonFolder?: string;
}
/**
* The ApiExtractorTask uses the api-extractor tool to analyze a project for public APIs. api-extractor will detect
* common problems and generate a report of the exported public API. The task uses the entry point of a project to
* find the aliased exports of the project. An api-extractor.ts file is generated for the project in the temp folder.
* @public
*/
export declare class ApiExtractorTask extends GulpTask<IApiExtractorTaskConfig> {
constructor();
loadSchema(): Object;
executeTask(gulp: typeof Gulp, completeCallback: (error?: string) => void): NodeJS.ReadWriteStream | void;
private _validateConfiguration();
} | */
enabled?: boolean; |
profile.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package user
import (
"fmt"
"path"
"strings"
"github.com/Unknwon/paginater"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/routers/repo"
)
const (
tplFollowers base.TplName = "user/meta/followers"
tplStars base.TplName = "user/meta/stars"
)
// GetUserByName get user by name
func GetUserByName(ctx *context.Context, name string) *models.User {
user, err := models.GetUserByName(name)
if err != nil {
if models.IsErrUserNotExist(err) {
ctx.Handle(404, "GetUserByName", nil)
} else {
ctx.Handle(500, "GetUserByName", err)
}
return nil
}
return user
}
// GetUserByParams returns user whose name is presented in URL paramenter.
func GetUserByParams(ctx *context.Context) *models.User {
return GetUserByName(ctx, ctx.Params(":username"))
}
// Profile render user's profile page
func Profile(ctx *context.Context) {
uname := ctx.Params(":username")
// Special handle for FireFox requests favicon.ico.
if uname == "favicon.ico" {
ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png"))
return |
isShowKeys := false
if strings.HasSuffix(uname, ".keys") {
isShowKeys = true
}
ctxUser := GetUserByName(ctx, strings.TrimSuffix(uname, ".keys"))
if ctx.Written() {
return
}
// Show SSH keys.
if isShowKeys {
ShowSSHKeys(ctx, ctxUser.ID)
return
}
if ctxUser.IsOrganization() {
showOrgProfile(ctx)
return
}
ctx.Data["Title"] = ctxUser.DisplayName()
ctx.Data["PageIsUserProfile"] = true
ctx.Data["Owner"] = ctxUser
orgs, err := models.GetOrgsByUserID(ctxUser.ID, ctx.IsSigned && (ctx.User.IsAdmin || ctx.User.ID == ctxUser.ID))
if err != nil {
ctx.Handle(500, "GetOrgsByUserIDDesc", err)
return
}
ctx.Data["Orgs"] = orgs
tab := ctx.Query("tab")
ctx.Data["TabName"] = tab
switch tab {
case "activity":
retrieveFeeds(ctx, ctxUser, -1, 0, true)
if ctx.Written() {
return
}
case "stars":
showPrivateRepos := ctx.IsSigned && ctx.User.ID == ctxUser.ID
starredRepos, err := ctxUser.GetStarredRepos(showPrivateRepos)
if err != nil {
ctx.Handle(500, "GetStarredRepos", err)
return
}
ctx.Data["Repos"] = starredRepos
default:
page := ctx.QueryInt("page")
if page <= 0 {
page = 1
}
ctx.Data["Repos"], err = models.GetUserRepositories(ctxUser.ID, ctx.IsSigned && ctx.User.ID == ctxUser.ID, page, setting.UI.User.RepoPagingNum)
if err != nil {
ctx.Handle(500, "GetRepositories", err)
return
}
ctx.Data["Page"] = paginater.New(ctxUser.NumRepos, setting.UI.User.RepoPagingNum, page, 5)
}
ctx.HTML(200, tplProfile)
}
// Followers render user's followers page
func Followers(ctx *context.Context) {
u := GetUserByParams(ctx)
if ctx.Written() {
return
}
ctx.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.followers")
ctx.Data["PageIsFollowers"] = true
ctx.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowers, u.GetFollowers, tplFollowers)
}
// Following render user's followering page
func Following(ctx *context.Context) {
u := GetUserByParams(ctx)
if ctx.Written() {
return
}
ctx.Data["Title"] = u.DisplayName()
ctx.Data["CardsTitle"] = ctx.Tr("user.following")
ctx.Data["PageIsFollowing"] = true
ctx.Data["Owner"] = u
repo.RenderUserCards(ctx, u.NumFollowing, u.GetFollowing, tplFollowers)
}
// Action response for follow/unfollow user request
func Action(ctx *context.Context) {
u := GetUserByParams(ctx)
if ctx.Written() {
return
}
var err error
switch ctx.Params(":action") {
case "follow":
err = models.FollowUser(ctx.User.ID, u.ID)
case "unfollow":
err = models.UnfollowUser(ctx.User.ID, u.ID)
}
if err != nil {
ctx.Handle(500, fmt.Sprintf("Action (%s)", ctx.Params(":action")), err)
return
}
redirectTo := ctx.Query("redirect_to")
if len(redirectTo) == 0 {
redirectTo = u.HomeLink()
}
ctx.Redirect(redirectTo)
} | } else if strings.HasSuffix(uname, ".png") {
ctx.Error(404)
return
} |
PropsStore.ts | class PropsStore {
static _instance: PropsStore
private propsByModuleName: Record<string, any> = {}
private pendingPropsByModuleName: Record<string, any> = {}
constructor() {
if (PropsStore._instance) {
return PropsStore._instance
}
PropsStore._instance = this
}
updateProps(moduleName: string, props: any, callback?: (updatedProps: { [key: string]: any }) => void) {
this.mergeNewPropsForModule(moduleName, props)
callback?.(this.propsByModuleName[moduleName])
}
setPendingProps(moduleName: string, newProps: any) {
this.pendingPropsByModuleName[moduleName] = newProps
} | getPropsForModule(moduleName: string) {
if (this.pendingPropsByModuleName[moduleName]) {
this.propsByModuleName[moduleName] = this.pendingPropsByModuleName[moduleName]
delete this.pendingPropsByModuleName[moduleName]
}
return this.propsByModuleName[moduleName] || {}
}
mergeNewPropsForModule(moduleName: string, newProps: any) {
const currentProps = this.getPropsForModule(moduleName)
this.propsByModuleName[moduleName] = {
...currentProps,
...newProps,
}
}
}
export const propsStore = new PropsStore() | |
instrument.py | import os
import re
import subprocess
import base64
import os.path as osp
import pickle as pickle
import inspect
import hashlib
import sys
from contextlib import contextmanager
import errno
from rllab.core.serializable import Serializable
from rllab import config
from rllab.misc.console import mkdir_p
from rllab.misc import ext
from io import StringIO
import datetime
import dateutil.tz
import json
import time
import numpy as np
from rllab.misc.ext import AttrDict
from rllab.viskit.core import flatten
import collections
class StubBase(object):
def __getitem__(self, item):
return StubMethodCall(self, "__getitem__", args=[item], kwargs=dict())
def __getattr__(self, item):
try:
return super(self.__class__, self).__getattribute__(item)
except AttributeError:
if item.startswith("__") and item.endswith("__"):
raise
return StubAttr(self, item)
def __pow__(self, power, modulo=None):
return StubMethodCall(self, "__pow__", [power, modulo], dict())
def __call__(self, *args, **kwargs):
return StubMethodCall(self.obj, self.attr_name, args, kwargs)
def __add__(self, other):
return StubMethodCall(self, "__add__", [other], dict())
def __rmul__(self, other):
return StubMethodCall(self, "__rmul__", [other], dict())
def __div__(self, other):
return StubMethodCall(self, "__div__", [other], dict())
def __rdiv__(self, other):
return StubMethodCall(BinaryOp(), "rdiv", [self, other], dict()) # self, "__rdiv__", [other], dict())
def __rpow__(self, power, modulo=None):
return StubMethodCall(self, "__rpow__", [power, modulo], dict())
class BinaryOp(Serializable):
def __init__(self):
Serializable.quick_init(self, locals())
def rdiv(self, a, b):
return b / a
# def __init__(self, opname, a, b):
# self.opname = opname
# self.a = a
# self.b = b
class StubAttr(StubBase):
def __init__(self, obj, attr_name):
self.__dict__["_obj"] = obj
self.__dict__["_attr_name"] = attr_name
@property
def obj(self):
return self.__dict__["_obj"]
@property
def attr_name(self):
return self.__dict__["_attr_name"]
def __str__(self):
return "StubAttr(%s, %s)" % (str(self.obj), str(self.attr_name))
class StubMethodCall(StubBase, Serializable):
def __init__(self, obj, method_name, args, kwargs):
self._serializable_initialized = False
Serializable.quick_init(self, locals())
self.obj = obj
self.method_name = method_name
self.args = args
self.kwargs = kwargs
def __str__(self):
return "StubMethodCall(%s, %s, %s, %s)" % (
str(self.obj), str(self.method_name), str(self.args), str(self.kwargs))
class StubClass(StubBase):
def __init__(self, proxy_class):
self.proxy_class = proxy_class
def __call__(self, *args, **kwargs):
if len(args) > 0:
# Convert the positional arguments to keyword arguments
spec = inspect.getargspec(self.proxy_class.__init__)
kwargs = dict(list(zip(spec.args[1:], args)), **kwargs)
args = tuple()
return StubObject(self.proxy_class, *args, **kwargs)
def __getstate__(self):
return dict(proxy_class=self.proxy_class)
def __setstate__(self, dict):
self.proxy_class = dict["proxy_class"]
def __getattr__(self, item):
if hasattr(self.proxy_class, item):
return StubAttr(self, item)
raise AttributeError
def __str__(self):
return "StubClass(%s)" % self.proxy_class
class StubObject(StubBase):
def __init__(self, __proxy_class, *args, **kwargs):
if len(args) > 0:
spec = inspect.getargspec(__proxy_class.__init__)
kwargs = dict(list(zip(spec.args[1:], args)), **kwargs)
args = tuple()
self.proxy_class = __proxy_class
self.args = args
self.kwargs = kwargs
def __getstate__(self):
return dict(args=self.args, kwargs=self.kwargs, proxy_class=self.proxy_class)
def __setstate__(self, dict):
self.args = dict["args"]
self.kwargs = dict["kwargs"]
self.proxy_class = dict["proxy_class"]
def __getattr__(self, item):
# why doesnt the commented code work?
# return StubAttr(self, item)
# checks bypassed to allow for accesing instance fileds
if hasattr(self.proxy_class, item):
return StubAttr(self, item)
raise AttributeError('Cannot get attribute %s from %s' % (item, self.proxy_class))
def __str__(self):
return "StubObject(%s, *%s, **%s)" % (str(self.proxy_class), str(self.args), str(self.kwargs))
class VariantDict(AttrDict):
def __init__(self, d, hidden_keys):
super(VariantDict, self).__init__(d)
self._hidden_keys = hidden_keys
def dump(self):
return {k: v for k, v in self.items() if k not in self._hidden_keys}
class VariantGenerator(object):
"""
Usage:
vg = VariantGenerator()
vg.add("param1", [1, 2, 3])
vg.add("param2", ['x', 'y'])
vg.variants() => # all combinations of [1,2,3] x ['x','y']
Supports noncyclic dependency among parameters:
vg = VariantGenerator()
vg.add("param1", [1, 2, 3])
vg.add("param2", lambda param1: [param1+1, param1+2])
vg.variants() => # ..
"""
def __init__(self):
self._variants = []
self._populate_variants()
self._hidden_keys = []
for k, vs, cfg in self._variants:
if cfg.get("hide", False):
self._hidden_keys.append(k)
def add(self, key, vals, **kwargs):
self._variants.append((key, vals, kwargs))
def _populate_variants(self):
methods = inspect.getmembers(
self.__class__, predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x))
methods = [x[1].__get__(self, self.__class__)
for x in methods if getattr(x[1], '__is_variant', False)]
for m in methods:
self.add(m.__name__, m, **getattr(m, "__variant_config", dict()))
def variants(self, randomized=False):
ret = list(self.ivariants())
if randomized:
np.random.shuffle(ret)
return list(map(self.variant_dict, ret))
def variant_dict(self, variant):
return VariantDict(variant, self._hidden_keys)
def to_name_suffix(self, variant):
|
def ivariants(self):
dependencies = list()
for key, vals, _ in self._variants:
if hasattr(vals, "__call__"):
args = inspect.getargspec(vals).args
if hasattr(vals, 'im_self') or hasattr(vals, "__self__"):
# remove the first 'self' parameter
args = args[1:]
dependencies.append((key, set(args)))
else:
dependencies.append((key, set()))
sorted_keys = []
# topo sort all nodes
while len(sorted_keys) < len(self._variants):
# get all nodes with zero in-degree
free_nodes = [k for k, v in dependencies if len(v) == 0]
if len(free_nodes) == 0:
error_msg = "Invalid parameter dependency: \n"
for k, v in dependencies:
if len(v) > 0:
error_msg += k + " depends on " + " & ".join(v) + "\n"
raise ValueError(error_msg)
dependencies = [(k, v)
for k, v in dependencies if k not in free_nodes]
# remove the free nodes from the remaining dependencies
for _, v in dependencies:
v.difference_update(free_nodes)
sorted_keys += free_nodes
return self._ivariants_sorted(sorted_keys)
def _ivariants_sorted(self, sorted_keys):
if len(sorted_keys) == 0:
yield dict()
else:
first_keys = sorted_keys[:-1]
first_variants = self._ivariants_sorted(first_keys)
last_key = sorted_keys[-1]
last_vals = [v for k, v, _ in self._variants if k == last_key][0]
if hasattr(last_vals, "__call__"):
last_val_keys = inspect.getargspec(last_vals).args
if hasattr(last_vals, 'im_self') or hasattr(last_vals, '__self__'):
last_val_keys = last_val_keys[1:]
else:
last_val_keys = None
for variant in first_variants:
if hasattr(last_vals, "__call__"):
last_variants = last_vals(
**{k: variant[k] for k in last_val_keys})
for last_choice in last_variants:
yield AttrDict(variant, **{last_key: last_choice})
else:
for last_choice in last_vals:
yield AttrDict(variant, **{last_key: last_choice})
def variant(*args, **kwargs):
def _variant(fn):
fn.__is_variant = True
fn.__variant_config = kwargs
return fn
if len(args) == 1 and isinstance(args[0], collections.Callable):
return _variant(args[0])
return _variant
def stub(glbs):
# replace the __init__ method in all classes
# hacky!!!
for k, v in list(glbs.items()):
# look at all variables that are instances of a class (not yet Stub)
if isinstance(v, type) and v != StubClass:
glbs[k] = StubClass(v) # and replaces them by a the same but Stub
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
exp_count = 0
now = datetime.datetime.now(dateutil.tz.tzlocal())
timestamp = now.strftime('%Y_%m_%d_%H_%M_%S')
remote_confirmed = False
def run_experiment_lite(
stub_method_call=None,
batch_tasks=None,
exp_prefix="experiment",
exp_name=None,
log_dir=None,
script="scripts/run_experiment_lite.py",
python_command="python",
mode="local",
dry=False,
docker_image=None,
aws_config=None,
env=None,
variant=None,
use_gpu=False,
sync_s3_pkl=False,
sync_s3_png=False,
sync_s3_log=False,
sync_log_on_termination=True,
confirm_remote=True,
terminate_machine=True,
periodic_sync=True,
periodic_sync_interval=15,
sync_all_data_node_to_s3=True,
use_cloudpickle=None,
pre_commands=None,
added_project_directories=[],
**kwargs):
"""
Serialize the stubbed method call and run the experiment using the specified mode.
:param stub_method_call: A stubbed method call.
:param script: The name of the entrance point python script
:param mode: Where & how to run the experiment. Should be one of "local", "local_docker", "ec2",
and "lab_kube".
:param dry: Whether to do a dry-run, which only prints the commands without executing them.
:param exp_prefix: Name prefix for the experiments
:param docker_image: name of the docker image. Ignored if using local mode.
:param aws_config: configuration for AWS. Only used under EC2 mode
:param env: extra environment variables
:param kwargs: All other parameters will be passed directly to the entrance python script.
:param variant: If provided, should be a dictionary of parameters
:param use_gpu: Whether the launched task is running on GPU. This triggers a few configuration changes including
certain environment flags
:param sync_s3_pkl: Whether to sync pkl files during execution of the experiment (they will always be synced at
the end of the experiment)
:param sync_s3_png: Whether to sync png files during execution of the experiment (they will always be synced at
the end of the experiment)
:param sync_s3_log: Whether to sync log files during execution of the experiment (they will always be synced at
the end of the experiment)
:param confirm_remote: Whether to confirm before launching experiments remotely
:param terminate_machine: Whether to terminate machine after experiment finishes. Only used when using
mode="ec2". This is useful when one wants to debug after an experiment finishes abnormally.
:param periodic_sync: Whether to synchronize certain experiment files periodically during execution.
:param periodic_sync_interval: Time interval between each periodic sync, in seconds.
"""
assert stub_method_call is not None or batch_tasks is not None, "Must provide at least either stub_method_call or batch_tasks"
if use_cloudpickle is None:
for maybe_stub in (batch_tasks or [stub_method_call]):
# decide mode
if isinstance(maybe_stub, StubBase):
use_cloudpickle = False
else:
assert hasattr(maybe_stub, '__call__')
use_cloudpickle = True
# ensure variant exists
if variant is None:
variant = dict()
if batch_tasks is None:
batch_tasks = [
dict(
kwargs,
pre_commands=pre_commands,
stub_method_call=stub_method_call,
exp_name=exp_name,
log_dir=log_dir,
env=env,
variant=variant,
use_cloudpickle=use_cloudpickle
)
]
global exp_count
global remote_confirmed
config.USE_GPU = use_gpu
# params_list = []
for task in batch_tasks:
call = task.pop("stub_method_call")
if use_cloudpickle:
import cloudpickle
data = base64.b64encode(cloudpickle.dumps(call)).decode("utf-8")
else:
data = base64.b64encode(pickle.dumps(call)).decode("utf-8")
task["args_data"] = data
exp_count += 1
params = dict(kwargs)
if task.get("exp_name", None) is None:
task["exp_name"] = "%s_%s_%04d" % (
exp_prefix, timestamp, exp_count)
if task.get("log_dir", None) is None:
task["log_dir"] = config.LOG_DIR + "/local/" + \
exp_prefix.replace("_", "-") + "/" + task["exp_name"]
if task.get("variant", None) is not None:
variant = task.pop("variant")
if "exp_name" not in variant:
variant["exp_name"] = task["exp_name"]
task["variant_data"] = base64.b64encode(pickle.dumps(variant)).decode("utf-8")
elif "variant" in task:
del task["variant"]
task["remote_log_dir"] = osp.join(
config.AWS_S3_PATH, exp_prefix.replace("_", "-"), task["exp_name"])
task["env"] = task.get("env", dict()) or dict()
task["env"]["RLLAB_USE_GPU"] = str(use_gpu)
if mode not in ["local", "local_docker"] and not remote_confirmed and not dry and confirm_remote:
remote_confirmed = query_yes_no(
"Running in (non-dry) mode %s. Confirm?" % mode)
if not remote_confirmed:
sys.exit(1)
if hasattr(mode, "__call__"):
if docker_image is None:
docker_image = config.DOCKER_IMAGE
mode(
task,
docker_image=docker_image,
use_gpu=use_gpu,
exp_prefix=exp_prefix,
script=script,
python_command=python_command,
sync_s3_pkl=sync_s3_pkl,
sync_log_on_termination=sync_log_on_termination,
periodic_sync=periodic_sync,
periodic_sync_interval=periodic_sync_interval,
sync_all_data_node_to_s3=sync_all_data_node_to_s3,
)
elif mode == "local":
for task in batch_tasks:
del task["remote_log_dir"]
env = task.pop("env", None)
command = to_local_command(
task,
python_command=python_command,
script=osp.join(config.PROJECT_PATH, script),
use_gpu=use_gpu
)
print(command)
if dry:
return
try:
if env is None:
env = dict()
subprocess.call(
command, shell=True, env=dict(os.environ, **env))
except Exception as e:
print(e)
if isinstance(e, KeyboardInterrupt):
raise
elif mode == "local_docker":
if docker_image is None:
docker_image = config.DOCKER_IMAGE
for task in batch_tasks:
del task["remote_log_dir"]
env = task.pop("env", None)
command = to_docker_command(
task, # these are the params. Pre and Post command can be here
docker_image=docker_image,
script=script,
env=env,
use_gpu=use_gpu,
use_tty=True,
python_command=python_command,
)
print(command)
if dry:
return
p = subprocess.Popen(command, shell=True)
try:
p.wait()
except KeyboardInterrupt:
try:
print("terminating")
p.terminate()
except OSError:
print("os error!")
pass
p.wait()
elif mode == "ec2":
if docker_image is None:
docker_image = config.DOCKER_IMAGE
s3_code_path = s3_sync_code(config, dry=dry, added_project_directories=added_project_directories)
launch_ec2(batch_tasks,
exp_prefix=exp_prefix,
docker_image=docker_image,
python_command=python_command,
script=script,
aws_config=aws_config,
dry=dry,
terminate_machine=terminate_machine,
use_gpu=use_gpu,
code_full_path=s3_code_path,
sync_s3_pkl=sync_s3_pkl,
sync_s3_png=sync_s3_png,
sync_s3_log=sync_s3_log,
sync_log_on_termination=sync_log_on_termination,
periodic_sync=periodic_sync,
periodic_sync_interval=periodic_sync_interval)
elif mode == "lab_kube":
# assert env is None
# first send code folder to s3
s3_code_path = s3_sync_code(config, dry=dry)
if docker_image is None:
docker_image = config.DOCKER_IMAGE
for task in batch_tasks:
# if 'env' in task:
# assert task.pop('env') is None
# TODO: dangerous when there are multiple tasks?
task["resources"] = params.pop(
"resources", config.KUBE_DEFAULT_RESOURCES)
task["node_selector"] = params.pop(
"node_selector", config.KUBE_DEFAULT_NODE_SELECTOR)
task["exp_prefix"] = exp_prefix
pod_dict = to_lab_kube_pod(
task, code_full_path=s3_code_path, docker_image=docker_image, script=script, is_gpu=use_gpu,
python_command=python_command,
sync_s3_pkl=sync_s3_pkl, periodic_sync=periodic_sync,
periodic_sync_interval=periodic_sync_interval,
sync_all_data_node_to_s3=sync_all_data_node_to_s3,
terminate_machine=terminate_machine,
)
pod_str = json.dumps(pod_dict, indent=1)
if dry:
print(pod_str)
dir = "{pod_dir}/{exp_prefix}".format(
pod_dir=config.POD_DIR, exp_prefix=exp_prefix)
ensure_dir(dir)
fname = "{dir}/{exp_name}.json".format(
dir=dir,
exp_name=task["exp_name"]
)
with open(fname, "w") as fh:
fh.write(pod_str)
kubecmd = "kubectl create -f %s" % fname
print(kubecmd)
if dry:
return
retry_count = 0
wait_interval = 1
while retry_count <= 5:
try:
return_code = subprocess.call(kubecmd, shell=True)
if return_code == 0:
break
retry_count += 1
print("trying again...")
time.sleep(wait_interval)
except Exception as e:
if isinstance(e, KeyboardInterrupt):
raise
print(e)
else:
raise NotImplementedError
_find_unsafe = re.compile(r'[a-zA-Z0-9_^@%+=:,./-]').search
def ensure_dir(dirname):
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise
def _shellquote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
def _to_param_val(v):
if v is None:
return ""
elif isinstance(v, list):
return " ".join(map(_shellquote, list(map(str, v))))
else:
return _shellquote(str(v))
def to_local_command(params, python_command="python", script=osp.join(config.PROJECT_PATH,
'scripts/run_experiment.py'),
use_gpu=False):
command = python_command + " " + script
if use_gpu and not config.USE_TF:
command = "THEANO_FLAGS='device=gpu,dnn.enabled=auto,floatX=float32' " + command
for k, v in config.ENV.items():
command = ("%s=%s " % (k, v)) + command
pre_commands = params.pop("pre_commands", None)
post_commands = params.pop("post_commands", None)
if pre_commands is not None or post_commands is not None:
print("Not executing the pre_commands: ", pre_commands, ", nor post_commands: ", post_commands)
for k, v in params.items():
if isinstance(v, dict):
for nk, nv in v.items():
if str(nk) == "_name":
command += " --%s %s" % (k, _to_param_val(nv))
else:
command += \
" --%s_%s %s" % (k, nk, _to_param_val(nv))
else:
command += " --%s %s" % (k, _to_param_val(v))
return command
def to_docker_command(params, docker_image, python_command="python", script='scripts/run_experiment_lite.py',
pre_commands=None, use_tty=False,
mujoco_path=None,
post_commands=None, dry=False, use_gpu=False, env=None, local_code_dir=None):
"""
:param params: The parameters for the experiment. If logging directory parameters are provided, we will create
docker volume mapping to make sure that the logging files are created at the correct locations
:param docker_image: docker image to run the command on
:param script: script command for running experiment
:return:
"""
log_dir = params.get("log_dir")
docker_args = params.pop("docker_args", "")
if pre_commands is None:
pre_commands = params.pop("pre_commands", None)
if post_commands is None:
post_commands = params.pop("post_commands", None)
if mujoco_path is None:
mujoco_path = config.MUJOCO_KEY_PATH
# script = 'rllab/' + script
# if not dry:
# create volume for logging directory
if use_gpu:
command_prefix = "nvidia-docker run"
else:
command_prefix = "docker run"
docker_log_dir = config.DOCKER_LOG_DIR
if env is None:
env = dict()
env = dict(
env,
AWS_ACCESS_KEY_ID=config.AWS_ACCESS_KEY,
AWS_SECRET_ACCESS_KEY=config.AWS_ACCESS_SECRET,
)
if env is not None:
for k, v in env.items():
command_prefix += " -e \"{k}={v}\"".format(k=k, v=v)
command_prefix += " -v {local_mujoco_key_dir}:{docker_mujoco_key_dir}".format(
local_mujoco_key_dir=mujoco_path, docker_mujoco_key_dir='/root/.mujoco')
command_prefix += " -v {local_log_dir}:{docker_log_dir}".format(
local_log_dir=log_dir,
docker_log_dir=docker_log_dir
)
command_prefix += docker_args
if local_code_dir is None:
local_code_dir = config.PROJECT_PATH
command_prefix += " -v {local_code_dir}:{docker_code_dir}".format(
local_code_dir=local_code_dir,
docker_code_dir=config.DOCKER_CODE_DIR
)
params = dict(params, log_dir=docker_log_dir)
if use_tty:
command_prefix += " -ti " + docker_image + " /bin/bash -c "
else:
command_prefix += " -i " + docker_image + " /bin/bash -c "
command_list = list()
if pre_commands is not None:
command_list.extend(pre_commands)
command_list.append("echo \"Running in docker\"")
command_list.append(to_local_command(
params, python_command=python_command, script=osp.join(config.DOCKER_CODE_DIR, script), use_gpu=use_gpu))
# We for 2 min sleep after termination to allow for last syncs.
if post_commands is None:
post_commands = ['sleep 120']
command_list.extend(post_commands)
return command_prefix + "'" + "; ".join(command_list) + "'"
def dedent(s):
lines = [l.strip() for l in s.split('\n')]
return '\n'.join(lines)
def launch_ec2(params_list, exp_prefix, docker_image, code_full_path,
python_command="python",
script='scripts/run_experiment.py',
aws_config=None, dry=False, terminate_machine=True, use_gpu=False, sync_s3_pkl=False,
sync_s3_png=False,
sync_s3_log=False,
sync_log_on_termination=True,
periodic_sync=True, periodic_sync_interval=15):
if len(params_list) == 0:
return
default_config = dict(
image_id=config.AWS_IMAGE_ID,
instance_type=config.AWS_INSTANCE_TYPE,
key_name=config.AWS_KEY_NAME,
spot=config.AWS_SPOT,
spot_price=config.AWS_SPOT_PRICE,
iam_instance_profile_name=config.AWS_IAM_INSTANCE_PROFILE_NAME,
security_groups=config.AWS_SECURITY_GROUPS,
security_group_ids=config.AWS_SECURITY_GROUP_IDS,
network_interfaces=config.AWS_NETWORK_INTERFACES,
)
if aws_config is None:
aws_config = dict()
aws_config = dict(default_config, **aws_config)
sio = StringIO()
sio.write("#!/bin/bash\n")
sio.write("{\n")
sio.write("""
die() { status=$1; shift; echo "FATAL: $*"; exit $status; }
""")
sio.write("""
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`"
""")
sio.write("""
aws ec2 create-tags --resources $EC2_INSTANCE_ID --tags Key=Name,Value={exp_name} --region {aws_region}
""".format(exp_name=params_list[0].get("exp_name"), aws_region=config.AWS_REGION_NAME))
if config.LABEL:
sio.write("""
aws ec2 create-tags --resources $EC2_INSTANCE_ID --tags Key=owner,Value={label} --region {aws_region}
""".format(label=config.LABEL, aws_region=config.AWS_REGION_NAME))
sio.write("""
aws ec2 create-tags --resources $EC2_INSTANCE_ID --tags Key=exp_prefix,Value={exp_prefix} --region {aws_region}
""".format(exp_prefix=exp_prefix, aws_region=config.AWS_REGION_NAME))
sio.write("""
service docker start
""")
sio.write("""
docker --config /home/ubuntu/.docker pull {docker_image}
""".format(docker_image=docker_image))
sio.write("""
export AWS_DEFAULT_REGION={aws_region}
""".format(aws_region=config.AWS_REGION_NAME))
if config.FAST_CODE_SYNC:
# sio.write("""
# aws s3 cp {code_full_path} /tmp/rllab_code.tar.gz --region {aws_region}
# """.format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR,
# aws_region=config.AWS_REGION_NAME))
sio.write("""
aws s3 cp {code_full_path} /tmp/rllab_code.tar.gz
""".format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR))
sio.write("""
mkdir -p {local_code_path}
""".format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR,
aws_region=config.AWS_REGION_NAME))
sio.write("""
tar -zxvf /tmp/rllab_code.tar.gz -C {local_code_path}
""".format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR,
aws_region=config.AWS_REGION_NAME))
else:
# sio.write("""
# aws s3 cp --recursive {code_full_path} {local_code_path} --region {aws_region}
# """.format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR,
# aws_region=config.AWS_REGION_NAME))
sio.write("""
aws s3 cp --recursive {code_full_path} {local_code_path}
""".format(code_full_path=code_full_path, local_code_path=config.DOCKER_CODE_DIR))
s3_mujoco_key_path = config.AWS_CODE_SYNC_S3_PATH + '/.mujoco/'
# sio.write("""
# aws s3 cp --recursive {} {} --region {}
# """.format(s3_mujoco_key_path, config.MUJOCO_KEY_PATH, config.AWS_REGION_NAME))
sio.write("""
aws s3 cp --recursive {} {}
""".format(s3_mujoco_key_path, config.MUJOCO_KEY_PATH))
sio.write("""
cd {local_code_path}
""".format(local_code_path=config.DOCKER_CODE_DIR))
for params in params_list:
log_dir = params.get("log_dir")
remote_log_dir = params.pop("remote_log_dir")
env = params.pop("env", None)
sio.write("""
aws ec2 create-tags --resources $EC2_INSTANCE_ID --tags Key=Name,Value={exp_name} --region {aws_region}
""".format(exp_name=params.get("exp_name"), aws_region=config.AWS_REGION_NAME))
sio.write("""
mkdir -p {log_dir}
""".format(log_dir=log_dir))
if periodic_sync:
include_png = " --include '*.png' " if sync_s3_png else " "
include_pkl = " --include '*.pkl' " if sync_s3_pkl else " "
include_log = " --include '*.log' " if sync_s3_log else " "
# sio.write("""
# while /bin/true; do
# aws s3 sync --exclude '*' {include_png} {include_pkl} {include_log}--include '*.csv' --include '*.json' {log_dir} {remote_log_dir} --region {aws_region}
# sleep {periodic_sync_interval}
# done & echo sync initiated""".format(include_png=include_png, include_pkl=include_pkl, include_log=include_log,
# log_dir=log_dir, remote_log_dir=remote_log_dir,
# aws_region=config.AWS_REGION_NAME,
# periodic_sync_interval=periodic_sync_interval))
sio.write("""
while /bin/true; do
aws s3 sync --exclude '*' {include_png} {include_pkl} {include_log}--include '*.csv' --include '*.json' {log_dir} {remote_log_dir}
sleep {periodic_sync_interval}
done & echo sync initiated""".format(include_png=include_png, include_pkl=include_pkl, include_log=include_log,
log_dir=log_dir, remote_log_dir=remote_log_dir,
periodic_sync_interval=periodic_sync_interval))
if sync_log_on_termination:
# sio.write("""
# while /bin/true; do
# if [ -z $(curl -Is http://169.254.169.254/latest/meta-data/spot/termination-time | head -1 | grep 404 | cut -d \ -f 2) ]
# then
# logger "Running shutdown hook."
# aws s3 cp /home/ubuntu/user_data.log {remote_log_dir}/stdout.log --region {aws_region}
# aws s3 cp --recursive {log_dir} {remote_log_dir} --region {aws_region}
# break
# else
# # Spot instance not yet marked for termination.
# sleep 5
# fi
# done & echo log sync initiated
# """.format(log_dir=log_dir, remote_log_dir=remote_log_dir, aws_region=config.AWS_REGION_NAME))
sio.write("""
while /bin/true; do
if [ -z $(curl -Is http://169.254.169.254/latest/meta-data/spot/termination-time | head -1 | grep 404 | cut -d \ -f 2) ]
then
logger "Running shutdown hook."
aws s3 cp /home/ubuntu/user_data.log {remote_log_dir}/stdout.log
aws s3 cp --recursive {log_dir} {remote_log_dir}
break
else
# Spot instance not yet marked for termination.
sleep 5
fi
done & echo log sync initiated
""".format(log_dir=log_dir, remote_log_dir=remote_log_dir))
if use_gpu:
sio.write("""
for i in {1..800}; do su -c "nvidia-modprobe -u -c=0" ubuntu && break || sleep 3; done
systemctl start nvidia-docker
""")
sio.write("""
{command}
""".format(command=to_docker_command(params, docker_image, python_command=python_command, script=script,
use_gpu=use_gpu, env=env,
local_code_dir=config.DOCKER_CODE_DIR)))
# sio.write("""
# aws s3 cp --recursive {log_dir} {remote_log_dir} --region {aws_region}
# """.format(log_dir=log_dir, remote_log_dir=remote_log_dir, aws_region=config.AWS_REGION_NAME))
sio.write("""
aws s3 cp --recursive {log_dir} {remote_log_dir}
""".format(log_dir=log_dir, remote_log_dir=remote_log_dir))
# sio.write("""
# aws s3 cp /home/ubuntu/user_data.log {remote_log_dir}/stdout.log --region {aws_region}
# """.format(remote_log_dir=remote_log_dir, aws_region=config.AWS_REGION_NAME))
sio.write("""
aws s3 cp /home/ubuntu/user_data.log {remote_log_dir}/stdout.log
""".format(remote_log_dir=remote_log_dir))
if terminate_machine:
sio.write("""
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
aws ec2 terminate-instances --instance-ids $EC2_INSTANCE_ID --region {aws_region}
""".format(aws_region=config.AWS_REGION_NAME))
sio.write("} >> /home/ubuntu/user_data.log 2>&1\n")
full_script = dedent(sio.getvalue())
import boto3
import botocore
if aws_config["spot"]:
ec2 = boto3.client(
"ec2",
region_name=config.AWS_REGION_NAME,
aws_access_key_id=config.AWS_ACCESS_KEY,
aws_secret_access_key=config.AWS_ACCESS_SECRET,
)
else:
ec2 = boto3.resource(
"ec2",
region_name=config.AWS_REGION_NAME,
aws_access_key_id=config.AWS_ACCESS_KEY,
aws_secret_access_key=config.AWS_ACCESS_SECRET,
)
if len(full_script) > 10000 or len(base64.b64encode(full_script.encode()).decode("utf-8")) > 10000:
# Script too long; need to upload script to s3 first.
# We're being conservative here since the actual limit is 16384 bytes
s3_path = upload_file_to_s3(full_script)
sio = StringIO()
sio.write("#!/bin/bash\n")
sio.write("""
aws s3 cp {s3_path} /home/ubuntu/remote_script.sh --region {aws_region} && \\
chmod +x /home/ubuntu/remote_script.sh && \\
bash /home/ubuntu/remote_script.sh
""".format(s3_path=s3_path, aws_region=config.AWS_REGION_NAME))
user_data = dedent(sio.getvalue())
else:
user_data = full_script
print(full_script)
with open("/tmp/full_script", "w") as f:
f.write(full_script)
instance_args = dict(
ImageId=aws_config["image_id"],
KeyName=aws_config["key_name"],
UserData=user_data,
InstanceType=aws_config["instance_type"],
EbsOptimized=config.EBS_OPTIMIZED,
SecurityGroups=aws_config["security_groups"],
SecurityGroupIds=aws_config["security_group_ids"],
NetworkInterfaces=aws_config["network_interfaces"],
IamInstanceProfile=dict(
Name=aws_config["iam_instance_profile_name"],
),
**config.AWS_EXTRA_CONFIGS,
)
if len(instance_args["NetworkInterfaces"]) > 0:
# disable_security_group = query_yes_no(
# "Cannot provide both network interfaces and security groups info. Do you want to disable security group settings?",
# default="yes",
# )
disable_security_group = True
if disable_security_group:
instance_args.pop("SecurityGroups")
instance_args.pop("SecurityGroupIds")
if aws_config.get("placement", None) is not None:
instance_args["Placement"] = aws_config["placement"]
if not aws_config["spot"]:
instance_args["MinCount"] = 1
instance_args["MaxCount"] = 1
print("************************************************************")
print(instance_args["UserData"])
print("************************************************************")
if aws_config["spot"]:
instance_args["UserData"] = base64.b64encode(instance_args["UserData"].encode()).decode("utf-8")
spot_args = dict(
DryRun=dry,
InstanceCount=1,
LaunchSpecification=instance_args,
SpotPrice=aws_config["spot_price"],
# ClientToken=params_list[0]["exp_name"],
)
import pprint
pprint.pprint(spot_args)
if not dry:
response = ec2.request_spot_instances(**spot_args)
print(response)
spot_request_id = response['SpotInstanceRequests'][
0]['SpotInstanceRequestId']
for _ in range(10):
try:
ec2.create_tags(
Resources=[spot_request_id],
Tags=[
{'Key': 'Name', 'Value': params_list[0]["exp_name"]}
],
)
break
except botocore.exceptions.ClientError:
continue
else:
import pprint
pprint.pprint(instance_args)
ec2.create_instances(
DryRun=dry,
**instance_args
)
S3_CODE_PATH = None
def s3_sync_code(config, dry=False, added_project_directories=[]):
global S3_CODE_PATH
if S3_CODE_PATH is not None:
return S3_CODE_PATH
base = config.AWS_CODE_SYNC_S3_PATH
has_git = True
if config.FAST_CODE_SYNC:
try:
current_commit = subprocess.check_output(
["git", "rev-parse", "HEAD"]).strip().decode("utf-8")
except subprocess.CalledProcessError as _:
print("Warning: failed to execute git commands")
current_commit = None
file_name = str(timestamp) + "_" + hashlib.sha224(
subprocess.check_output(["pwd"]) + str(current_commit).encode() + str(timestamp).encode()
).hexdigest() + ".tar.gz"
file_path = "/tmp/" + file_name
tar_cmd = ["tar", "-zcvf", file_path, "-C", config.PROJECT_PATH]
for pattern in config.FAST_CODE_SYNC_IGNORES:
tar_cmd += ["--exclude", pattern]
tar_cmd += ["-h", "."]
for path in added_project_directories:
tar_cmd.append("-C")
tar_cmd.append(path)
tar_cmd += ["."]
remote_path = "%s/%s" % (base, file_name)
upload_cmd = ["aws", "s3", "cp", file_path, remote_path]
mujoco_key_cmd = [
"aws", "s3", "sync", config.MUJOCO_KEY_PATH, "{}/.mujoco/".format(base)]
print(" ".join(tar_cmd))
print(" ".join(upload_cmd))
print(" ".join(mujoco_key_cmd))
if not dry:
subprocess.check_call(tar_cmd)
subprocess.check_call(upload_cmd)
try:
subprocess.check_call(mujoco_key_cmd)
except Exception as e:
print(e)
S3_CODE_PATH = remote_path
return remote_path
else:
try:
current_commit = subprocess.check_output(
["git", "rev-parse", "HEAD"]).strip().decode("utf-8")
clean_state = len(
subprocess.check_output(["git", "status", "--porcelain"])) == 0
except subprocess.CalledProcessError as _:
print("Warning: failed to execute git commands")
has_git = False
dir_hash = base64.b64encode(subprocess.check_output(["pwd"])).decode("utf-8")
code_path = "%s_%s" % (
dir_hash,
(current_commit if clean_state else "%s_dirty_%s" % (current_commit, timestamp)) if
has_git else timestamp
)
full_path = "%s/%s" % (base, code_path)
cache_path = "%s/%s" % (base, dir_hash)
cache_cmds = ["aws", "s3", "cp", "--recursive"] + \
flatten(["--exclude", "%s" % pattern] for pattern in config.CODE_SYNC_IGNORES) + \
[cache_path, full_path]
cmds = ["aws", "s3", "cp", "--recursive"] + \
flatten(["--exclude", "%s" % pattern] for pattern in config.CODE_SYNC_IGNORES) + \
[".", full_path]
caching_cmds = ["aws", "s3", "cp", "--recursive"] + \
flatten(["--exclude", "%s" % pattern] for pattern in config.CODE_SYNC_IGNORES) + \
[full_path, cache_path]
mujoco_key_cmd = [
"aws", "s3", "sync", config.MUJOCO_KEY_PATH, "{}/.mujoco/".format(base)]
print(cache_cmds, cmds, caching_cmds, mujoco_key_cmd)
if not dry:
subprocess.check_call(cache_cmds)
subprocess.check_call(cmds)
subprocess.check_call(caching_cmds)
try:
subprocess.check_call(mujoco_key_cmd)
except Exception:
print('Unable to sync mujoco keys!')
S3_CODE_PATH = full_path
return full_path
def upload_file_to_s3(script_content):
import tempfile
import uuid
f = tempfile.NamedTemporaryFile(delete=False)
f.write(script_content.encode())
f.close()
remote_path = os.path.join(
config.AWS_CODE_SYNC_S3_PATH, "oversize_bash_scripts", str(uuid.uuid4()))
subprocess.check_call(["aws", "s3", "cp", f.name, remote_path])
os.unlink(f.name)
return remote_path
def to_lab_kube_pod(
params, docker_image, code_full_path,
python_command="python",
script='scripts/run_experiment.py',
is_gpu=False,
sync_s3_pkl=False,
periodic_sync=True,
periodic_sync_interval=15,
sync_all_data_node_to_s3=False,
terminate_machine=True
):
"""
:param params: The parameters for the experiment. If logging directory parameters are provided, we will create
docker volume mapping to make sure that the logging files are created at the correct locations
:param docker_image: docker image to run the command on
:param script: script command for running experiment
:return:
"""
log_dir = params.get("log_dir")
remote_log_dir = params.pop("remote_log_dir")
resources = params.pop("resources")
node_selector = params.pop("node_selector")
exp_prefix = params.pop("exp_prefix")
kube_env = [
{"name": k, "value": v}
for k, v in (params.pop("env", None) or dict()).items()
]
mkdir_p(log_dir)
pre_commands = list()
pre_commands.append('mkdir -p ~/.aws')
pre_commands.append('mkdir ~/.mujoco')
# fetch credentials from the kubernetes secret file
pre_commands.append('echo "[default]" >> ~/.aws/credentials')
pre_commands.append(
"echo \"aws_access_key_id = %s\" >> ~/.aws/credentials" % config.AWS_ACCESS_KEY)
pre_commands.append(
"echo \"aws_secret_access_key = %s\" >> ~/.aws/credentials" % config.AWS_ACCESS_SECRET)
s3_mujoco_key_path = config.AWS_CODE_SYNC_S3_PATH + '/.mujoco/'
pre_commands.append(
'aws s3 cp --recursive {} {}'.format(s3_mujoco_key_path, '~/.mujoco'))
if config.FAST_CODE_SYNC:
pre_commands.append('aws s3 cp %s /tmp/rllab_code.tar.gz' % code_full_path)
pre_commands.append('mkdir -p %s' % config.DOCKER_CODE_DIR)
pre_commands.append('tar -zxvf /tmp/rllab_code.tar.gz -C %s' % config.DOCKER_CODE_DIR)
else:
pre_commands.append('aws s3 cp --recursive %s %s' %
(code_full_path, config.DOCKER_CODE_DIR))
pre_commands.append('cd %s' % config.DOCKER_CODE_DIR)
pre_commands.append('mkdir -p %s' %
(log_dir))
if sync_all_data_node_to_s3:
print('Syncing all data from node to s3.')
if periodic_sync:
if sync_s3_pkl:
pre_commands.append("""
while /bin/true; do
aws s3 sync {log_dir} {remote_log_dir} --region {aws_region} --quiet
sleep {periodic_sync_interval}
done & echo sync initiated""".format(log_dir=log_dir, remote_log_dir=remote_log_dir,
aws_region=config.AWS_REGION_NAME,
periodic_sync_interval=periodic_sync_interval))
else:
pre_commands.append("""
while /bin/true; do
aws s3 sync {log_dir} {remote_log_dir} --region {aws_region} --quiet
sleep {periodic_sync_interval}
done & echo sync initiated""".format(log_dir=log_dir, remote_log_dir=remote_log_dir,
aws_region=config.AWS_REGION_NAME,
periodic_sync_interval=periodic_sync_interval))
else:
if periodic_sync:
if sync_s3_pkl:
pre_commands.append("""
while /bin/true; do
aws s3 sync --exclude '*' --include '*.csv' --include '*.json' --include '*.pkl' {log_dir} {remote_log_dir} --region {aws_region} --quiet
sleep {periodic_sync_interval}
done & echo sync initiated""".format(log_dir=log_dir, remote_log_dir=remote_log_dir,
aws_region=config.AWS_REGION_NAME,
periodic_sync_interval=periodic_sync_interval))
else:
pre_commands.append("""
while /bin/true; do
aws s3 sync --exclude '*' --include '*.csv' --include '*.json' {log_dir} {remote_log_dir} --region {aws_region} --quiet
sleep {periodic_sync_interval}
done & echo sync initiated""".format(log_dir=log_dir, remote_log_dir=remote_log_dir,
aws_region=config.AWS_REGION_NAME,
periodic_sync_interval=periodic_sync_interval))
# copy the file to s3 after execution
post_commands = list()
post_commands.append('aws s3 cp --recursive %s %s' %
(log_dir,
remote_log_dir))
if not terminate_machine:
post_commands.append('sleep infinity')
command_list = list()
if pre_commands is not None:
command_list.extend(pre_commands)
command_list.append("echo \"Running in docker\"")
command_list.append(
"%s 2>&1 | tee -a %s" % (
to_local_command(params, python_command=python_command, script=script),
"%s/stdouterr.log" % log_dir
)
)
if post_commands is not None:
command_list.extend(post_commands)
command = "; ".join(command_list)
pod_name = config.KUBE_PREFIX + params["exp_name"]
# underscore is not allowed in pod names
pod_name = pod_name.replace("_", "-")
print("Is gpu: ", is_gpu)
if not is_gpu:
return {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": pod_name,
"labels": {
"owner": config.LABEL,
"expt": pod_name,
"exp_time": timestamp,
"exp_prefix": exp_prefix,
},
},
"spec": {
"containers": [
{
"name": "foo",
"image": docker_image,
"command": [
"/bin/bash",
"-c",
"-li", # to load conda env file
command,
],
"resources": resources,
"imagePullPolicy": "Always",
}
],
"restartPolicy": "Never",
"nodeSelector": node_selector,
"dnsPolicy": "Default",
}
}
return {
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": pod_name,
"labels": {
"owner": config.LABEL,
"expt": pod_name,
"exp_time": timestamp,
"exp_prefix": exp_prefix,
},
},
"spec": {
"containers": [
{
"name": "foo",
"image": docker_image,
"env": kube_env,
"command": [
"/bin/bash",
"-c",
"-li", # to load conda env file
command,
],
"resources": resources,
"imagePullPolicy": "Always",
# gpu specific
"volumeMounts": [
{
"name": "nvidia",
"mountPath": "/usr/local/nvidia",
"readOnly": True,
}
],
"securityContext": {
"privileged": True,
}
}
],
"volumes": [
{
"name": "nvidia",
"hostPath": {
"path": "/var/lib/docker/volumes/nvidia_driver_352.63/_data",
}
}
],
"restartPolicy": "Never",
"nodeSelector": node_selector,
"dnsPolicy": "Default",
}
}
def concretize(maybe_stub):
if isinstance(maybe_stub, StubMethodCall):
obj = concretize(maybe_stub.obj)
method = getattr(obj, maybe_stub.method_name)
args = concretize(maybe_stub.args)
kwargs = concretize(maybe_stub.kwargs)
return method(*args, **kwargs)
elif isinstance(maybe_stub, StubClass):
return maybe_stub.proxy_class
elif isinstance(maybe_stub, StubAttr):
obj = concretize(maybe_stub.obj)
attr_name = maybe_stub.attr_name
attr_val = getattr(obj, attr_name)
return concretize(attr_val)
elif isinstance(maybe_stub, StubObject):
if not hasattr(maybe_stub, "__stub_cache"):
args = concretize(maybe_stub.args)
kwargs = concretize(maybe_stub.kwargs)
try:
maybe_stub.__stub_cache = maybe_stub.proxy_class(
*args, **kwargs)
except Exception as e:
print(("Error while instantiating %s" % maybe_stub.proxy_class))
import traceback
traceback.print_exc()
ret = maybe_stub.__stub_cache
return ret
elif isinstance(maybe_stub, dict):
# make sure that there's no hidden caveat
ret = dict()
for k, v in maybe_stub.items():
ret[concretize(k)] = concretize(v)
return ret
elif isinstance(maybe_stub, (list, tuple)):
return maybe_stub.__class__(list(map(concretize, maybe_stub)))
else:
return maybe_stub
| suffix = []
for k, vs, cfg in self._variants:
if not cfg.get("hide", False):
suffix.append(k + "_" + str(variant[k]))
return "_".join(suffix) |
main.rs | #![feature(result_flattening, try_blocks, iter_intersperse)]
use std::fs::File;
use crate::{
config::Config,
drawing::{pdf_maker::PdfMaker, DrawError, Drawer},
parser::Content,
};
mod cli_args;
mod config;
mod drawing;
mod parser;
mod util;
fn main() -> Result<(), DrawError> {
let args = cli_args::get();
let mut config = Config::builder()
.with_style(args.style)
.with_templates(args.templates)
.build(&args.doc_name);
let source = std::fs::read_to_string(args.present_file).unwrap();
let slides = parser::parse(&source);
let mut pdf = PdfMaker::with_config(&config).expect("couldn't get the pdfmaker");
for slide in slides {
match slide.kind.as_str() {
"Style" => {
let path = slide
.contents
.into_iter()
.next() | _ => None,
})
.flatten()
.expect("expected path to a style sheet");
config
.change_style(path)
.expect("Couldn't load style sheet");
}
_ => pdf
.create_slide(slide, &config)
.expect("Could not create the slides due to"),
}
}
let file = File::create(args.output).expect("couldn't open file");
pdf.write(file)
} | .map(|c| match c {
Content::Config(p) => Some(p), |
contacts.js | 'use stricts';
/**
* Just a couple of testing tools for the Contacts app.
*
* Right now, it just allows you to insert a large number of fake contacts
* into the database, and then clear the database.
*/
var ContactsTest = {
get loadButton() {
delete this.loadButton;
return this.loadButton = document.getElementById('insert-contacts');
},
get clearButton() {
delete this.clearButton;
return this.clearButton = document.getElementById('clear-contacts');
},
get getButton() {
delete this.getButton;
return this.getButton = document.getElementById('get-contacts');
},
get pickActivityButton() {
delete this.pickActivityButton;
return this.pickActivityButton = document.getElementById('activities-pick');
},
get newActivityButton() {
delete this.newActivityButton;
return this.newActivityButton = document.getElementById('activities-new');
},
get newWithDataActivityButton() {
delete this.newWithDataActivityButton;
return this.newWithDataActivityButton =
document.getElementById('activities-new-data');
},
get insertSocialContacts() {
delete this.insertSocialContacts;
return this.insertSocialContacts =
document.getElementById('insert-social-contacts');
},
init: function ct_init() {
this.loadButton.addEventListener('click', this.loadContacts.bind(this));
this.clearButton.addEventListener('click', this.clearContacts.bind(this));
this.getButton.addEventListener('click', this.getContacts.bind(this));
this.pickActivityButton.addEventListener('click',
this.pickActivity.bind(this));
this.newActivityButton.addEventListener('click',
this.newActivity.bind(this));
this.newWithDataActivityButton.addEventListener('click',
this.newWithDataActivity.bind(this));
this.insertSocialContacts.addEventListener('click',
this.finsertSocialContacts.bind(this));
},
uninit: function ct_uninit() {
this.loadButton.removeEventListener('click', this.loadContacts.bind(this));
this.clearButton.removeEventListener('click',
this.clearContacts.bind(this));
this.getButton.removeEventListener('click', this.getContacts.bind(this));
this.newActivityButton.removeEventListener('click',
this.newActivity.bind(this));
},
clearContacts: function ct_clearContacts() {
if (!confirm('This will wipe out ALL of the contacts in the database. ' +
'Are you sure?'))
return;
// Ok, we're really doing this.
var req = window.navigator.mozContacts.clear();
req.onsuccess = function() {
alert('Contacts deleted.');
};
req.onerror = function() {
alert('Problem deleting contacts');
};
},
getContacts: function ct_getContacts() {
var options = {
sortBy: 'familyName',
sortOrder: 'ascending'
};
var start = new Date();
var req = window.navigator.mozContacts.find(options);
req.onsuccess = function() {
var duration = new Date() - start;
alert('Contacts received: ' + duration + 'msec');
};
req.onerror = function() {
alert('Problem receiving contacts');
};
},
setContactId: function ct_setContactId(id) {
this.contactId = id;
},
getContactId: function ct_getContactId() {
return this.contactId;
},
pickActivity: function ct_pickActivity() {
var activity = new MozActivity({
name: 'pick',
data: {
type: 'webcontacts/contact'
}
});
var self = this;
activity.onsuccess = function() {
var number = this.result.number;
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'Picked contact with number: ' + number;
var app = evt.target.result;
app.launch();
};
};
activity.onerror = function() {
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'Activity canceled';
var app = evt.target.result;
app.launch();
};
};
},
newActivity: function ct_newActivity() {
var activity = new MozActivity({
name: 'new',
data: {
type: 'webcontacts/contact'
}
});
var self = this;
activity.onsuccess = function() {
var contact = this.result.contact;
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'New contact' + ' create with id: ' + contact.id;
self.setContactId(contact.id);
var app = evt.target.result;
app.launch();
};
};
activity.onerror = function() {
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'Activity canceled';
var app = evt.target.result;
app.launch();
};
};
}, | data: {
type: 'webcontacts/contact',
params: {
'tel': '555-555-555',
'email': '[email protected]',
'address': 'San Francisco',
'note': 'This is a note',
'giveName': 'John',
'familyName': 'Orlock',
'company': 'Lost Industries'
}
}
});
var self = this;
activity.onsuccess = function() {
var contact = this.result.contact;
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'New contact' + ' create with id: ' + contact.id;
self.setContactId(contact.id);
var app = evt.target.result;
app.launch();
};
};
activity.onerror = function() {
navigator.mozApps.getSelf().onsuccess = function getSelfCB(evt) {
document.getElementById('activities-result').innerHTML =
'Activity canceled';
var app = evt.target.result;
app.launch();
};
};
},
loadContacts: function ct_loadContacts() {
var req = new XMLHttpRequest();
req.overrideMimeType('application/json');
req.open('GET', '../data/fakecontacts/fakecontacts.json', true);
req.onreadystatechange = function() {
// We will get a 0 status if the app is in app://
if (req.readyState === 4 && (req.status === 200 ||
req.status === 0)) {
var contacts = JSON.parse(req.responseText);
this._insertContacts(contacts);
}
}.bind(this);
this.loadButton.disabled = true;
req.send(null);
},
_insertContacts: function ct_insertContacts(aContacts) {
var self = this;
var cs = new ContactsSaver(aContacts);
cs.start();
cs.onsuccess = function() {
self.loadButton.disabled = false;
}
cs.onsaved = function(n) {
self._setInsertionCount(n, aContacts.length);
}
cs.onerror = function(c, e) {
Components.utils.reportError('Could not add contact with name: ' +
c.familyName[0]);
}
},
_setInsertionCount: function ct__setInsertionCount(aSoFar, aTotal) {
var insertionEl = document.getElementById('insertion-count');
insertionEl.textContent = aSoFar + ' / ' + aTotal;
},
_error: function ct__error(c) {
Components.utils.reportError('Could not add contact with name: ' +
c.familyName[0]);
},
finsertSocialContacts: function ct_finsertSocialContacts() {
var xhr = new XMLHttpRequest();
xhr.overrideMimeType('application/json');
xhr.open('GET', '../data/fakesocialcontacts/contacts_social.json', true);
xhr.onload = function(e) {
// We will get a 0 status if the app is in app://
if (xhr.status === 200 || xhr.status === 0) {
var cdata = JSON.parse(xhr.responseText);
this._insertSocialContacts(cdata.data);
}
}.bind(this);
xhr.send(null);
},
_insertSocialContacts: function ct__insertSocialContacts(contacts) {
var cs = new ContactsSaver(contacts);
cs.start();
var self = this;
cs.onsuccess = function() { window.alert('Added!'); }
cs.onerror = function(e, c) {
self._error(c);
}
}
};
window.addEventListener('load', ContactsTest.init.bind(ContactsTest));
window.addEventListener('unload', ContactsTest.uninit.bind(ContactsTest)); |
newWithDataActivity: function ct_newActivity() {
var activity = new MozActivity({
name: 'new', |
events.go | package events
import (
"fmt"
goChargify "github.com/GetWagz/go-chargify"
"github.com/GetWagz/go-chargify/example/cli/cmd/subscriptions/shared"
"github.com/GetWagz/go-chargify/example/cli/internal"
"github.com/GetWagz/go-chargify/example/cli/internal/utils"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var command = &cobra.Command{
Use: "events",
Short: "query subscriptions events",
PersistentPreRunE: utils.ParentPersistentPreRunE,
PreRunE: preRunE,
RunE: func(cmd *cobra.Command, args []string) error {
return execute()
},
}
type optionalListSubscriptionEventsQueryParams struct {
Page int `json:"page,omitempty" mapstructure:"page,omitempty"`
PerPage int `json:"per_page,omitempty" mapstructure:"per_page,omitempty"`
SinceID int `json:"since_id,omitempty" mapstructure:"since_id,omitempty"`
MaxID int `json:"max_id,omitempty" mapstructure:"max_id,omitempty"`
Direction string `json:"direction,omitempty" mapstructure:"direction,omitempty"`
Filter string `json:"filter,omitempty" mapstructure:"filter,omitempty"`
}
var optionalQueryParams = optionalListSubscriptionEventsQueryParams{}
var listEventQueryParams = goChargify.ListSubscriptionEventsQueryParams{}
func preRunE(cmd *cobra.Command, args []string) error |
func Init(rootCmd *cobra.Command) {
rootCmd.AddCommand(command)
// page
command.Flags().IntVar(&optionalQueryParams.Page, "page", internal.NotSetIntParam, "page, i.e. 1 or above")
// per-page
command.Flags().IntVar(&optionalQueryParams.PerPage, "per-page", internal.NotSetIntParam, "per-page, i.e. 1 or above")
// since_id
command.Flags().IntVar(&optionalQueryParams.SinceID, "since_id", internal.NotSetIntParam, "since_id, i.e. 1 or above")
// max_id
command.Flags().IntVar(&optionalQueryParams.MaxID, "max_id", internal.NotSetIntParam, "max_id, i.e. 1 or above")
// direction
command.Flags().StringVar(&optionalQueryParams.Direction, "direction", internal.NotSetStringParam, "asc,desc")
// filter
command.Flags().StringVar(&optionalQueryParams.Filter, "filter", internal.NotSetStringParam, "filter")
}
func execute() error {
apiKey := viper.Get("chargify-api-key")
log.Debug().Str("api-key", apiKey.(string)).Send()
log.Debug().Int("", shared.SubscriptionID).Interface("listEventQueryParams", listEventQueryParams).Send()
fmt.Printf("products/%v", shared.SubscriptionID)
found, err := goChargify.ListSubscriptionEvents(shared.SubscriptionID, &listEventQueryParams)
if err != nil {
return err
}
fmt.Println(utils.PrettyJSON(found))
return nil
}
| {
if optionalQueryParams.Page != internal.NotSetIntParam {
listEventQueryParams.Page = &optionalQueryParams.Page
}
if optionalQueryParams.PerPage != internal.NotSetIntParam {
listEventQueryParams.PerPage = &optionalQueryParams.PerPage
}
if optionalQueryParams.SinceID != internal.NotSetIntParam {
listEventQueryParams.SinceID = &optionalQueryParams.SinceID
}
if optionalQueryParams.MaxID != internal.NotSetIntParam {
listEventQueryParams.MaxID = &optionalQueryParams.MaxID
}
if optionalQueryParams.Direction != internal.NotSetStringParam {
if !(optionalQueryParams.Direction == "asc" || optionalQueryParams.Direction == "desc") {
return fmt.Errorf("--direction must be asc or desc")
}
listEventQueryParams.Direction = &optionalQueryParams.Direction
}
if optionalQueryParams.Filter != internal.NotSetStringParam {
listEventQueryParams.Filter = &optionalQueryParams.Filter
}
return nil
} |
knownsec.py | #!/usr/bin/env python
NAME = 'KS-WAF (KnownSec)'
def | (self):
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, page = r
if b'/ks-waf-error.png' in page:
return True
return False | is_waf |
resultsServices.ts | import { AxiosResponse, AxiosError } from 'axios';
import { api } from 'utils/api';
import { ServerError } from 'typings/utils.typings';
import { GetResultsResponse } from 'typings/result.typings';
export const getResults = async (
startTime: string
): Promise<GetResultsResponse | ServerError> => {
let response: AxiosResponse;
try { | },
});
} catch (error) {
if (error?.response) {
const axiosError: AxiosError<ServerError> = error;
if (axiosError.response) return axiosError.response.data;
}
throw error;
}
return response.data;
}; | response = await api.get<GetResultsResponse>('/results', {
params: {
startTime, |
lib.rs | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use consts::*;
use helloworld::*;
use wasmlib::*; | mod consts;
mod helloworld;
#[no_mangle]
fn on_load() {
let exports = ScExports::new();
exports.add_func(FUNC_HELLO_WORLD, func_hello_world);
exports.add_view(VIEW_GET_HELLO_WORLD, view_get_hello_world);
} | |
reader.go | /*
* Copyright 2020 Saffat Technologies, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except 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 agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package wal
import (
"encoding/binary"
"errors"
"github.com/unit-io/bpool"
"github.com/unit-io/unitdb/uid"
)
// Reader reads logs from WAL.
// Reader reader is a simple iterator over log data.
type Reader struct {
Id uid.LID
offset int64
entryCount uint32
buffer *bpool.Buffer
wal *WAL
}
// NewReader returns new log reader to read the logs from the WAL.
func (wal *WAL) NewReader() (*Reader, error) {
if err := wal.ok(); err != nil {
return &Reader{wal: wal}, err
}
r := &Reader{
Id: uid.NewLID(),
wal: wal,
}
return r, nil
}
// Iterator iterates the pending logs from the WAL.
func (r *Reader) Iterator(f func(timeID int64) (bool, error)) (err error) {
r.wal.mu.RLock()
r.buffer = r.wal.bufPool.Get()
defer func() {
r.wal.recoveredTimeIDs = r.wal.recoveredTimeIDs[:0]
r.wal.bufPool.Put(r.buffer)
r.wal.mu.RUnlock()
}()
for _, timeID := range r.wal.recoveredTimeIDs {
r.offset = 0
r.buffer.Reset()
info := r.wal.logStore.read(timeID, r.buffer)
r.entryCount = info.count
if stop, err := f(timeID); stop || err != nil {
return err
} | }
return nil
}
// Count returns entry count for the current interation.
func (r *Reader) Count() uint32 {
return r.entryCount
}
// Next returns next record from the iterator or false if iteration is done.
func (r *Reader) Next() ([]byte, bool, error) {
if r.entryCount == 0 {
return nil, false, nil
}
r.entryCount--
scratch, _ := r.buffer.Slice(r.offset, r.offset+4)
dataLen := binary.LittleEndian.Uint32(scratch)
data, err := r.buffer.Slice(r.offset+4, r.offset+int64(dataLen))
if err != nil {
return nil, false, errors.New("error reading log")
}
r.offset += int64(dataLen)
return data, true, nil
} | |
faSocks.js | "use strict";
Object.defineProperty(exports, "__esModule", {value: true});
var prefix = "fas"; | var width = 512;
var height = 512;
var ligatures = [];
var unicode = "f696";
var svgPathData = "M214.66 311.01L288 256V96H128v176l-86.65 64.61c-39.4 29.56-53.86 84.42-29.21 127.06C30.39 495.25 63.27 512 96.08 512c20.03 0 40.25-6.25 57.52-19.2l21.86-16.39c-29.85-55.38-13.54-125.84 39.2-165.4zM288 32c0-11.05 3.07-21.3 8.02-30.38C293.4.92 290.85 0 288 0H160c-17.67 0-32 14.33-32 32v32h160V32zM480 0H352c-17.67 0-32 14.33-32 32v32h192V32c0-17.67-14.33-32-32-32zM320 272l-86.13 64.61c-39.4 29.56-53.86 84.42-29.21 127.06 18.25 31.58 50.61 48.33 83.42 48.33 20.03 0 40.25-6.25 57.52-19.2l115.2-86.4A127.997 127.997 0 0 0 512 304V96H320v176z";
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]
};
exports.faSocks = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | var iconName = "socks"; |
locations.py | """Locations where we look for configs, install stuff, etc"""
from __future__ import absolute_import
import os
import os.path
import site
import sys
from distutils import sysconfig
from distutils.command.install import install, SCHEME_KEYS # noqa
from pip.compat import WINDOWS, expanduser
from pip.utils import appdirs
# Application Directories
USER_CACHE_DIR = appdirs.user_cache_dir("pip")
DELETE_MARKER_MESSAGE = """\
This file is placed here by pip to indicate the source was put
here by pip.
Once this package is successfully installed this source code will be
deleted (unless you remove this file).
"""
PIP_DELETE_MARKER_FILENAME = "pip-delete-this-directory.txt"
def write_delete_marker_file(directory):
"""
Write the pip delete marker file into this directory.
"""
filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME)
with open(filepath, "w") as marker_fp:
marker_fp.write(DELETE_MARKER_MESSAGE)
def running_under_virtualenv():
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, "real_prefix"):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
return False
def virtualenv_no_global():
"""
Return True if in a venv and no system site packages.
"""
# this mirrors the logic in virtualenv.py for locating the
# no-global-site-packages.txt file
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, "no-global-site-packages.txt")
if running_under_virtualenv() and os.path.isfile(no_global_file):
return True
if running_under_virtualenv():
src_prefix = os.path.join(sys.prefix, "src")
else:
# FIXME: keep src in cwd for now (it is not a temporary folder)
try:
src_prefix = os.path.join(os.getcwd(), "src")
except OSError:
# In case the current working directory has been renamed or deleted
sys.exit("The folder you are executing pip from can no longer be found.")
# under macOS + virtualenv sys.prefix is not properly resolved
# it is something like /path/to/python/bin/..
# Note: using realpath due to tmp dirs on OSX being symlinks
src_prefix = os.path.abspath(src_prefix)
# FIXME doesn't account for venv linked to global site-packages
site_packages = sysconfig.get_python_lib()
user_site = site.USER_SITE
user_dir = expanduser("~")
if WINDOWS:
bin_py = os.path.join(sys.prefix, "Scripts")
bin_user = os.path.join(user_site, "Scripts")
# buildout uses 'bin' on Windows too?
if not os.path.exists(bin_py):
bin_py = os.path.join(sys.prefix, "bin")
bin_user = os.path.join(user_site, "bin")
config_basename = "pip.ini"
legacy_storage_dir = os.path.join(user_dir, "pip")
legacy_config_file = os.path.join(
legacy_storage_dir,
config_basename,
)
else:
bin_py = os.path.join(sys.prefix, "bin")
bin_user = os.path.join(user_site, "bin")
config_basename = "pip.conf"
legacy_storage_dir = os.path.join(user_dir, ".pip")
legacy_config_file = os.path.join(
legacy_storage_dir,
config_basename,
)
# Forcing to use /usr/local/bin for standard macOS framework installs
# Also log to ~/Library/Logs/ for use with the Console.app log viewer
if sys.platform[:6] == "darwin" and sys.prefix[:16] == "/System/Library/":
bin_py = "/usr/local/bin"
site_config_files = [
os.path.join(path, config_basename) for path in appdirs.site_config_dirs("pip")
]
def distutils_scheme(
dist_name, user=False, home=None, root=None, isolated=False, prefix=None
):
"""
Return a distutils install scheme
"""
from distutils.dist import Distribution
scheme = {}
if isolated:
extra_dist_args = {"script_args": ["--no-user-cfg"]}
else:
extra_dist_args = {}
dist_args = {"name": dist_name}
dist_args.update(extra_dist_args)
d = Distribution(dist_args)
d.parse_config_files()
i = d.get_command_obj("install", create=True)
# NOTE: setting user or home has the side-effect of creating the home dir
# or user base for installations during finalize_options()
# ideally, we'd prefer a scheme class that has no side-effects.
assert not (user and prefix), "user={0} prefix={1}".format(user, prefix)
i.user = user or i.user
if user:
i.prefix = ""
i.prefix = prefix or i.prefix
i.home = home or i.home
i.root = root or i.root
i.finalize_options()
for key in SCHEME_KEYS:
scheme[key] = getattr(i, "install_" + key)
# install_lib specified in setup.cfg should install *everything*
# into there (i.e. it takes precedence over both purelib and
# platlib). Note, i.install_lib is *always* set after
# finalize_options(); we only want to override here if the user
# has explicitly requested it hence going back to the config
if "install_lib" in d.get_option_dict("install"):
scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib)) | "include",
"site",
"python" + sys.version[:3],
dist_name,
)
if root is not None:
path_no_drive = os.path.splitdrive(os.path.abspath(scheme["headers"]))[1]
scheme["headers"] = os.path.join(
root,
path_no_drive[1:],
)
return scheme |
if running_under_virtualenv():
scheme["headers"] = os.path.join(
sys.prefix, |
cloudconfig_test.go | // Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except 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 agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cloudinit
import (
"testing"
)
func TestSCloudConfig_UserData(t *testing.T) {
usr1 := NewUser("root")
usr1.SshKey("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCa4E8wmIOlmh1G8ZRcU2zpnl2frD2lLKdXpbTeUUZEKYFFlYM8TM5UrKrqrMCd3rFjaYGTKWiQwOiWroXlAXausbbVEI29KY+1Vd26qNyejj+CZO9MCj0naIrqa1V0of3TQY5I2U+ToIkyLqVFWhWVa57v/GUxsV2aNTmUS/qz0OPSCFPbGWWB35rsjwnFwq2jF6E8yJgTGDTYZcsghRi3IWfyfeHbSuWdvn6N8XrPBDmNg7h+GSvO6FJlp6MUw1hscECi13GwqXYgJnLG5RMiFH6s0vhozyHkue1vOTcryPHRQD0Jz/INUSaggH8L1HnYSUavOf4Cw25W9HfzgUBf")
usr2 := NewUser("yunion")
usr2.Password("123@yunion").SudoPolicy(USER_SUDO_NOPASSWD)
file1 := NewWriteFile("/etc/ansible/hosts", "gobuild\ncloudev\n", "", "", true)
file2 := NewWriteFile("/etc/hosts", "127.0.0.1 localhost\n", "", "", false)
config := SCloudConfig{
Users: []SUser{
usr1,
usr2,
},
WriteFiles: []SWriteFile{
file1,
file2,
},
Runcmd: []string{
"mkdir /var/run/httpd", | DisableRoot: 0,
SshPwauth: SSH_PASSWORD_AUTH_ON,
}
userData := config.UserData()
t.Logf("%s", userData)
config2, err := ParseUserData(userData)
if err != nil {
t.Errorf("%s", err)
} else {
userData2 := config2.UserData()
t.Logf("%s", userData2)
if userData != userData2 {
t.Errorf("userData not equal to userData2")
}
}
t.Log(config2.UserDataScript())
} | },
PhoneHome: &SPhoneHome{
Url: "http://www.yunion.io/$INSTANCE_ID",
}, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.