text:
import json
import logging
from datetime import datetime
from io import BytesIO
from typing import Any, Dict, Optional
from zipfile import ZipFile

import simplejson
from flask import g, make_response, redirect, request, Response, send_file, url_for
from flask_appbuilder.api import expose, protect, rison, safe
from flask_appbuilder.hooks import before_request
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_babel import gettext as _, ngettext
from marshmallow import ValidationError
from werkzeug.wrappers import Response as WerkzeugResponse
from werkzeug.wsgi import FileWrapper

from superset import is_feature_enabled, thumbnail_cache
from superset.charts.commands.bulk_delete import BulkDeleteChartCommand
from superset.charts.commands.create import CreateChartCommand
from superset.charts.commands.data import ChartDataCommand
from superset.charts.commands.delete import DeleteChartCommand
from superset.charts.commands.exceptions import (
    ChartBulkDeleteFailedError,
    ChartCreateFailedError,
    ChartDataCacheLoadError,
    ChartDataQueryFailedError,
    ChartDeleteFailedError,
    ChartForbiddenError,
    ChartInvalidError,
    ChartNotFoundError,
    ChartUpdateFailedError,
)
from superset.charts.commands.export import ExportChartsCommand
from superset.charts.commands.importers.dispatcher import ImportChartsCommand
from superset.charts.commands.update import UpdateChartCommand
from superset.charts.dao import ChartDAO
from superset.charts.filters import ChartAllTextFilter, ChartFavoriteFilter, ChartFilter
from superset.charts.post_processing import apply_post_process
from superset.charts.schemas import (
    CHART_SCHEMAS,
    ChartPostSchema,
    ChartPutSchema,
    get_delete_ids_schema,
    get_export_ids_schema,
    get_fav_star_ids_schema,
    openapi_spec_methods_override,
    screenshot_query_schema,
    thumbnail_query_schema,
)
from superset.commands.importers.exceptions import NoValidFilesFoundError
from superset.commands.importers.v1.utils import get_contents_from_bundle
from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.exceptions import QueryObjectValidationError
from superset.extensions import event_logger, security_manager
from superset.models.slice import Slice
from superset.tasks.thumbnails import cache_chart_thumbnail
from superset.utils.async_query_manager import AsyncQueryTokenException
from superset.utils.core import (
    ChartDataResultFormat,
    ChartDataResultType,
    json_int_dttm_ser,
)
from superset.utils.screenshots import ChartScreenshot
from superset.utils.urls import get_url_path
from superset.views.base_api import (
    BaseSupersetModelRestApi,
    RelatedFieldFilter,
    statsd_metrics,
)
from superset.views.core import CsvResponse, generate_download_headers
from superset.views.filters import FilterRelatedOwners

logger = logging.getLogger(__name__)

class ChartRestApi(BaseSupersetModelRestApi):
    datamodel = SQLAInterface(Slice)

    resource_name = "chart"
    allow_browser_login = True

    @before_request(only=["thumbnail", "screenshot", "cache_screenshot"])
    def ensure_thumbnails_enabled(self) -> Optional[Response]:
        if not is_feature_enabled("THUMBNAILS"):
            return self.response_404()
        return None

    include_route_methods = RouteMethod.REST_MODEL_VIEW_CRUD_SET | {
        RouteMethod.EXPORT,
        RouteMethod.IMPORT,
        RouteMethod.RELATED,
        "bulk_delete",  # not using RouteMethod since locally defined
        "data",
        "get_data",
        "data_from_cache",
        "viz_types",
        "favorite_status",
        "thumbnail",
        "screenshot",
        "cache_screenshot",
    }
    class_permission_name = "Chart"
    method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
    show_columns = [
        "cache_timeout",
        "dashboards.dashboard_title",
        "dashboards.id",
        "description",
        "owners.first_name",
        "owners.id",
        "owners.last_name",
        "owners.username",
        "params",
        "slice_name",
        "viz_type",
        "query_context",
    ]
    show_select_columns = show_columns + ["table.id"]
    list_columns = [
        "cache_timeout",
        "changed_by.first_name",
        "changed_by.last_name",
        "changed_by_name",
        "changed_by_url",
        "changed_on_delta_humanized",
        "changed_on_utc",
        "created_by.first_name",
        "created_by.id",
        "created_by.last_name",
        "datasource_id",
        "datasource_name_text",
        "datasource_type",
        "datasource_url",
        "description",
        "description_markeddown",
        "edit_url",
        "id",
        "last_saved_at",
        "last_saved_by.id",
        "last_saved_by.first_name",
        "last_saved_by.last_name",
        "owners.first_name",
        "owners.id",
        "owners.last_name",
        "owners.username",
        "params",
        "slice_name",
        "table.default_endpoint",
        "table.table_name",
        "thumbnail_url",
        "url",
        "viz_type",
    ]
    list_select_columns = list_columns + ["changed_by_fk", "changed_on"]
    order_columns = [
        "changed_by.first_name",
        "changed_on_delta_humanized",
        "datasource_id",
        "datasource_name",
        "last_saved_at",
        "last_saved_by.id",
        "last_saved_by.first_name",
        "last_saved_by.last_name",
        "slice_name",
        "viz_type",
    ]
    search_columns = [
        "created_by",
        "changed_by",
        "last_saved_at",
        "last_saved_by.id",
        "last_saved_by.first_name",
        "last_saved_by.last_name",
        "datasource_id",
        "datasource_name",
        "datasource_type",
        "description",
        "id",
        "owners",
        "slice_name",
        "viz_type",
    ]
    base_order = ("changed_on", "desc")
    base_filters = [["id", ChartFilter, lambda: []]]
    search_filters = {
        "id": [ChartFavoriteFilter],
        "slice_name": [ChartAllTextFilter],
    }

    # Will just affect _info endpoint
    edit_columns = ["slice_name"]
    add_columns = edit_columns

    add_model_schema = ChartPostSchema()
    edit_model_schema = ChartPutSchema()

    openapi_spec_tag = "Charts"
    """ Override the name set for this collection of endpoints """
    openapi_spec_component_schemas = CHART_SCHEMAS

    apispec_parameter_schemas = {
        "screenshot_query_schema": screenshot_query_schema,
        "get_delete_ids_schema": get_delete_ids_schema,
        "get_export_ids_schema": get_export_ids_schema,
        "get_fav_star_ids_schema": get_fav_star_ids_schema,
    }
    """ Add extra schemas to the OpenAPI components schema section """
    openapi_spec_methods = openapi_spec_methods_override
    """ Overrides GET methods OpenApi descriptions """

    order_rel_fields = {
        "slices": ("slice_name", "asc"),
        "owners": ("first_name", "asc"),
    }

    related_field_filters = {
        "owners": RelatedFieldFilter("first_name", FilterRelatedOwners),
        "created_by": RelatedFieldFilter("first_name", FilterRelatedOwners),
    }

    allowed_rel_fields = {"owners", "created_by"}

    @expose("/", methods=["POST"])
    @protect()
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.post",
        log_to_statsd=False,
    )
    def post(self) -> Response:
        """Creates a new Chart
        ---
        post:
          description: >-
            Create a new Chart.
          requestBody:
            description: Chart schema
            required: true
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
          responses:
            201:
              description: Chart added
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      id:
                        type: number
                      result:
                        $ref: '#/components/schemas/{{self.__class__.__name__}}.post'
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        if not request.is_json:
            return self.response_400(message="Request is not JSON")
        try:
            item = self.add_model_schema.load(request.json)
        # This validates custom Schema with custom validations
        except ValidationError as error:
            return self.response_400(message=error.messages)
        try:
            new_model = CreateChartCommand(g.user, item).run()
            return self.response(201, id=new_model.id, result=item)
        except ChartInvalidError as ex:
            return self.response_422(message=ex.normalized_messages())
        except ChartCreateFailedError as ex:
            logger.error(
                "Error creating model %s: %s",
                self.__class__.__name__,
                str(ex),
                exc_info=True,
            )
            return self.response_422(message=str(ex))

    @expose("/<pk>", methods=["PUT"])
    @protect()
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.put",
        log_to_statsd=False,
    )
    def put(self, pk: int) -> Response:
        """Changes a Chart
        ---
        put:
          description: >-
            Changes a Chart.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
          requestBody:
            description: Chart schema
            required: true
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/{{self.__class__.__name__}}.put'
          responses:
            200:
              description: Chart changed
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      id:
                        type: number
                      result:
                        $ref: '#/components/schemas/{{self.__class__.__name__}}.put'
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            403:
              $ref: '#/components/responses/403'
            404:
              $ref: '#/components/responses/404'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        if not request.is_json:
            return self.response_400(message="Request is not JSON")
        try:
            item = self.edit_model_schema.load(request.json)
        # This validates custom Schema with custom validations
        except ValidationError as error:
            return self.response_400(message=error.messages)
        try:
            changed_model = UpdateChartCommand(g.user, pk, item).run()
            response = self.response(200, id=changed_model.id, result=item)
        except ChartNotFoundError:
            response = self.response_404()
        except ChartForbiddenError:
            response = self.response_403()
        except ChartInvalidError as ex:
            response = self.response_422(message=ex.normalized_messages())
        except ChartUpdateFailedError as ex:
            logger.error(
                "Error updating model %s: %s",
                self.__class__.__name__,
                str(ex),
                exc_info=True,
            )
            response = self.response_422(message=str(ex))

        return response

    @expose("/<pk>", methods=["DELETE"])
    @protect()
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.delete",
        log_to_statsd=False,
    )
    def delete(self, pk: int) -> Response:
        """Deletes a Chart
        ---
        delete:
          description: >-
            Deletes a Chart.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
          responses:
            200:
              description: Chart delete
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      message:
                        type: string
            401:
              $ref: '#/components/responses/401'
            403:
              $ref: '#/components/responses/403'
            404:
              $ref: '#/components/responses/404'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        try:
            DeleteChartCommand(g.user, pk).run()
            return self.response(200, message="OK")
        except ChartNotFoundError:
            return self.response_404()
        except ChartForbiddenError:
            return self.response_403()
        except ChartDeleteFailedError as ex:
            logger.error(
                "Error deleting model %s: %s",
                self.__class__.__name__,
                str(ex),
                exc_info=True,
            )
            return self.response_422(message=str(ex))

    @expose("/", methods=["DELETE"])
    @protect()
    @safe
    @statsd_metrics
    @rison(get_delete_ids_schema)
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.bulk_delete",
        log_to_statsd=False,
    )
    def bulk_delete(self, **kwargs: Any) -> Response:
        """Delete bulk Charts
        ---
        delete:
          description: >-
            Deletes multiple Charts in a bulk operation.
          parameters:
          - in: query
            name: q
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/get_delete_ids_schema'
          responses:
            200:
              description: Charts bulk delete
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      message:
                        type: string
            401:
              $ref: '#/components/responses/401'
            403:
              $ref: '#/components/responses/403'
            404:
              $ref: '#/components/responses/404'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        item_ids = kwargs["rison"]
        try:
            BulkDeleteChartCommand(g.user, item_ids).run()
            return self.response(
                200,
                message=ngettext(
                    "Deleted %(num)d chart", "Deleted %(num)d charts", num=len(item_ids)
                ),
            )
        except ChartNotFoundError:
            return self.response_404()
        except ChartForbiddenError:
            return self.response_403()
        except ChartBulkDeleteFailedError as ex:
            return self.response_422(message=str(ex))

    def send_chart_response(
        self, result: Dict[Any, Any], form_data: Optional[Dict[str, Any]] = None,
    ) -> Response:
        result_type = result["query_context"].result_type
        result_format = result["query_context"].result_format

        # Post-process the data so it matches the data presented in the chart.
        # This is needed for sending reports based on text charts that do the
        # post-processing of data, eg, the pivot table.
        if (
            result_type == ChartDataResultType.POST_PROCESSED
            and result_format == ChartDataResultFormat.CSV
        ):
            result = apply_post_process(result, form_data)

        if result_format == ChartDataResultFormat.CSV:
            # Verify user has permission to export CSV file
            if not security_manager.can_access("can_csv", "Superset"):
                return self.response_403()

            # return the first result
            data = result["queries"][0]["data"]
            return CsvResponse(data, headers=generate_download_headers("csv"))

        if result_format == ChartDataResultFormat.JSON:
            response_data = simplejson.dumps(
                {"result": result["queries"]},
                default=json_int_dttm_ser,
                ignore_nan=True,
            )
            resp = make_response(response_data, 200)
            resp.headers["Content-Type"] = "application/json; charset=utf-8"
            return resp

        return self.response_400(message=f"Unsupported result_format: {result_format}")

    def get_data_response(
        self,
        command: ChartDataCommand,
        force_cached: bool = False,
        form_data: Optional[Dict[str, Any]] = None,
    ) -> Response:
        try:
            result = command.run(force_cached=force_cached)
        except ChartDataCacheLoadError as exc:
            return self.response_422(message=exc.message)
        except ChartDataQueryFailedError as exc:
            return self.response_400(message=exc.message)

        return self.send_chart_response(result, form_data)

    @expose("/<int:pk>/data/", methods=["GET"])
    @protect()
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.data",
        log_to_statsd=False,
    )
    def get_data(self, pk: int) -> Response:
        """
        Takes a chart ID and uses the query context stored when the chart was saved
        to return payload data response.
        ---
        get:
          description: >-
            Takes a chart ID and uses the query context stored when the chart was saved
            to return payload data response.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
            description: The chart ID
          - in: query
            name: format
            description: The format in which the data should be returned
            schema:
              type: string
          - in: query
            name: type
            description: The type in which the data should be returned
            schema:
              type: string
          responses:
            200:
              description: Query result
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartDataResponseSchema"
            202:
              description: Async job details
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartDataAsyncResponseSchema"
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            500:
              $ref: '#/components/responses/500'
        """
        chart = self.datamodel.get(pk, self._base_filters)
        if not chart:
            return self.response_404()

        try:
            json_body = json.loads(chart.query_context)
        except (TypeError, json.decoder.JSONDecodeError):
            json_body = None

        if json_body is None:
            return self.response_400(
                message=_(
                    "Chart has no query context saved. Please save the chart again."
                )
            )

        # override saved query context
        json_body["result_format"] = request.args.get(
            "format", ChartDataResultFormat.JSON
        )
        json_body["result_type"] = request.args.get("type", ChartDataResultType.FULL)

        try:
            command = ChartDataCommand()
            query_context = command.set_query_context(json_body)
            command.validate()
        except QueryObjectValidationError as error:
            return self.response_400(message=error.message)
        except ValidationError as error:
            return self.response_400(
                message=_(
                    "Request is incorrect: %(error)s", error=error.normalized_messages()
                )
            )

        # TODO: support CSV, SQL query and other non-JSON types
        if (
            is_feature_enabled("GLOBAL_ASYNC_QUERIES")
            and query_context.result_format == ChartDataResultFormat.JSON
            and query_context.result_type == ChartDataResultType.FULL
        ):
            return self._run_async(command)

        try:
            form_data = json.loads(chart.params)
        except (TypeError, json.decoder.JSONDecodeError):
            form_data = {}

        return self.get_data_response(command, form_data=form_data)

    @expose("/data", methods=["POST"])
    @protect()
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.data",
        log_to_statsd=False,
    )
    def data(self) -> Response:
        """
        Takes a query context constructed in the client and returns payload
        data response for the given query.
        ---
        post:
          description: >-
            Takes a query context constructed in the client and returns payload data
            response for the given query.
          requestBody:
            description: >-
              A query context consists of a datasource from which to fetch data
              and one or many query objects.
            required: true
            content:
              application/json:
                schema:
                  $ref: "#/components/schemas/ChartDataQueryContextSchema"
          responses:
            200:
              description: Query result
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartDataResponseSchema"
            202:
              description: Async job details
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartDataAsyncResponseSchema"
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            500:
              $ref: '#/components/responses/500'
        """
        json_body = None
        if request.is_json:
            json_body = request.json
        elif request.form.get("form_data"):
            # CSV export submits regular form data
            try:
                json_body = json.loads(request.form["form_data"])
            except (TypeError, json.JSONDecodeError):
                pass

        if json_body is None:
            return self.response_400(message=_("Request is not JSON"))

        try:
            command = ChartDataCommand()
            query_context = command.set_query_context(json_body)
            command.validate()
        except QueryObjectValidationError as error:
            return self.response_400(message=error.message)
        except ValidationError as error:
            return self.response_400(
                message=_(
                    "Request is incorrect: %(error)s", error=error.normalized_messages()
                )
            )

        # TODO: support CSV, SQL query and other non-JSON types
        if (
            is_feature_enabled("GLOBAL_ASYNC_QUERIES")
            and query_context.result_format == ChartDataResultFormat.JSON
            and query_context.result_type == ChartDataResultType.FULL
        ):
            return self._run_async(command)

        return self.get_data_response(command)

    def _run_async(self, command: ChartDataCommand) -> Response:
        """
        Execute command as an async query.
        """
        # First, look for the chart query results in the cache.
        try:
            result = command.run(force_cached=True)
        except ChartDataCacheLoadError:
            result = None  # type: ignore

        already_cached_result = result is not None

        # If the chart query has already been cached, return it immediately.
        if already_cached_result:
            return self.send_chart_response(result)

        # Otherwise, kick off a background job to run the chart query.
        # Clients will either poll or be notified of query completion,
        # at which point they will call the /data/<cache_key> endpoint
        # to retrieve the results.
        try:
            command.validate_async_request(request)
        except AsyncQueryTokenException:
            return self.response_401()

        result = command.run_async(g.user.get_id())
        return self.response(202, **result)

    @expose("/data/<cache_key>", methods=["GET"])
    @protect()
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
        f".data_from_cache",
        log_to_statsd=False,
    )
    def data_from_cache(self, cache_key: str) -> Response:
        """
        Takes a query context cache key and returns payload
        data response for the given query.
        ---
        get:
          description: >-
            Takes a query context cache key and returns payload data
            response for the given query.
          parameters:
          - in: path
            schema:
              type: string
            name: cache_key
          responses:
            200:
              description: Query result
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartDataResponseSchema"
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        command = ChartDataCommand()
        try:
            cached_data = command.load_query_context_from_cache(cache_key)
            command.set_query_context(cached_data)
            command.validate()
        except ChartDataCacheLoadError:
            return self.response_404()
        except ValidationError as error:
            return self.response_400(
                message=_("Request is incorrect: %(error)s", error=error.messages)
            )

        return self.get_data_response(command, True)

    @expose("/<pk>/cache_screenshot/", methods=["GET"])
    @protect()
    @rison(screenshot_query_schema)
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
        f".cache_screenshot",
        log_to_statsd=False,
    )
    def cache_screenshot(self, pk: int, **kwargs: Any) -> WerkzeugResponse:
        """
        ---
        get:
          description: Compute and cache a screenshot.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
          - in: query
            name: q
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/screenshot_query_schema'
          responses:
            200:
              description: Chart async result
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/ChartCacheScreenshotResponseSchema"
            302:
              description: Redirects to the current digest
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            500:
              $ref: '#/components/responses/500'
        """
        rison_dict = kwargs["rison"]
        window_size = rison_dict.get("window_size") or (800, 600)

        # Don't shrink the image if thumb_size is not specified
        thumb_size = rison_dict.get("thumb_size") or window_size

        chart = self.datamodel.get(pk, self._base_filters)
        if not chart:
            return self.response_404()

        chart_url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
        screenshot_obj = ChartScreenshot(chart_url, chart.digest)
        cache_key = screenshot_obj.cache_key(window_size, thumb_size)
        image_url = get_url_path(
            "ChartRestApi.screenshot", pk=chart.id, digest=cache_key
        )

        def trigger_celery() -> WerkzeugResponse:
            logger.info("Triggering screenshot ASYNC")
            kwargs = {
                "url": chart_url,
                "digest": chart.digest,
                "force": True,
                "window_size": window_size,
                "thumb_size": thumb_size,
            }
            cache_chart_thumbnail.delay(**kwargs)
            return self.response(
                202, cache_key=cache_key, chart_url=chart_url, image_url=image_url
            )

        return trigger_celery()

    @expose("/<pk>/screenshot/<digest>/", methods=["GET"])
    @protect()
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.screenshot",
        log_to_statsd=False,
    )
    def screenshot(self, pk: int, digest: str) -> WerkzeugResponse:
        """Get Chart screenshot
        ---
        get:
          description: Get a computed screenshot from cache.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
          - in: path
            schema:
              type: string
            name: digest
          responses:
            200:
              description: Chart thumbnail image
              content:
               image/*:
                 schema:
                   type: string
                   format: binary
            302:
              description: Redirects to the current digest
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            500:
              $ref: '#/components/responses/500'
        """
        chart = self.datamodel.get(pk, self._base_filters)

        # Making sure the chart still exists
        if not chart:
            return self.response_404()

        # fetch the chart screenshot using the current user and cache if set
        img = ChartScreenshot.get_from_cache_key(thumbnail_cache, digest)
        if img:
            return Response(
                FileWrapper(img), mimetype="image/png", direct_passthrough=True
            )
        # TODO: return an empty image
        return self.response_404()

    @expose("/<pk>/thumbnail/<digest>/", methods=["GET"])
    @protect()
    @rison(thumbnail_query_schema)
    @safe
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.thumbnail",
        log_to_statsd=False,
    )
    def thumbnail(self, pk: int, digest: str, **kwargs: Any) -> WerkzeugResponse:
        """Get Chart thumbnail
        ---
        get:
          description: Compute or get already computed chart thumbnail from cache.
          parameters:
          - in: path
            schema:
              type: integer
            name: pk
          - in: path
            schema:
              type: string
            name: digest
          responses:
            200:
              description: Chart thumbnail image
              content:
               image/*:
                 schema:
                   type: string
                   format: binary
            302:
              description: Redirects to the current digest
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            500:
              $ref: '#/components/responses/500'
        """
        chart = self.datamodel.get(pk, self._base_filters)
        if not chart:
            return self.response_404()

        url = get_url_path("Superset.slice", slice_id=chart.id, standalone="true")
        if kwargs["rison"].get("force", False):
            logger.info(
                "Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
            )
            cache_chart_thumbnail.delay(url, chart.digest, force=True)
            return self.response(202, message="OK Async")
        # fetch the chart screenshot using the current user and cache if set
        screenshot = ChartScreenshot(url, chart.digest).get_from_cache(
            cache=thumbnail_cache
        )
        # If not screenshot then send request to compute thumb to celery
        if not screenshot:
            self.incr_stats("async", self.thumbnail.__name__)
            logger.info(
                "Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
            )
            cache_chart_thumbnail.delay(url, chart.digest, force=True)
            return self.response(202, message="OK Async")
        # If digests
        if chart.digest != digest:
            self.incr_stats("redirect", self.thumbnail.__name__)
            return redirect(
                url_for(
                    f"{self.__class__.__name__}.thumbnail", pk=pk, digest=chart.digest
                )
            )
        self.incr_stats("from_cache", self.thumbnail.__name__)
        return Response(
            FileWrapper(screenshot), mimetype="image/png", direct_passthrough=True
        )

    @expose("/export/", methods=["GET"])
    @protect()
    @safe
    @statsd_metrics
    @rison(get_export_ids_schema)
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.export",
        log_to_statsd=False,
    )
    def export(self, **kwargs: Any) -> Response:
        """Export charts
        ---
        get:
          description: >-
            Exports multiple charts and downloads them as YAML files
          parameters:
          - in: query
            name: q
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/get_export_ids_schema'
          responses:
            200:
              description: A zip file with chart(s), dataset(s) and database(s) as YAML
              content:
                application/zip:
                  schema:
                    type: string
                    format: binary
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            500:
              $ref: '#/components/responses/500'
        """
        token = request.args.get("token")
        requested_ids = kwargs["rison"]
        timestamp = datetime.now().strftime("%Y%m%dT%H%M%S")
        root = f"chart_export_{timestamp}"
        filename = f"{root}.zip"

        buf = BytesIO()
        with ZipFile(buf, "w") as bundle:
            try:
                for file_name, file_content in ExportChartsCommand(requested_ids).run():
                    with bundle.open(f"{root}/{file_name}", "w") as fp:
                        fp.write(file_content.encode())
            except ChartNotFoundError:
                return self.response_404()
        buf.seek(0)

        response = send_file(
            buf,
            mimetype="application/zip",
            as_attachment=True,
            attachment_filename=filename,
        )
        if token:
            response.set_cookie(token, "done", max_age=600)
        return response

    @expose("/favorite_status/", methods=["GET"])
    @protect()
    @safe
    @rison(get_fav_star_ids_schema)
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}"
        f".favorite_status",
        log_to_statsd=False,
    )
    def favorite_status(self, **kwargs: Any) -> Response:
        """Favorite stars for Charts
        ---
        get:
          description: >-
            Check favorited dashboards for current user
          parameters:
          - in: query
            name: q
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/get_fav_star_ids_schema'
          responses:
            200:
              description:
              content:
                application/json:
                  schema:
                    $ref: "#/components/schemas/GetFavStarIdsSchema"
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            404:
              $ref: '#/components/responses/404'
            500:
              $ref: '#/components/responses/500'
        """
        requested_ids = kwargs["rison"]
        charts = ChartDAO.find_by_ids(requested_ids)
        if not charts:
            return self.response_404()
        favorited_chart_ids = ChartDAO.favorited_ids(charts, g.user.get_id())
        res = [
            {"id": request_id, "value": request_id in favorited_chart_ids}
            for request_id in requested_ids
        ]
        return self.response(200, result=res)

    @expose("/import/", methods=["POST"])
    @protect()
    @statsd_metrics
    @event_logger.log_this_with_context(
        action=lambda self, *args, **kwargs: f"{self.__class__.__name__}.import_",
        log_to_statsd=False,
    )
    def import_(self) -> Response:
        """Import chart(s) with associated datasets and databases
        ---
        post:
          requestBody:
            required: true
            content:
              multipart/form-data:
                schema:
                  type: object
                  properties:
                    formData:
                      description: upload file (ZIP)
                      type: string
                      format: binary
                    passwords:
                      description: JSON map of passwords for each file
                      type: string
                    overwrite:
                      description: overwrite existing databases?
                      type: boolean
          responses:
            200:
              description: Chart import result
              content:
                application/json:
                  schema:
                    type: object
                    properties:
                      message:
                        type: string
            400:
              $ref: '#/components/responses/400'
            401:
              $ref: '#/components/responses/401'
            422:
              $ref: '#/components/responses/422'
            500:
              $ref: '#/components/responses/500'
        """
        upload = request.files.get("formData")
        if not upload:
            return self.response_400()
        with ZipFile(upload) as bundle:
            contents = get_contents_from_bundle(bundle)

        if not contents:
            raise NoValidFilesFoundError()

        passwords = (
            json.loads(request.form["passwords"])
            if "passwords" in request.form
            else None
        )
        overwrite = request.form.get("overwrite") == "true"

        command = ImportChartsCommand(
            contents, passwords=passwords, overwrite=overwrite
        )
        command.run()
        return self.response(200, message="OK")


text:
<?php

namespace PHPExiftool\Driver\Tag\MAC;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class TotalFrames extends AbstractTag
{

    protected $Id = 'mixed';

    protected $Name = 'TotalFrames';

    protected $FullName = 'mixed';

    protected $GroupName = 'MAC';

    protected $g0 = 'APE';

    protected $g1 = 'MAC';

    protected $g2 = 'Audio';

    protected $Type = 'int32u';

    protected $Writable = false;

    protected $Description = 'Total Frames';

}

redpajama_set_name: RedPajamaGithub


text:
package tests;
import java.util.*;
import java.lang.*;
import java.io.*;
import judge.*;
import datastruct.*;

public class max_sum_rect {
    public static int num_test = 60;
    public static int[][][] in_0;
    public static int[][][] in_org_0;
    public static int[] out;

    public static void load_test() {
        File fil = new File("judge/tests/max-sum-rect.txt");
        FileReader inputFil = null;
        try {
            inputFil = new FileReader(fil);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        BufferedReader in = new BufferedReader(inputFil);
        try {
            in_0 = common.read_int_matrix_arr(in);
            in_org_0 = test_common.copy(in_0);
            out = common.read_int_array(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void judge() {
        load_test();
        common.capture_stdout();
        Solution s = new Solution();

        long startTime = System.currentTimeMillis();

        for(int i = 0; i < num_test; ++i) {
            System.out.printf("Testing case #%d\n", i+1);
            int answer = s.max_sum_rect(in_0[i]);
            if(answer != out[i]) {
                common.release_stdout();
                System.out.printf("%d / %d;", i+1, num_test);
                String outs = common.to_string(max_sum_rect.in_org_0[i]);
                System.out.print(outs + ";");
                System.out.print(common.to_string(answer) + ";");
                System.out.println(common.to_string(out[i]));
                return;
            }
        }

        common.release_stdout();
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("Accepted;");
        System.out.println(estimatedTime);
    }
}


text:
title: An introduction to web services
disqus_identifier: 2003-04-an-introduction-to-web-services
comments: true
---

One of my goals for the new year was to contribute more to the development community. One way that I determined I could contribute was to author articles to provide insight on how to accomplish certain tasks.

The first step to achieving this goal was the creation of this web log. This means of communication is very effective and gets your ideas to a lot of people in an efficient manner.

Given this, I have finally contributed my first article to [codeproject.com][1]. The article is an introduction to authoring web services with the Microsoft .NET framework and Visual Studio .NET. The sample code associated with the article demonstrates a web service that retrieves the daily [Dilbert][2] image. You can view the article [here][2]. I'm very open to suggestions/comments on the article.

[1]:http://www.codeproject.com
[2]:http://www.dilbert.com/
[3]:http://www.codeproject.com/useritems/dilbertservice.asp


text:
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Collections;
using System.Xml;
using NUnit.Framework;
using SharpVectors.Dom.Css;
using SharpVectors.Dom;

		[TestFixture]
		public class CssValueTests
		{
			protected virtual string aCssText
			{
				get{return "sometext";}
			}

			protected virtual string anotherCssText
			{
				get{return "kalle";}
			}

			protected virtual CssValueType cssValueType
			{
				get{return CssValueType.Custom;}
			}

			protected virtual CssValue _getCssValue(string cssText, bool readOnly)
			{
				return new CssValue(CssValueType.Custom, cssText, readOnly);
			}

			protected virtual Type Type
			{
				get{return typeof(CssValue);}
			}

			[Test]
			public void TestCssText()
			{
				CssValue cssValue = _getCssValue(aCssText, false);
				Assert.AreEqual(Type, cssValue.GetType());
			}

			[Test]
			public void TestType()
			{
				CssValue cssValue = _getCssValue(aCssText, false);
				Assert.AreEqual(aCssText, cssValue.CssText);
			}

			[Test]
			public void TestCssTextTrim()
			{
				CssValue cssValue = _getCssValue(" " + aCssText + " ", false);
				Assert.AreEqual(aCssText, cssValue.CssText);
			}

			[Test]
			public void TestCssValueType()
			{
				CssValue cssValue = _getCssValue(aCssText, false);
				Assert.AreEqual(cssValueType, cssValue.CssValueType);
			}

			[Test]
			public virtual void TestCssReadOnly()
			{
				CssValue cssValue = _getCssValue(aCssText, false);
				Assert.AreEqual(false, cssValue.ReadOnly);

				cssValue = _getCssValue(aCssText, true);
				Assert.AreEqual(true, cssValue.ReadOnly);
			}

			[Test]
			public void TestCssTextReadWrite()
			{
				CssValue cssValue = _getCssValue(aCssText, false);
				cssValue.CssText = anotherCssText;
				Assert.AreEqual(anotherCssText, cssValue.CssText);
			}

			[Test]
			[ExpectedException(typeof(DomException))]
			public virtual void TestCssTextReadOnly()
			{
				CssValue cssValue = _getCssValue(aCssText, true);
				cssValue.CssText = anotherCssText;
			}

			[Test]
			public void CssValueInheritTest()
			{
				CssValue cssValue = new CssValue(CssValueType.Inherit, "inherit", false);
				Assert.AreEqual("inherit", cssValue.CssText);
				Assert.AreEqual(CssValueType.Inherit, cssValue.CssValueType);
			}

			[Test]
			public void CssValueCustomTest()
			{
				CssValue cssValue = new CssValue(CssValueType.Custom, "some custom value ", false);
				Assert.AreEqual("some custom value", cssValue.CssText);
				Assert.AreEqual(CssValueType.Custom, cssValue.CssValueType);
			}
		}


text:
#pragma once

#include <stdbool.h>
#include <stdint.h>

#if defined(_MSC_VER)
#pragma warning(disable : 4127) /* conditional expression is constant */
#if _MSC_VER > 1800
#pragma warning(disable : 4464) /* relative include path contains '..' */
#endif
#endif /* MSVC */

#include "../t1ha.h" /* for byteorder and common __ia32__ */

/*****************************************************************************/

typedef uint64_t timestamp_t;

enum mera_flags {
  timestamp_clock_have = 1u << 0,
  timestamp_clock_cheap = 1u << 1,
  timestamp_ticks = 1u << 2,
  timestamp_cycles = 1u << 3,
  timestamp_clock_stable = 1u << 4,
};

typedef struct {
  unsigned (*start)(timestamp_t *);
  unsigned (*finish)(timestamp_t *);
  double (*convert)(timestamp_t);
  const char *units;
  const char *source;
  unsigned flags;
  int cpunum;
} mera_t;

extern mera_t mera;
bool mera_init(void);

typedef struct {
  unsigned retry_count, restart_count;
  unsigned overhead_loops_max, overhead_best_count, overhead_accounted_loops,
      overhead_worthless_loops;
  uint64_t overhead_best, overhead_gate;

  unsigned target_loops, tail_loops_max, target_best_count,
      target_accounted_loops, target_worthless_loops, spent_seconds;
  uint64_t target_best, target_gate;
} mera_bci_t /* bci = Bench Convergence Info */;

extern mera_bci_t mera_bci;
typedef uint64_t (*mera_bench_target_t)(const void *data, size_t bytes,
                                        uint64_t seed);

#define MERA_BENCH_TARGET mera_bench_target_t
#define MERA_BENCH_SELF_ARGS const void *data, size_t bytes, uint64_t seed
#define MERA_BENCH_TARGET_ARGS data, bytes, seed
#define MERA_PERROR_PREFIX " - "

double mera_bench(MERA_BENCH_TARGET target, MERA_BENCH_SELF_ARGS);

/*****************************************************************************/

#if defined(__ia32__)
typedef struct _ia32_cpu_features {
  struct {
    uint32_t ebx;
    uint32_t ecx;
    uint32_t edx;
  } basic /* https://en.wikipedia.org/wiki/CPUID#EAX=1:_Processor_Info_and_Feature_Bits
           */
      ,
      extended_7 /* https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features
                  */
      ;

  struct {
    uint32_t ecx;
    uint32_t edx;
  } extended_80000001 /* https://en.wikipedia.org/wiki/CPUID#EAX=80000001h:_Extended_Processor_Info_and_Feature_Bits
                       */
      ;

  struct {
    uint32_t ecx;
    uint32_t edx;
  } extended_80000007 /*  Advanced Power Management Information */;

} ia32_cpu_features_t;

extern ia32_cpu_features_t ia32_cpu_features;
void ia32_fetch_cpu_features(void);
#endif /* __ia32__ */


text:
//
//  ChooseViewController.m
//  BirdFight
//
//  Created by 聚米 on 16/10/22.
//  Copyright © 2016年 聚米. All rights reserved.
//

#import "ChooseViewController.h"

@interface ChooseViewController ()

@property (weak, nonatomic) IBOutlet UIView *view_back_1;
@property (weak, nonatomic) IBOutlet UIView *view_back_2;
@property (weak, nonatomic) IBOutlet UILabel *label_1;
@property (weak, nonatomic) IBOutlet UILabel *label_2;
@property (weak, nonatomic) IBOutlet UILabel *label_3;
@property (weak, nonatomic) IBOutlet UILabel *label_4;
@property (weak, nonatomic) IBOutlet UILabel *label_5;
@property (weak, nonatomic) IBOutlet UILabel *label_6;

@end

@implementation ChooseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
/*!
 * phaser-super-storage - version 1.0.4
 * A cross platform storage plugin for Phaser
 *
 * Azerion
 * Build at 15-03-2019
 * Released under MIT License
 */

var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StorageAdapters;
    (function (StorageAdapters) {
        /**
         * Storage driver for cookies
         */
        var CookieStorage = (function () {
            function CookieStorage(spacedName) {
                if (spacedName === void 0) { spacedName = ''; }
                this.namespace = '';
                this.forcePromises = false;
                this.setNamespace(spacedName);
            }
            Object.defineProperty(CookieStorage.prototype, "length", {
                get: function () {
                    return (this.getNameSpaceMatches() !== null) ? this.getNameSpaceMatches().length : 0;
                },
                enumerable: true,
                configurable: true
            });
            CookieStorage.prototype.key = function (n) {
                var key = this.getNameSpaceMatches()[n];
                var result = this.getCookiesForNameSpace()[key] || null;
                if (this.forcePromises) {
                    return this.promisefy(result);
                }
                return result;
            };
            CookieStorage.prototype.getItem = function (key) {
                var result = this.getCookiesForNameSpace()[key] || null;
                if (this.forcePromises) {
                    return this.promisefy(result);
                }
                return result;
            };
            CookieStorage.prototype.setItem = function (key, value) {
                document.cookie = encodeURIComponent(this.namespace + key) + '=' + encodeURIComponent(value) + '; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/';
                if (this.forcePromises) {
                    return this.promisefy(null);
                }
            };
            CookieStorage.prototype.removeItem = function (key) {
                document.cookie = encodeURIComponent(this.namespace + key) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
                if (this.forcePromises) {
                    return this.promisefy(null);
                }
            };
            CookieStorage.prototype.clear = function () {
                var cookies = this.getCookiesForNameSpace();
                for (var key in cookies) {
                    if (cookies.hasOwnProperty(key)) {
                        this.removeItem(key);
                    }
                }
                if (this.forcePromises) {
                    return this.promisefy(null);
                }
            };
            CookieStorage.prototype.setNamespace = function (namespace) {
                if (namespace) {
                    this.namespace = namespace + ':';
                    this.reg = new RegExp('^' + this.namespace + '[a-zA-Z0-9]*', 'g');
                }
                if (this.forcePromises) {
                    return this.promisefy(namespace);
                }
            };
            CookieStorage.prototype.getNameSpaceMatches = function () {
                var _this = this;
                var cookies = decodeURIComponent(document.cookie).split('; ');
                return cookies.filter(function (val) {
                    return (val.match(_this.reg) !== null) ? val.match(_this.reg).length > 0 : false;
                });
            };
            CookieStorage.prototype.getCookiesForNameSpace = function () {
                var _this = this;
                var cookies = {};
                this.getNameSpaceMatches().forEach(function (cookie) {
                    var temp = cookie.replace(_this.namespace, '').split('=');
                    cookies[temp[0]] = temp[1];
                });
                return cookies;
            };
            CookieStorage.prototype.promisefy = function (value) {
                return new Promise(function (resolve, reject) {
                    resolve(value);
                });
            };
            return CookieStorage;
        }());
        StorageAdapters.CookieStorage = CookieStorage;
    })(StorageAdapters = PhaserSuperStorage.StorageAdapters || (PhaserSuperStorage.StorageAdapters = {}));
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StorageAdapters;
    (function (StorageAdapters) {
        /**
         * Storage driver for browser's localStorage
         */
        var CordovaStorage = (function () {
            // Due to async /w promise it is not possible to pass namespace in constructor
            function CordovaStorage() {
                this.namespace = '';
                this.keys = [];
            }
            Object.defineProperty(CordovaStorage.prototype, "forcePromises", {
                get: function () {
                    return true;
                },
                set: function (v) {
                    //Do nothing
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(CordovaStorage.prototype, "length", {
                get: function () {
                    return this.keys.length;
                },
                enumerable: true,
                configurable: true
            });
            CordovaStorage.prototype.key = function (n) {
                return this.promisefy(this.keys[n]);
            };
            CordovaStorage.prototype.getItem = function (key) {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    NativeStorage.getItem(_this.namespace + key, function (value) {
                        resolve(value);
                    }, function (error) {
                        if (error.code === 2) {
                            resolve(null);
                        }
                        else {
                            reject(error);
                        }
                    });
                });
            };
            CordovaStorage.prototype.setItem = function (key, value) {
                var _this = this;
                if (key.length < 1) {
                    console.error('CordovaStorage: Key cannot be an empty string!');
                    return;
                }
                return new Promise(function (resolve, reject) {
                    NativeStorage.setItem(_this.namespace + key, value, function () {
                        if (_this.keys.indexOf(key) < 0) {
                            _this.keys.push(key);
                            _this.save();
                        }
                        resolve(null);
                    }, function (error) {
                        reject(error);
                    });
                });
            };
            CordovaStorage.prototype.removeItem = function (key) {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    NativeStorage.remove(_this.namespace + key, function () {
                        var id = _this.keys.indexOf(key);
                        if (id >= 0) {
                            _this.keys.splice(id, 1);
                            _this.save();
                        }
                        resolve(null);
                    }, function (error) {
                        reject(error);
                    });
                });
            };
            CordovaStorage.prototype.clear = function () {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    var counter = 0;
                    for (var i = 0; i < _this.keys.length; i++) {
                        NativeStorage.remove(_this.namespace + _this.keys[i], function () {
                            if (++counter >= _this.keys.length) {
                                _this.keys = [];
                                _this.save();
                                resolve(null);
                            }
                        }, function (error) {
                            reject(error);
                        });
                    }
                });
            };
            CordovaStorage.prototype.setNamespace = function (spacedName) {
                var _this = this;
                if (spacedName === void 0) { spacedName = ''; }
                this.namespace = spacedName + ':';
                this.keys = [];
                return new Promise(function (resolve, reject) {
                    _this.load().then(resolve).catch(resolve);
                });
            };
            CordovaStorage.prototype.promisefy = function (value) {
                return new Promise(function (resolve, reject) {
                    resolve(value);
                });
            };
            CordovaStorage.prototype.load = function () {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    NativeStorage.getItem(_this.namespace, function (value) {
                        _this.keys = JSON.parse(value);
                        resolve(null);
                    }, function (error) {
                        reject(error);
                    });
                });
            };
            CordovaStorage.prototype.save = function () {
                NativeStorage.setItem(this.namespace, JSON.stringify(this.keys), function () {
                    return;
                }, function (error) {
                    console.warn('CordovaStorage: Failed to save keys of namespace.');
                });
            };
            return CordovaStorage;
        }());
        StorageAdapters.CordovaStorage = CordovaStorage;
    })(StorageAdapters = PhaserSuperStorage.StorageAdapters || (PhaserSuperStorage.StorageAdapters = {}));
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StorageAdapters;
    (function (StorageAdapters) {
        /**
         * Storage driver for browser's localStorage
         */
        var IframeStorage = (function () {
            function IframeStorage(spacedName, expectedOrigin) {
                if (spacedName === void 0) { spacedName = ''; }
                if (expectedOrigin === void 0) { expectedOrigin = '*'; }
                this.namespace = '';
                this.expectedOrigin = '';
                this.storageLength = 0;
                this.enabled = false;
                if (spacedName !== '') {
                    this.setNamespace(spacedName);
                }
                this.expectedOrigin = expectedOrigin;
            }
            Object.defineProperty(IframeStorage.prototype, "forcePromises", {
                get: function () {
                    return true;
                },
                set: function (v) {
                    //Do nothing
                },
                enumerable: true,
                configurable: true
            });
            Object.defineProperty(IframeStorage.prototype, "length", {
                get: function () {
                    return this.storageLength;
                },
                enumerable: true,
                configurable: true
            });
            IframeStorage.prototype.init = function () {
                var _this = this;
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.init
                }).then(function () {
                    _this.enabled = true;
                });
            };
            IframeStorage.prototype.key = function (n) {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.key,
                    value: n
                });
            };
            IframeStorage.prototype.getItem = function (key) {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.getItem,
                    key: key
                });
            };
            IframeStorage.prototype.setItem = function (key, value) {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.setItem,
                    key: key,
                    value: value
                });
            };
            IframeStorage.prototype.removeItem = function (key) {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.removeItem,
                    key: key
                });
            };
            IframeStorage.prototype.clear = function () {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.clear
                });
            };
            IframeStorage.prototype.setNamespace = function (spacedName) {
                return this.sendMessage({
                    command: PhaserSuperStorage.StorageCommand.setNamespace,
                    value: spacedName
                });
            };
            IframeStorage.prototype.sendMessage = function (message) {
                var _this = this;
                var returnedResult;
                if (message.command === PhaserSuperStorage.StorageCommand.init) {
                    returnedResult = false;
                }
                var messageChannel = new MessageChannel();
                return new Promise(function (resolve, reject) {
                    if (!_this.enabled && message.command !== PhaserSuperStorage.StorageCommand.init) {
                        reject('Messaging not enabled!');
                    }
                    if (message.command === PhaserSuperStorage.StorageCommand.init) {
                        //small timeout to see if stuff is enabled
                        setTimeout(function () {
                            if (!returnedResult) {
                                reject('Unable to get a response in time');
                            }
                        }, 1000);
                    }
                    messageChannel.port1.onmessage = function (event) {
                        console.log('Frame received message', event);
                        var receivedMessage = PhaserSuperStorage.StorageUtils.validateMessage(event.data);
                        if (receivedMessage.command === PhaserSuperStorage.StorageCommand.init) {
                            returnedResult = true;
                        }
                        if (receivedMessage.status === undefined || receivedMessage.status !== 'ok') {
                            reject(receivedMessage.value);
                        }
                        if (receivedMessage.length !== undefined) {
                            _this.storageLength = receivedMessage.length;
                        }
                        switch (receivedMessage.command) {
                            case PhaserSuperStorage.StorageCommand.setNamespace:
                                _this.namespace = receivedMessage.value + ':';
                            case PhaserSuperStorage.StorageCommand.getItem:
                            case PhaserSuperStorage.StorageCommand.length:
                            case PhaserSuperStorage.StorageCommand.key:
                                resolve(receivedMessage.value);
                                break;
                            case PhaserSuperStorage.StorageCommand.setItem:
                            case PhaserSuperStorage.StorageCommand.removeItem:
                            case PhaserSuperStorage.StorageCommand.clear:
                            case PhaserSuperStorage.StorageCommand.init:
                                resolve(receivedMessage.status);
                                break;
                            default:
                                reject(receivedMessage.value);
                                break;
                        }
                    };
                    if (_this.enabled || message.command === PhaserSuperStorage.StorageCommand.init) {
                        console.log('Sending message to parent: ', message);
                        window.parent.postMessage(message, _this.expectedOrigin, [messageChannel.port2]);
                    }
                });
            };
            return IframeStorage;
        }());
        StorageAdapters.IframeStorage = IframeStorage;
    })(StorageAdapters = PhaserSuperStorage.StorageAdapters || (PhaserSuperStorage.StorageAdapters = {}));
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StorageAdapters;
    (function (StorageAdapters) {
        /**
         * Storage driver for browser's localStorage
         */
        var LocalStorage = (function () {
            function LocalStorage(spacedName) {
                if (spacedName === void 0) { spacedName = ''; }
                this.namespace = '';
                this.forcePromises = false;
                this.setNamespace(spacedName);
            }
            Object.defineProperty(LocalStorage.prototype, "length", {
                get: function () {
                    var keys = Object.keys(localStorage);
                    return PhaserSuperStorage.StorageUtils.nameSpaceKeyFilter(keys, this.namespace).length;
                },
                enumerable: true,
                configurable: true
            });
            LocalStorage.prototype.key = function (n) {
                return this.forcePromises ?
                    this.promisefy(this._key, arguments) :
                    this._key(n);
            };
            LocalStorage.prototype._key = function (n) {
                var keys = Object.keys(localStorage);
                var spacedKeys = PhaserSuperStorage.StorageUtils.nameSpaceKeyFilter(keys, this.namespace);
                var item = localStorage.getItem(spacedKeys[n]);
                return item;
            };
            LocalStorage.prototype.getItem = function (key) {
                return this.forcePromises ?
                    this.promisefy(this._getItem, arguments) :
                    this._getItem(key);
            };
            LocalStorage.prototype._getItem = function (key) {
                return localStorage.getItem(this.namespace + key);
            };
            LocalStorage.prototype.setItem = function (key, value) {
                return this.forcePromises ?
                    this.promisefy(this._setItem, arguments) :
                    this._setItem(key, value);
            };
            LocalStorage.prototype._setItem = function (key, value) {
                return localStorage.setItem(this.namespace + key, value);
            };
            LocalStorage.prototype.removeItem = function (key) {
                return this.forcePromises ?
                    this.promisefy(this._removeItem, arguments) :
                    this._removeItem(key);
            };
            LocalStorage.prototype._removeItem = function (key) {
                return localStorage.removeItem(this.namespace + key);
            };
            LocalStorage.prototype.clear = function () {
                return this.forcePromises ?
                    this.promisefy(this._clear, arguments) :
                    this._clear();
            };
            LocalStorage.prototype._clear = function () {
                var keys = Object.keys(localStorage);
                var spacedKeys = PhaserSuperStorage.StorageUtils.nameSpaceKeyFilter(keys, this.namespace);
                for (var i = 0; i < spacedKeys.length; i++) {
                    localStorage.removeItem(spacedKeys[i]);
                }
                return;
            };
            LocalStorage.prototype.setNamespace = function (spacedName) {
                return this.forcePromises ?
                    this.promisefy(this._setNameSpace, arguments) :
                    this._setNameSpace(spacedName);
            };
            LocalStorage.prototype._setNameSpace = function (spacedName) {
                if (spacedName) {
                    this.namespace = spacedName + ':';
                }
            };
            LocalStorage.prototype.promisefy = function (value, args) {
                var _this = this;
                return new Promise(function (resolve, reject) {
                    resolve(value.apply(_this, args));
                });
            };
            return LocalStorage;
        }());
        StorageAdapters.LocalStorage = LocalStorage;
    })(StorageAdapters = PhaserSuperStorage.StorageAdapters || (PhaserSuperStorage.StorageAdapters = {}));
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StoragePlugin = (function () {
        function StoragePlugin(game) {
            if (undefined !== game) {
                Object.defineProperty(game, 'storage', {
                    value: this
                });
            }
            else {
                if (StoragePlugin.instance === null) {
                    StoragePlugin.instance = this;
                }
                else {
                    return StoragePlugin.instance;
                }
            }
            if (PhaserSuperStorage.StorageUtils.isLocalStorageSupport()) {
                this.setAdapter(new PhaserSuperStorage.StorageAdapters.LocalStorage());
            }
            else {
                this.setAdapter(new PhaserSuperStorage.StorageAdapters.CookieStorage());
            }
        }
        StoragePlugin.prototype.setAdapter = function (storageAdapter) {
            this.storage = storageAdapter;
        };
        Object.defineProperty(StoragePlugin.prototype, "forcePromises", {
            get: function () {
                return this.storage.forcePromises;
            },
            set: function (forceIt) {
                this.storage.forcePromises = forceIt;
            },
            enumerable: true,
            configurable: true
        });
        Object.defineProperty(StoragePlugin.prototype, "length", {
            get: function () {
                if (this.storage === null) {
                    return 0;
                }
                return this.storage.length;
            },
            enumerable: true,
            configurable: true
        });
        StoragePlugin.prototype.setNamespace = function (namedSpace) {
            if (this.storage !== null) {
                return this.storage.setNamespace(namedSpace);
            }
        };
        StoragePlugin.prototype.key = function (n) {
            if (this.storage === null) {
                return '';
            }
            return this.storage.key(n);
        };
        StoragePlugin.prototype.getItem = function (key) {
            if (this.storage === null) {
                return null;
            }
            return this.storage.getItem(key);
        };
        StoragePlugin.prototype.setItem = function (key, value) {
            if (this.storage !== null) {
                return this.storage.setItem(key, value);
            }
        };
        StoragePlugin.prototype.removeItem = function (key) {
            if (this.storage !== null) {
                return this.storage.removeItem(key);
            }
        };
        StoragePlugin.prototype.clear = function () {
            if (this.storage !== null) {
                return this.storage.clear();
            }
        };
        return StoragePlugin;
    }());
    StoragePlugin.instance = null;
    PhaserSuperStorage.StoragePlugin = StoragePlugin;
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
if (window.Phaser !== undefined) {
    Phaser.Utils.mixinPrototype(PhaserSuperStorage.StoragePlugin, Phaser.Plugin);
}
var PhaserSuperStorage;
(function (PhaserSuperStorage) {
    var StorageCommand;
    (function (StorageCommand) {
        StorageCommand[StorageCommand["init"] = 0] = "init";
        StorageCommand[StorageCommand["setItem"] = 1] = "setItem";
        StorageCommand[StorageCommand["getItem"] = 2] = "getItem";
        StorageCommand[StorageCommand["removeItem"] = 3] = "removeItem";
        StorageCommand[StorageCommand["clear"] = 4] = "clear";
        StorageCommand[StorageCommand["setNamespace"] = 5] = "setNamespace";
        StorageCommand[StorageCommand["length"] = 6] = "length";
        StorageCommand[StorageCommand["key"] = 7] = "key";
        StorageCommand[StorageCommand["error"] = 8] = "error";
    })(StorageCommand = PhaserSuperStorage.StorageCommand || (PhaserSuperStorage.StorageCommand = {}));
    var StorageUtils = (function () {
        function StorageUtils() {
        }
        StorageUtils.isLocalStorageSupport = function () {
            try {
                if (typeof localStorage === 'object') {
                    localStorage.setItem('testingLocalStorage', 'foo');
                    localStorage.removeItem('testingLocalStorage');
                    return true;
                }
            }
            catch (e) {
                return false;
            }
            return false;
        };
        StorageUtils.validateMessage = function (data) {
            if (data.hasOwnProperty('command')) {
                return data;
            }
            return null;
        };
        StorageUtils.nameSpaceKeyFilter = function (keys, namespace) {
            return keys.filter(function (keyName) {
                return (keyName.substring(0, namespace.length) === namespace);
            });
        };
        return StorageUtils;
    }());
    PhaserSuperStorage.StorageUtils = StorageUtils;
})(PhaserSuperStorage || (PhaserSuperStorage = {}));
//# sourceMappingURL=phaser-super-storage.js.map


text:
namespace LODS.SharePoint.ContentManagement.Exceptions {
    /// <summary>
    /// On the hosting side, resources necessary to launch the lab were unavailable.  This generally means
    /// a configuration error in the lab.
    /// </summary>
    public class LodInsufficientResourcesException: LodSystemException {
        /// <summary>
        /// On the hosting side, resources necessary to launch the lab were unavailable.  This generally means
        /// a configuration error in the lab.
        /// </summary>
        public LodInsufficientResourcesException() : base("Required resources for your lab are not available in the lab system for your request at this time.  Please try again later.") { }
    }
}


text:
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DotNet.Cli.Utils
{
    // Stupid-simple console manager
    public class Reporter
    {
        private static readonly Reporter NullReporter = new Reporter(console: null);
        private static object _lock = new object();

        private readonly AnsiConsole _console;

        static Reporter()
        {
            Reset();
        }

        private Reporter(AnsiConsole console)
        {
            _console = console;
        }

        public static Reporter Output { get; private set; }
        public static Reporter Error { get; private set; }
        public static Reporter Verbose { get; private set; }

        /// <summary>
        /// Resets the Reporters to write to the current Console Out/Error.
        /// </summary>
        public static void Reset()
        {
            lock (_lock)
            {
                Output = new Reporter(AnsiConsole.GetOutput());
                Error = new Reporter(AnsiConsole.GetError());
                Verbose = IsVerbose ?
                    new Reporter(AnsiConsole.GetOutput()) :
                    NullReporter;
            }
        }

        public static bool IsVerbose => CommandContext.IsVerbose();

        public void WriteLine(string message)
        {
            lock (_lock)
            {
                if (CommandContext.ShouldPassAnsiCodesThrough())
                {
                    _console?.Writer?.WriteLine(message);
                }
                else
                {
                    _console?.WriteLine(message);
                }
            }
        }

        public void WriteLine()
        {
            lock (_lock)
            {
                _console?.Writer?.WriteLine();
            }
        }

        public void Write(string message)
        {
            lock (_lock)
            {
                if (CommandContext.ShouldPassAnsiCodesThrough())
                {
                    _console?.Writer?.Write(message);
                }
                else
                {
                    _console?.Write(message);
                }
            }
        }
    }
}


text:
/**
 * RateCard.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package com.google.api.ads.dfp.v201306;

/**
 * Defines a collection of rules, including base rates for product
 * templates and products, premiums,
 *             proposal line item level adjustments and proposal level
 * adjustments.
 */
public class RateCard  implements java.io.Serializable {
    /* The ID of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google
     * when a rate card is created. */
    private java.lang.Long id;

    /* The name of the {@code RateCard}.
     *                 This attribute is required and has a maximum length
     * of 255 characters.
     *                 This attribute must also be case-insensitive unique. */
    private java.lang.String name;

    /* The status of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google.
     * Rate cards are
     *                 created in the {@link RateCardStatus#INACTIVE} state. */
    private com.google.api.ads.dfp.v201306.RateCardStatus status;

    /* The IDs of all teams this rate card is directly in.
     *                 This attribute is optional. */
    private long[] appliedTeamIds;

    public RateCard() {
    }

    public RateCard(
           java.lang.Long id,
           java.lang.String name,
           com.google.api.ads.dfp.v201306.RateCardStatus status,
           long[] appliedTeamIds) {
           this.id = id;
           this.name = name;
           this.status = status;
           this.appliedTeamIds = appliedTeamIds;
    }

    /**
     * Gets the id value for this RateCard.
     *
     * @return id   * The ID of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google
     * when a rate card is created.
     */
    public java.lang.Long getId() {
        return id;
    }

    /**
     * Sets the id value for this RateCard.
     *
     * @param id   * The ID of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google
     * when a rate card is created.
     */
    public void setId(java.lang.Long id) {
        this.id = id;
    }

    /**
     * Gets the name value for this RateCard.
     *
     * @return name   * The name of the {@code RateCard}.
     *                 This attribute is required and has a maximum length
     * of 255 characters.
     *                 This attribute must also be case-insensitive unique.
     */
    public java.lang.String getName() {
        return name;
    }

    /**
     * Sets the name value for this RateCard.
     *
     * @param name   * The name of the {@code RateCard}.
     *                 This attribute is required and has a maximum length
     * of 255 characters.
     *                 This attribute must also be case-insensitive unique.
     */
    public void setName(java.lang.String name) {
        this.name = name;
    }

    /**
     * Gets the status value for this RateCard.
     *
     * @return status   * The status of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google.
     * Rate cards are
     *                 created in the {@link RateCardStatus#INACTIVE} state.
     */
    public com.google.api.ads.dfp.v201306.RateCardStatus getStatus() {
        return status;
    }

    /**
     * Sets the status value for this RateCard.
     *
     * @param status   * The status of the {@code RateCard}.
     *                 This attribute is read-only and is assigned by Google.
     * Rate cards are
     *                 created in the {@link RateCardStatus#INACTIVE} state.
     */
    public void setStatus(com.google.api.ads.dfp.v201306.RateCardStatus status) {
        this.status = status;
    }

    /**
     * Gets the appliedTeamIds value for this RateCard.
     *
     * @return appliedTeamIds   * The IDs of all teams this rate card is directly in.
     *                 This attribute is optional.
     */
    public long[] getAppliedTeamIds() {
        return appliedTeamIds;
    }

    /**
     * Sets the appliedTeamIds value for this RateCard.
     *
     * @param appliedTeamIds   * The IDs of all teams this rate card is directly in.
     *                 This attribute is optional.
     */
    public void setAppliedTeamIds(long[] appliedTeamIds) {
        this.appliedTeamIds = appliedTeamIds;
    }

    public long getAppliedTeamIds(int i) {
        return this.appliedTeamIds[i];
    }

    public void setAppliedTeamIds(int i, long _value) {
        this.appliedTeamIds[i] = _value;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof RateCard)) return false;
        RateCard other = (RateCard) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.id==null && other.getId()==null) ||
             (this.id!=null &&
              this.id.equals(other.getId()))) &&
            ((this.name==null && other.getName()==null) ||
             (this.name!=null &&
              this.name.equals(other.getName()))) &&
            ((this.status==null && other.getStatus()==null) ||
             (this.status!=null &&
              this.status.equals(other.getStatus()))) &&
            ((this.appliedTeamIds==null && other.getAppliedTeamIds()==null) ||
             (this.appliedTeamIds!=null &&
              java.util.Arrays.equals(this.appliedTeamIds, other.getAppliedTeamIds())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getId() != null) {
            _hashCode += getId().hashCode();
        }
        if (getName() != null) {
            _hashCode += getName().hashCode();
        }
        if (getStatus() != null) {
            _hashCode += getStatus().hashCode();
        }
        if (getAppliedTeamIds() != null) {
            for (int i=0;
                 i<java.lang.reflect.Array.getLength(getAppliedTeamIds());
                 i++) {
                java.lang.Object obj = java.lang.reflect.Array.get(getAppliedTeamIds(), i);
                if (obj != null &&
                    !obj.getClass().isArray()) {
                    _hashCode += obj.hashCode();
                }
            }
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(RateCard.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "RateCard"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("id");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "id"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("name");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "name"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("status");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "status"));
        elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "RateCardStatus"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("appliedTeamIds");
        elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201306", "appliedTeamIds"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
        elemField.setMinOccurs(0);
        elemField.setNillable(false);
        elemField.setMaxOccursUnbounded(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
"""Utils for serializing data as pybullet state or x100 training tfrecords."""
import collections
import os
from typing import List

from ibc.environments.utils.utils_pybullet import write_pybullet_state
import tensorflow as tf
from tf_agents.trajectories import policy_step
from tf_agents.trajectories import trajectory
from tf_agents.utils import example_encoding_dataset

EpisodeData = collections.namedtuple('EpisodeData',
                                     ('time_step', 'action', 'pybullet_state'))

def get_tfrecord_observers(env,
                           tfagents_path=None,
                           worker_id=None,
                           dataset_nshards=None):
  """Initialize TFAgent observers (for saving tfrecord data). One per shard."""
  observers = []
  if tfagents_path:
    tf.io.gfile.makedirs(os.path.dirname(tfagents_path))
    observers = _init_observers(env, tfagents_path, worker_id, dataset_nshards)
  return observers

def _init_observers(env, tfagents_path, worker_id, dataset_nshards):
  """Initialize TFAgent observers (for saving data). One per shard."""
  observers = []
  for i in range(dataset_nshards):
    dataset_split_path = os.path.splitext(tfagents_path)
    data_spec = trajectory.from_transition(
        env.time_step_spec(), policy_step.PolicyStep(env.action_spec()),
        env.time_step_spec())
    observers.append(
        example_encoding_dataset.TFRecordObserver(
            dataset_split_path[0] + '_%d' % i + '_worker-%d' % worker_id +
            dataset_split_path[1],
            data_spec,
            py_mode=True,
            compress_image=True))
  return observers

def write_tfagents_data(
    episode_data,
    observer):
  """Write out the episode data using the TFRecordObserver."""
  assert episode_data.action, 'empty episode (got done on reset)'
  assert len(episode_data.action) + 1 == len(episode_data.time_step)
  for i in range(len(episode_data.action)):
    traj = trajectory.from_transition(episode_data.time_step[i],
                                      episode_data.action[i],
                                      episode_data.time_step[i + 1])
    observer(traj)

def write_pybullet_data(task,
                        pybullet_state_path,
                        episode_data,
                        i_episode,
                        worker_id):
  """Write out the pybullet json for replay."""
  actions = [policy_step.action.tolist() for policy_step in episode_data.action]
  filename = '%s_ep%d_worker-%d.json.zip' % (pybullet_state_path, i_episode,
                                             worker_id)
  write_pybullet_state(
      filename, episode_data.pybullet_state, task, actions=actions)


text:
select.form-control + .chzn-container.chzn-container-single .chzn-single {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    vertical-align: middle;
    background-color: #fff;
    border: 1px solid #ccc;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
    box-shadow: inset 0 1px 1px rgba(0,0,0,0.075);
    -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s;
    background-image:none;
}

select.form-control + .chzn-container.chzn-container-single .chzn-single div {
    top:4px;
    color:#000;
}

select.form-control + .chzn-container .chzn-drop {
    background-color: #FFF;
    border: 1px solid #CCC;
    border: 1px solid rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
    background-clip: padding-box;
    margin: 2px 0 0;

}

select.form-control + .chzn-container .chzn-search input[type=text] {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    vertical-align: middle;
    background-color: #FFF;
    border: 1px solid #CCC;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
    transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
    background-image:none;
}

select.form-control + .chzn-container .chzn-results {
    margin: 2px 0 0;
    padding: 5px 0;
    font-size: 14px;
    list-style: none;
    background-color: #fff;
    margin-bottom: 5px;
}

select.form-control + .chzn-container .chzn-results li ,
select.form-control + .chzn-container .chzn-results li.active-result {
    display: block;
    padding: 3px 20px;
    clear: both;
    font-weight: normal;
    line-height: 1.428571429;
    color: #333;
    white-space: nowrap;
    background-image:none;
}
select.form-control + .chzn-container .chzn-results li:hover,
select.form-control + .chzn-container .chzn-results li.active-result:hover,
select.form-control + .chzn-container .chzn-results li.highlighted
{
    color: #FFF;
    text-decoration: none;
    background-color: #428BCA;
    background-image:none;
}

select.form-control + .chzn-container-multi .chzn-choices {
    display: block;
    width: 100%;
    min-height: 34px;
    padding: 6px;
    font-size: 14px;
    line-height: 1.428571429;
    color: #555;
    vertical-align: middle;
    background-color: #FFF;
    border: 1px solid #CCC;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
    -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
    transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
    background-image:none;
}

select.form-control + .chzn-container-multi .chzn-choices li.search-field input[type="text"] {
    height:auto;
    padding:5px 0;
}

select.form-control + .chzn-container-multi .chzn-choices li.search-choice {

    background-image: none;
    padding: 3px 24px 3px 5px;
    margin: 0 6px 0 0;
    font-size: 14px;
    font-weight: normal;
    line-height: 1.428571429;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    cursor: pointer;
    border: 1px solid #ccc;
    border-radius: 4px;
    color: #333;
    background-color: #FFF;
    border-color: #CCC;
}

select.form-control + .chzn-container-multi .chzn-choices li.search-choice .search-choice-close {
    top:8px;
    right:6px;
}

select.form-control + .chzn-container-multi.chzn-container-active .chzn-choices,
select.form-control + .chzn-container.chzn-container-single.chzn-container-active .chzn-single,
select.form-control + .chzn-container .chzn-search input[type=text]:focus{
    border-color: #66AFE9;
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),0 0 8px rgba(102, 175, 233, 0.6);
}

select.form-control + .chzn-container-multi .chzn-results li.result-selected{
    display: list-item;
    color: #ccc;
    cursor: default;
    background-color: white;
}


text:
// ::color::get:: hue( c )

 namespace color
  {
   namespace get
    {

     template< typename tag_name >
      inline
      typename ::color::model< ::color::category::LabCH< tag_name> >::component_const_type
      hue( ::color::model< ::color::category::LabCH<tag_name> > const& color_parameter )
       {
        typedef ::color::category::LabCH< tag_name>  category_type;
        enum
         {
          hue_p  = ::color::place::_internal::hue<category_type>::position_enum
         };

        return color_parameter.template get<hue_p>();
       }

    }
  }

#endif


text:
		<
		>

{{artists[whichItem].name}}

{{artists[whichItem].reknown}}

{{artists[whichItem].bio}}

	«返回搜索页面