text:
"""Autoscaler monitoring loop daemon."""

import argparse
import json
import logging.handlers
import os
import signal
import sys
import time
import traceback
from dataclasses import asdict
from typing import Any, Callable, Dict, Optional, Union

import ray
import ray._private.ray_constants as ray_constants
import ray._private.utils
from ray._private.event.event_logger import get_event_logger
from ray._private.gcs_pubsub import GcsPublisher
from ray._private.gcs_utils import GcsClient
from ray._private.ray_logging import setup_component_logger
from ray.autoscaler._private.autoscaler import StandardAutoscaler
from ray.autoscaler._private.commands import teardown_cluster
from ray.autoscaler._private.constants import (
    AUTOSCALER_MAX_RESOURCE_DEMAND_VECTOR_SIZE,
    AUTOSCALER_METRIC_PORT,
    AUTOSCALER_UPDATE_INTERVAL_S,
)
from ray.autoscaler._private.event_summarizer import EventSummarizer
from ray.autoscaler._private.load_metrics import LoadMetrics
from ray.autoscaler._private.prom_metrics import AutoscalerPrometheusMetrics
from ray.autoscaler._private.util import format_readonly_node_type
from ray.core.generated import gcs_pb2, gcs_service_pb2, gcs_service_pb2_grpc
from ray.core.generated.event_pb2 import Event as RayEvent
from ray.experimental.internal_kv import (
    _initialize_internal_kv,
    _internal_kv_del,
    _internal_kv_get,
    _internal_kv_initialized,
    _internal_kv_put,
)

try:
    import prometheus_client
except ImportError:
    prometheus_client = None

logger = logging.getLogger(__name__)

def parse_resource_demands(resource_load_by_shape):
    """Handle the message.resource_load_by_shape protobuf for the demand
    based autoscaling. Catch and log all exceptions so this doesn't
    interfere with the utilization based autoscaler until we're confident
    this is stable. Worker queue backlogs are added to the appropriate
    resource demand vector.

    Args:
        resource_load_by_shape (pb2.gcs.ResourceLoad): The resource demands
            in protobuf form or None.

    Returns:
        List[ResourceDict]: Waiting bundles (ready and feasible).
        List[ResourceDict]: Infeasible bundles.
    """
    waiting_bundles, infeasible_bundles = [], []
    try:
        for resource_demand_pb in list(resource_load_by_shape.resource_demands):
            request_shape = dict(resource_demand_pb.shape)
            for _ in range(resource_demand_pb.num_ready_requests_queued):
                waiting_bundles.append(request_shape)
            for _ in range(resource_demand_pb.num_infeasible_requests_queued):
                infeasible_bundles.append(request_shape)

            # Infeasible and ready states for tasks are (logically)
            # mutually exclusive.
            if resource_demand_pb.num_infeasible_requests_queued > 0:
                backlog_queue = infeasible_bundles
            else:
                backlog_queue = waiting_bundles
            for _ in range(resource_demand_pb.backlog_size):
                backlog_queue.append(request_shape)
            if (
                len(waiting_bundles + infeasible_bundles)
                > AUTOSCALER_MAX_RESOURCE_DEMAND_VECTOR_SIZE
            ):
                break
    except Exception:
        logger.exception("Failed to parse resource demands.")

    return waiting_bundles, infeasible_bundles

# Readonly provider config (e.g., for laptop mode, manually setup clusters).
BASE_READONLY_CONFIG = {
    "cluster_name": "default",
    "max_workers": 0,
    "upscaling_speed": 1.0,
    "docker": {},
    "idle_timeout_minutes": 0,
    "provider": {
        "type": "readonly",
        "use_node_id_as_ip": True,  # For emulated multi-node on laptop.
    },
    "auth": {},
    "available_node_types": {
        "ray.head.default": {"resources": {}, "node_config": {}, "max_workers": 0}
    },
    "head_node_type": "ray.head.default",
    "file_mounts": {},
    "cluster_synced_files": [],
    "file_mounts_sync_continuously": False,
    "rsync_exclude": [],
    "rsync_filter": [],
    "initialization_commands": [],
    "setup_commands": [],
    "head_setup_commands": [],
    "worker_setup_commands": [],
    "head_start_ray_commands": [],
    "worker_start_ray_commands": [],
    "head_node": {},
    "worker_nodes": {},
}

class Monitor:
    """Autoscaling monitor.

    This process periodically collects stats from the GCS and triggers
    autoscaler updates.
    """

    def __init__(
        self,
        address: str,
        autoscaling_config: Union[str, Callable[[], Dict[str, Any]]],
        log_dir: str = None,
        prefix_cluster_info: bool = False,
        monitor_ip: Optional[str] = None,
        retry_on_failure: bool = True,
    ):
        self.gcs_address = address
        options = ray_constants.GLOBAL_GRPC_OPTIONS
        gcs_channel = ray._private.utils.init_grpc_channel(self.gcs_address, options)
        # TODO: Use gcs client for this
        self.gcs_node_resources_stub = (
            gcs_service_pb2_grpc.NodeResourceInfoGcsServiceStub(gcs_channel)
        )
        self.gcs_node_info_stub = gcs_service_pb2_grpc.NodeInfoGcsServiceStub(
            gcs_channel
        )
        worker = ray._private.worker.global_worker
        gcs_client = GcsClient(address=self.gcs_address)

        if monitor_ip:
            monitor_addr = f"{monitor_ip}:{AUTOSCALER_METRIC_PORT}"
            gcs_client.internal_kv_put(
                b"AutoscalerMetricsAddress", monitor_addr.encode(), True, None
            )
        _initialize_internal_kv(gcs_client)
        if monitor_ip:
            monitor_addr = f"{monitor_ip}:{AUTOSCALER_METRIC_PORT}"
            gcs_client.internal_kv_put(
                b"AutoscalerMetricsAddress", monitor_addr.encode(), True, None
            )
        worker.mode = 0
        head_node_ip = self.gcs_address.split(":")[0]

        self.load_metrics = LoadMetrics()
        self.last_avail_resources = None
        self.event_summarizer = EventSummarizer()
        self.prefix_cluster_info = prefix_cluster_info
        self.retry_on_failure = retry_on_failure
        self.autoscaling_config = autoscaling_config
        self.autoscaler = None
        # If set, we are in a manually created cluster (non-autoscaling) and
        # simply mirroring what the GCS tells us the cluster node types are.
        self.readonly_config = None

        if log_dir:
            try:
                self.event_logger = get_event_logger(
                    RayEvent.SourceType.AUTOSCALER, log_dir
                )
            except Exception:
                self.event_logger = None
        else:
            self.event_logger = None

        self.prom_metrics = AutoscalerPrometheusMetrics()
        if monitor_ip and prometheus_client:
            # If monitor_ip wasn't passed in, then don't attempt to start the
            # metric server to keep behavior identical to before metrics were
            # introduced
            try:
                logger.info(
                    "Starting autoscaler metrics server on port {}".format(
                        AUTOSCALER_METRIC_PORT
                    )
                )
                kwargs = {"addr": "127.0.0.1"} if head_node_ip == "127.0.0.1" else {}
                prometheus_client.start_http_server(
                    port=AUTOSCALER_METRIC_PORT,
                    registry=self.prom_metrics.registry,
                    **kwargs,
                )
            except Exception:
                logger.exception(
                    "An exception occurred while starting the metrics server."
                )
        elif not prometheus_client:
            logger.warning(
                "`prometheus_client` not found, so metrics will not be exported."
            )

        logger.info("Monitor: Started")

    def _initialize_autoscaler(self):
        if self.autoscaling_config:
            autoscaling_config = self.autoscaling_config
        else:
            # This config mirrors the current setup of the manually created
            # cluster. Each node gets its own unique node type.
            self.readonly_config = BASE_READONLY_CONFIG

            # Note that the "available_node_types" of the config can change.
            def get_latest_readonly_config():
                return self.readonly_config

            autoscaling_config = get_latest_readonly_config
        self.autoscaler = StandardAutoscaler(
            autoscaling_config,
            self.load_metrics,
            self.gcs_node_info_stub,
            prefix_cluster_info=self.prefix_cluster_info,
            event_summarizer=self.event_summarizer,
            prom_metrics=self.prom_metrics,
        )

    def update_load_metrics(self):
        """Fetches resource usage data from GCS and updates load metrics."""

        request = gcs_service_pb2.GetAllResourceUsageRequest()
        response = self.gcs_node_resources_stub.GetAllResourceUsage(request, timeout=60)
        resources_batch_data = response.resource_usage_data
        log_resource_batch_data_if_desired(resources_batch_data)

        # Tell the readonly node provider what nodes to report.
        if self.readonly_config:
            new_nodes = []
            for msg in list(resources_batch_data.batch):
                node_id = msg.node_id.hex()
                new_nodes.append((node_id, msg.node_manager_address))
            self.autoscaler.provider._set_nodes(new_nodes)

        mirror_node_types = {}
        cluster_full = False
        if (
            hasattr(response, "cluster_full_of_actors_detected_by_gcs")
            and response.cluster_full_of_actors_detected_by_gcs
        ):
            # GCS has detected the cluster full of actors.
            cluster_full = True
        for resource_message in resources_batch_data.batch:
            node_id = resource_message.node_id
            # Generate node type config based on GCS reported node list.
            if self.readonly_config:
                # Keep prefix in sync with ReadonlyNodeProvider.
                node_type = format_readonly_node_type(node_id.hex())
                resources = {}
                for k, v in resource_message.resources_total.items():
                    resources[k] = v
                mirror_node_types[node_type] = {
                    "resources": resources,
                    "node_config": {},
                    "max_workers": 1,
                }
            if (
                hasattr(resource_message, "cluster_full_of_actors_detected")
                and resource_message.cluster_full_of_actors_detected
            ):
                # A worker node has detected the cluster full of actors.
                cluster_full = True
            resource_load = dict(resource_message.resource_load)
            total_resources = dict(resource_message.resources_total)
            available_resources = dict(resource_message.resources_available)

            waiting_bundles, infeasible_bundles = parse_resource_demands(
                resources_batch_data.resource_load_by_shape
            )

            pending_placement_groups = list(
                resources_batch_data.placement_group_load.placement_group_data
            )

            use_node_id_as_ip = self.autoscaler is not None and self.autoscaler.config[
                "provider"
            ].get("use_node_id_as_ip", False)

            # "use_node_id_as_ip" is a hack meant to address situations in
            # which there's more than one Ray node residing at a given ip.
            # TODO (Dmitri): Stop using ips as node identifiers.
            # https://github.com/ray-project/ray/issues/19086
            if use_node_id_as_ip:
                peloton_id = total_resources.get("NODE_ID_AS_RESOURCE")
                # Legacy support https://github.com/ray-project/ray/pull/17312
                if peloton_id is not None:
                    ip = str(int(peloton_id))
                else:
                    ip = node_id.hex()
            else:
                ip = resource_message.node_manager_address
            self.load_metrics.update(
                ip,
                node_id,
                total_resources,
                available_resources,
                resource_load,
                waiting_bundles,
                infeasible_bundles,
                pending_placement_groups,
                cluster_full,
            )
        if self.readonly_config:
            self.readonly_config["available_node_types"].update(mirror_node_types)

    def update_resource_requests(self):
        """Fetches resource requests from the internal KV and updates load."""
        if not _internal_kv_initialized():
            return
        data = _internal_kv_get(
            ray._private.ray_constants.AUTOSCALER_RESOURCE_REQUEST_CHANNEL
        )
        if data:
            try:
                resource_request = json.loads(data)
                self.load_metrics.set_resource_requests(resource_request)
            except Exception:
                logger.exception("Error parsing resource requests")

    def _run(self):
        """Run the monitor loop."""
        while True:
            try:
                gcs_request_start_time = time.time()
                self.update_load_metrics()
                gcs_request_time = time.time() - gcs_request_start_time
                self.update_resource_requests()
                self.update_event_summary()
                load_metrics_summary = self.load_metrics.summary()
                status = {
                    "gcs_request_time": gcs_request_time,
                    "load_metrics_report": asdict(load_metrics_summary),
                    "time": time.time(),
                    "monitor_pid": os.getpid(),
                }

                if self.autoscaler and not self.load_metrics:
                    # load_metrics is Falsey iff we haven't collected any
                    # resource messages from the GCS, which can happen at startup if
                    # the GCS hasn't yet received data from the Raylets.
                    # In this case, do not do an autoscaler update.
                    # Wait to get load metrics.
                    logger.info(
                        "Autoscaler has not yet received load metrics. Waiting."
                    )
                elif self.autoscaler:
                    # Process autoscaling actions
                    self.autoscaler.update()
                    autoscaler_summary = self.autoscaler.summary()
                    if autoscaler_summary:
                        status["autoscaler_report"] = asdict(autoscaler_summary)
                        status[
                            "non_terminated_nodes_time"
                        ] = (
                            self.autoscaler.non_terminated_nodes.non_terminated_nodes_time  # noqa: E501
                        )

                        for resource_name in ["CPU", "GPU"]:
                            _, total = load_metrics_summary.usage.get(
                                resource_name, (0, 0)
                            )
                            pending = autoscaler_summary.pending_resources.get(
                                resource_name, 0
                            )
                            self.prom_metrics.cluster_resources.labels(
                                resource=resource_name
                            ).set(total)
                            self.prom_metrics.pending_resources.labels(
                                resource=resource_name
                            ).set(pending)

                    for msg in self.event_summarizer.summary():
                        # Need to prefix each line of the message for the lines to
                        # get pushed to the driver logs.
                        for line in msg.split("\n"):
                            logger.info(
                                "{}{}".format(
                                    ray_constants.LOG_PREFIX_EVENT_SUMMARY, line
                                )
                            )
                            if self.event_logger:
                                self.event_logger.info(line)

                    self.event_summarizer.clear()

                as_json = json.dumps(status)
                if _internal_kv_initialized():
                    _internal_kv_put(
                        ray_constants.DEBUG_AUTOSCALING_STATUS, as_json, overwrite=True
                    )
            except Exception:
                # By default, do not exit the monitor on failure.
                if self.retry_on_failure:
                    logger.exception("Monitor: Execution exception. Trying again...")
                else:
                    raise

            # Wait for a autoscaler update interval before processing the next
            # round of messages.
            time.sleep(AUTOSCALER_UPDATE_INTERVAL_S)

    def update_event_summary(self):
        """Report the current size of the cluster.

        To avoid log spam, only cluster size changes (CPU or GPU count change)
        are reported to the event summarizer. The event summarizer will report
        only the latest cluster size per batch.
        """
        avail_resources = self.load_metrics.resources_avail_summary()
        if not self.readonly_config and avail_resources != self.last_avail_resources:
            self.event_summarizer.add(
                "Resized to {}.",  # e.g., Resized to 100 CPUs, 4 GPUs.
                quantity=avail_resources,
                aggregate=lambda old, new: new,
            )
            self.last_avail_resources = avail_resources

    def destroy_autoscaler_workers(self):
        """Cleanup the autoscaler, in case of an exception in the run() method.

        We kill the worker nodes, but retain the head node in order to keep
        logs around, keeping costs minimal. This monitor process runs on the
        head node anyway, so this is more reliable."""

        if self.autoscaler is None:
            return  # Nothing to clean up.

        if self.autoscaling_config is None:
            # This is a logic error in the program. Can't do anything.
            logger.error("Monitor: Cleanup failed due to lack of autoscaler config.")
            return

        logger.info("Monitor: Exception caught. Taking down workers...")
        clean = False
        while not clean:
            try:
                teardown_cluster(
                    config_file=self.autoscaling_config,
                    yes=True,  # Non-interactive.
                    workers_only=True,  # Retain head node for logs.
                    override_cluster_name=None,
                    keep_min_workers=True,  # Retain minimal amount of workers.
                )
                clean = True
                logger.info("Monitor: Workers taken down.")
            except Exception:
                logger.error("Monitor: Cleanup exception. Trying again...")
                time.sleep(2)

    def _handle_failure(self, error):
        logger.exception("Error in monitor loop")
        if (
            self.autoscaler is not None
            and os.environ.get("RAY_AUTOSCALER_FATESHARE_WORKERS", "") == "1"
        ):
            self.autoscaler.kill_workers()
            # Take down autoscaler workers if necessary.
            self.destroy_autoscaler_workers()

        # Something went wrong, so push an error to all current and future
        # drivers.
        message = f"The autoscaler failed with the following error:\n{error}"
        if _internal_kv_initialized():
            _internal_kv_put(
                ray_constants.DEBUG_AUTOSCALING_ERROR, message, overwrite=True
            )
        gcs_publisher = GcsPublisher(address=self.gcs_address)
        from ray._private.utils import publish_error_to_driver

        publish_error_to_driver(
            ray_constants.MONITOR_DIED_ERROR,
            message,
            gcs_publisher=gcs_publisher,
        )

    def _signal_handler(self, sig, frame):
        try:
            self._handle_failure(
                f"Terminated with signal {sig}\n"
                + "".join(traceback.format_stack(frame))
            )
        except Exception:
            logger.exception("Monitor: Failure in signal handler.")
        sys.exit(sig + 128)

    def run(self):
        # Register signal handlers for autoscaler termination.
        # Signals will not be received on windows
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
        try:
            if _internal_kv_initialized():
                # Delete any previous autoscaling errors.
                _internal_kv_del(ray_constants.DEBUG_AUTOSCALING_ERROR)
            self._initialize_autoscaler()
            self._run()
        except Exception:
            self._handle_failure(traceback.format_exc())
            raise

def log_resource_batch_data_if_desired(
    resources_batch_data: gcs_pb2.ResourceUsageBatchData,
) -> None:
    if os.getenv("AUTOSCALER_LOG_RESOURCE_BATCH_DATA") == "1":
        logger.info("Logging raw resource message pulled from GCS.")
        logger.info(resources_batch_data)
        logger.info("Done logging raw resource message.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=("Parse GCS server for the monitor to connect to.")
    )
    parser.add_argument(
        "--gcs-address", required=False, type=str, help="The address (ip:port) of GCS."
    )
    parser.add_argument(
        "--redis-address", required=False, type=str, help="This is deprecated"
    )
    parser.add_argument(
        "--redis-password",
        required=False,
        type=str,
        default=None,
        help="This is deprecated",
    )
    parser.add_argument(
        "--autoscaling-config",
        required=False,
        type=str,
        help="the path to the autoscaling config file",
    )
    parser.add_argument(
        "--logging-level",
        required=False,
        type=str,
        default=ray_constants.LOGGER_LEVEL,
        choices=ray_constants.LOGGER_LEVEL_CHOICES,
        help=ray_constants.LOGGER_LEVEL_HELP,
    )
    parser.add_argument(
        "--logging-format",
        required=False,
        type=str,
        default=ray_constants.LOGGER_FORMAT,
        help=ray_constants.LOGGER_FORMAT_HELP,
    )
    parser.add_argument(
        "--logging-filename",
        required=False,
        type=str,
        default=ray_constants.MONITOR_LOG_FILE_NAME,
        help="Specify the name of log file, "
        "log to stdout if set empty, default is "
        f'"{ray_constants.MONITOR_LOG_FILE_NAME}"',
    )
    parser.add_argument(
        "--logs-dir",
        required=True,
        type=str,
        help="Specify the path of the temporary directory used by Ray processes.",
    )
    parser.add_argument(
        "--logging-rotate-bytes",
        required=False,
        type=int,
        default=ray_constants.LOGGING_ROTATE_BYTES,
        help="Specify the max bytes for rotating "
        "log file, default is "
        f"{ray_constants.LOGGING_ROTATE_BYTES} bytes.",
    )
    parser.add_argument(
        "--logging-rotate-backup-count",
        required=False,
        type=int,
        default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT,
        help="Specify the backup count of rotated log file, default is "
        f"{ray_constants.LOGGING_ROTATE_BACKUP_COUNT}.",
    )
    parser.add_argument(
        "--monitor-ip",
        required=False,
        type=str,
        default=None,
        help="The IP address of the machine hosting the monitor process.",
    )

    args = parser.parse_args()
    setup_component_logger(
        logging_level=args.logging_level,
        logging_format=args.logging_format,
        log_dir=args.logs_dir,
        filename=args.logging_filename,
        max_bytes=args.logging_rotate_bytes,
        backup_count=args.logging_rotate_backup_count,
    )

    logger.info(f"Starting monitor using ray installation: {ray.__file__}")
    logger.info(f"Ray version: {ray.__version__}")
    logger.info(f"Ray commit: {ray.__commit__}")
    logger.info(f"Monitor started with command: {sys.argv}")

    if args.autoscaling_config:
        autoscaling_config = os.path.expanduser(args.autoscaling_config)
    else:
        autoscaling_config = None

    bootstrap_address = args.gcs_address
    if bootstrap_address is None:
        raise ValueError("--gcs-address must be set!")

    monitor = Monitor(
        bootstrap_address,
        autoscaling_config,
        log_dir=args.logs_dir,
        monitor_ip=args.monitor_ip,
    )

    monitor.run()


text:
<?php
namespace Bolt\Extension\IComeFromTheNet\BookMe\Bundle\HolidayRule\Model;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\DBALException;

use Bolt\Extension\IComeFromTheNet\BookMe\Bundle\HolidayRule\Model\Command\SaveHolidayCommand;

class HolidayRuleCreator
{

    /**
     *  @var Connection
     */
    protected $oDatabase;

    public function __construct (Connection $oDatabase)
    {
        $this->oDatabase = $oDatabase;

    }

    public function newRule()
    {

    }

    public function forMember($iMemberId)
    {

    }

    public function forCalendarYear()
    {

    }

}
/* End of Class */

redpajama_set_name: RedPajamaGithub


text:
"""AppAssure 5 Core API"""

from appassure.api import AppAssureAPI

class ICoreCallbackManagement(AppAssureAPI):
    """Full documentation online at
    http://docs.appassure.com/display/AA50D/ICoreCallbackManagement
    """

    def processAgentProtectionRequest(self, data):
        """The method is called by failover agent in order to
        perform remote pairing. This method is for internal usage
        only.
        """
        return self.session.request('corecallback/agentprotectionrequest', 'POST',
                    self.getXML(data, 'coreCallbackRequest'))

    def verifyConnect(self):
        """Called by agent to verify connectivity to this core."""
        return self.session.request('corecallback/connect')


text:
require 'spec_helper'

describe Github do
  let(:method) { 'create_repos'}
  let(:alt_method) { 'repos.create'}

  it { described_class.constants.should include :DEPRECATION_PREFIX }

  context '.deprecate' do
    before do
      Github.deprecation_tracker = []
    end

    it 'tracks messages' do
      Github.should_receive(:warn).once()
      Github.deprecate(method)
      Github.deprecate(method)
    end

    it 'prints the message through Kernel' do
      Github.should_receive(:warn).once()
      Github.deprecate method
    end
  end

  it 'prints the message through Kernel' do
    Github.should_receive(:warn)
    Github.warn_deprecation method
  end
end # Github


text:
[![Version](https://vsmarketplacebadge.apphb.com/version/tobiasalthoff.atom-material-theme.svg)](https://marketplace.visualstudio.com/items?itemName=tobiasalthoff.atom-material-theme)
[![Rating](https://vsmarketplacebadge.apphb.com/rating/tobiasalthoff.atom-material-theme.svg)](https://marketplace.visualstudio.com/items?itemName=tobiasalthoff.atom-material-theme)
[![Downloads](https://vsmarketplacebadge.apphb.com/downloads/tobiasalthoff.atom-material-theme.svg)](https://marketplace.visualstudio.com/items?itemName=tobiasalthoff.atom-material-theme)

> This Theme based on [atom-material-ui](https://github.com/atom-material/atom-material-ui) and [atom-material-syntax](https://github.com/atom-material/atom-material-syntax)

![Preview](https://raw.githubusercontent.com/tobiasalthoff/vscode-atom-material-theme/main/images/screenshot.png)

## Installation

1. Open Extensions sidebar panel in VS Code. **View → Extensions**
2. Search for **Atom Material Theme**
3. Click **Install** to install it.
4. Click **Reload** to reload the editor.
5. File > Preferences > Color Theme > Atom Material Theme

## Recommended Settings

```
{
  "editor.fontSize": 16,
  "editor.lineHeight": 1.5,
  "editor.letterSpacing": 0.5
}
```

## FAQ

### Which font do you use?

I use [Operator Mono](https://www.typography.com/fonts/operator/overview). Yes, I paid for it and it is worth every €€€ :-)

## Contributing

If something don't look correct, please open an issue. I'll try to fix it.

## Credits

- UI: [atom-material-ui](https://github.com/atom-material/atom-material-ui)
- Syntax: [atom-material-syntax](https://github.com/atom-material/atom-material-syntax)
- Samples: [Atom Language Examples](https://github.com/atom/language-examples)


text:
<?php

namespace rock\validate\rules;

class Space extends CType
{
    /**
     * @inheritdoc
     */
    public function validate($input)
    {
        if (!is_scalar($input) || $input === '') {
            return false;
        }
        $input = str_replace(str_split($this->params['additionalChars']), '', (string)$input);
        return $input === '' || ctype_space($input);
    }
}


text:
package com.tinymooc.handler.upload.controller;

import java.io.OutputStream;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tinymooc.util.FileUploadUtils;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {
	@RequestMapping("test.htm")
	public ModelAndView test() {
		return new ModelAndView("/test/testxheditors");
	}

	@RequestMapping("delFile.htm")
	public void delFile(HttpServletRequest request, OutputStream out) throws Exception {
		FileUploadUtils.DelFile(request, request.getParameter("url"));
	}

	@RequestMapping("uploadFile.htm")
	public void uploadfile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HashMap params = FileUploadUtils.UploadFile(request, response, "files");

		JSONObject responseInfo = JSONObject.fromObject("{'err':'','msg':'" + params.get("filedata") + "'}");
		response.getWriter().write(responseInfo.toString());
        // FIXME
        System.out.println("================responseInfo.toString()"+responseInfo.toString());
    }

	@RequestMapping("uploadPic.htm")
	public void uploadpic(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HashMap params = FileUploadUtils.UploadFile(request, response, "folder");
		JSONObject res=JSONObject.fromObject("{'err':'','msg':'"
				+ params.get("filedata") + "'}");
//		String responseInfo = JSONOperator.toJSON("{'err':'','msg':'"
//				+ params.get("filedata") + "'}");
		response.getWriter().write(res.toString());

        // FIXME
        String picUrl = params.get("filedata").toString();
        System.out.println("==============params.get(filedata)=="+picUrl);
        request.getSession().setAttribute("picUrl", picUrl);
	}

//	@RequestMapping("downloadFile.htm")
//	public void downloadFile(HttpServletRequest request,HttpServletResponse response){
//		String filePath=ServletRequestUtils.getStringParameter(request, "filePath", "");
//		try {
//			FileUploadUtils.downFile(request, response, filePath, null,true);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

}


text:
Stock Manager
-------------

Description later :D


text:
API中文手册
============

DataProvider API
----------------

..  toctree::
    :maxdepth: 1

    data_provider/dataprovider_cn.rst
    data_provider/pydataprovider2_cn.rst

..  _api_trainer_config:

Model Config API
----------------

..  toctree::
    :maxdepth: 1

    trainer_config_helpers/optimizers.rst
    trainer_config_helpers/data_sources.rst
    trainer_config_helpers/layers.rst
    trainer_config_helpers/activations.rst
    trainer_config_helpers/poolings.rst
    trainer_config_helpers/networks.rst
    trainer_config_helpers/evaluators.rst
    trainer_config_helpers/attrs.rst

Applications API
----------------

..  toctree::
    :maxdepth: 1

    predict/swig_py_paddle_cn.rst


text:
#ifndef __TEST_STAGE_H__
#define __TEST_STAGE_H__

#include "lagopus_apis.h"
#include "lagopus_pipeline_stage_internal.h"

typedef enum {
  test_stage_type_unknown = 0,
  test_stage_type_ingress,
  test_stage_type_intermediate,
  test_stage_type_egress
} test_stage_type_t;

typedef struct {
  size_t m_offset;
  size_t m_length;
} enqueue_info_t;

typedef enum {
  test_stage_state_unknown = 0,
  test_stage_state_initialized,
  test_stage_state_running,
  test_stage_state_done
} test_stage_state_t;

typedef struct test_stage_record {
  base_stage_record m_base_stg;

  test_stage_type_t m_type;

  lagopus_mutex_t m_lock;
  lagopus_cond_t m_cond;
  volatile bool m_do_exit;

  uint64_t *m_data;
  size_t m_n_data;
  enqueue_info_t *m_enq_infos;	/* The length is # of workers */

  test_stage_state_t *m_states;	/* The length is # of workers */

  size_t m_weight;

  volatile uint64_t m_sum;
  volatile size_t m_n_events;
  volatile uint64_t m_start_clock;
  volatile uint64_t m_end_clock;
  lagopus_chrono_t m_start_time;
  lagopus_chrono_t m_end_time;
} test_stage_record;
typedef test_stage_record	*test_stage_t;

typedef struct test_stage_spec_t {
  size_t m_n_workers;
  size_t m_n_qs;
  size_t m_q_len;
  size_t m_n_events;
  size_t m_batch_size;
  base_stage_sched_t m_sched_type;
  base_stage_fetch_t m_fetch_type;
  lagopus_chrono_t m_to;
} test_stage_spec_t;

#endif /* ! __TEST_STAGE_H__ */


text:
'use strict';

var React = require('react');

var d3 = require('d3');

var StyleConstants = require('../../constants/Style');

var LineGroup = React.createClass({
  displayName: 'LineGroup',

  propTypes: {
    adjustedHeight: React.PropTypes.number.isRequired,
    dashLine: React.PropTypes.bool,
    data: React.PropTypes.array.isRequired,
    lineColor: React.PropTypes.string,
    shouldAnimate: React.PropTypes.bool,
    strokeWidth: React.PropTypes.number,
    translation: React.PropTypes.string,
    xScaleValueFunction: React.PropTypes.func.isRequired,
    yScaleValueFunction: React.PropTypes.func.isRequired
  },

  getDefaultProps: function getDefaultProps() {
    return {
      dashLine: false,
      lineColor: StyleConstants.Colors.CHARCOAL,
      shouldAnimate: true,
      strokeWidth: 2,
      translation: 'translate(0,0)'
    };
  },
  componentWillMount: function componentWillMount() {
    var _this = this;

    var flatLine = d3.svg.line().x(function (d) {
      return _this.props.xScaleValueFunction(d.x);
    }).y(function () {
      return _this.props.adjustedHeight;
    });

    var line = d3.svg.line().x(function (d) {
      return _this.props.xScaleValueFunction(d.x);
    }).y(function (d) {
      return _this.props.yScaleValueFunction(d.y);
    });

    this.setState({
      flatLine: flatLine,
      line: line
    });
  },
  componentDidMount: function componentDidMount() {
    this._animateLine();
  },
  componentDidUpdate: function componentDidUpdate() {
    this._animateLine();
  },
  _animateLine: function _animateLine() {
    if (this.props.shouldAnimate) {
      d3.select(this.refs.chartLine).transition().attr('d', this.state.line(this.props.data));
    }
  },
  render: function render() {
    var _props = this.props;
    var data = _props.data;
    var dashLine = _props.dashLine;
    var lineColor = _props.lineColor;
    var shouldAnimate = _props.shouldAnimate;
    var strokeWidth = _props.strokeWidth;
    var translation = _props.translation;

    return React.createElement(
      'g',
      { className: 'chart-line-group', ref: 'chartLineGroup', transform: translation },
      React.createElement('path', {
        d: shouldAnimate ? this.state.flatLine(data) : this.state.line(data),
        fill: 'none',
        ref: 'chartLine',
        stroke: lineColor,
        strokeDasharray: dashLine ? '4,4' : 'none',
        strokeWidth: strokeWidth
      })
    );
  }
});

module.exports = LineGroup;


text:
package com.openshift.metrics.extension;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOVE;

import java.text.MessageFormat;
import java.util.Locale;

import org.jboss.as.controller.AbstractRemoveStepHandler;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.descriptions.DefaultOperationDescriptionProvider;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver;
import org.jboss.dmr.ModelNode;

public class MetricRemoveHandler extends AbstractRemoveStepHandler implements DescriptionProvider {
    public static final MetricRemoveHandler INSTANCE = new MetricRemoveHandler();

    public MetricRemoveHandler() {
    }

    @Override
    public ModelNode getModelDescription(Locale locale) {
        final StandardResourceDescriptionResolver resourceDescriptionResolver = OpenShiftSubsystemExtension.getResourceDescriptionResolver(Constants.METRICS_GROUP, Constants.SOURCE, Constants.METRIC);
        final DefaultOperationDescriptionProvider delegate = new DefaultOperationDescriptionProvider(REMOVE,
                resourceDescriptionResolver, MetricDefinition.SOURCE_KEY);
        return delegate.getModelDescription(locale);
    }

    @Override
    protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
        MetricsService service = (MetricsService) context.getServiceRegistry(true).getRequiredService(MetricsService.getServiceName()).getValue();
        final ModelNode address = operation.get(ModelDescriptionConstants.ADDRESS);
        final String schedule = PathAddress.pathAddress(address).getElement(1).getValue();
        final String source = PathAddress.pathAddress(address).getElement(2).getValue();
        String publishKey = PathAddress.pathAddress(address).getElement(3).getValue();
        final String cronExpression = Util.decodeCronExpression(schedule);
        try {
            service.removeMetric(cronExpression, source, publishKey);
        } catch (Exception e) {
            String message = MessageFormat.format("Encountered exception trying to remove metric[schedule={0}, source={1}, publishKey={2}]", cronExpression, source, publishKey);
            throw new OperationFailedException(message, e);
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="style_struc.css">
        <link rel="stylesheet" href="style_forms.css">
        <link rel="stylesheet" href="style_responsive.css">
        <title> Organisations | Let'sVolunteer </title>

        <?php  include("elements_struc/header.php"); ?>

 How we can help your organisation

 LetsVolunteer is a website that helps future volunteers find and sign up to volunteering offers. Our aim is to increase the volunteering activity and raising its awarness!

 Your organisation can be part of this project by registering to be in our database. Once you're entered in the database, users can follow your organisation to keep updated, favorite and sign up to volunteering offers you propose! Once users submitted a request for an activity, you will receive an email from us with all the information and you can then accept the request to confirm the activity scheduled!

 Having your offers as a part of our database will make your organisation more visible to potential volunteers and will help us raising awarness in volunteering!

 If you want to register and have your organisation represented on our website, please send an email to  letsvolunteer_organisations@gmail.com .
We look forward hearing from you.

        <?php include("elements_struc/footer.php"); ?>


text:
package com.emmett.testday;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.emmett.testday.model.question.QuestionPool;
import com.emmett.testday.states.*;

public class Main extends ApplicationAdapter {

	GameStateManager manager = new GameStateManager();

	@Override
	public void create () {

        Stage stage = new Stage(new FitViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
        Gdx.input.setInputProcessor(stage);
        stage.getViewport().apply();

        stage.addListener(new InputListener() {
            @Override
            public boolean keyDown(InputEvent event, int keycode) {
                if(keycode == Input.Keys.ENTER) {
                    GameState currentState = manager.currentState;
                    if(currentState != null) {
                        manager.setCurrentState(currentState.next());
                    }
                    return true;
                }
                return false;
            }
        });

        QuestionPool pool = new QuestionPool();
        pool.shuffle();
        TextBookState bookState = new TextBookState(pool, stage);
        ExamState examState = new ExamState(pool, stage);
        ExamState examState2 = new ExamState(pool, stage);
        ExamState examState3 = new ExamState(pool, stage);
        examState2.order = 1;
        examState3.order = 2;
        GradingState grades = new GradingState(pool, stage);
        TitleScreen title = new TitleScreen(stage);
        title.nextState = bookState;
        examState.manager = manager;
        examState2.manager = manager;
        examState3.manager = manager;
        bookState.nextState = examState;
        bookState.manager = manager;
        examState.nextState = examState2;
        examState2.nextState = examState3;
        examState3.nextState = grades;
        grades.nextState = bookState;

        manager = new GameStateManager();
        manager.setCurrentState(title);

	}

	@Override
	public void render () {
		manager.display();
	}

	@Override
	public void resize(int x, int y) {
		manager.resize(x, y);
	}

}


text:
using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(MvcSumator.Startup))]
namespace MvcSumator
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
        }
    }
}


text:
/*
 * socket_server.c
 *
 *  Created on: Sep 7, 2017
 *      Author: Murugan Viswanathan
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define MV_PORT 50123
#define DATASIZE (4*1024)

int main()
{
    int ret = 0;

    //Create Raw socket that allows TCP packets
    //int sock = socket(PF_INET, SOCK_RAW, IPPROTO_TCP);

    //Create TCP socket
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd == -1)
    {
        perror("[SERVER SOCKET] Error Creating Socket!\n");
        return 1;
    }

    /* set socket opt
    int opt = 1;
    ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    if(ret == -1)
    {
        perror("[SERVER SOCKET] Error setsockopt!\n");
        return 1;
    }
    */

    // bind : attach MV_PORT to socket
    struct sockaddr_in servAddr;
    servAddr.sin_family = AF_INET;
    servAddr.sin_addr.s_addr = INADDR_ANY;
    servAddr.sin_port = htons(MV_PORT);
    int addrlen = sizeof(servAddr);

    ret = bind(sockfd, (struct sockaddr*)&servAddr, addrlen);
    if(ret == -1)
    {
        perror("[SERVER SOCKET] Error bind!\n");
        return 1;
    }

    // listen for connection from client
    printf("[SERVER SOCKET] listening for connection...\n");
    static int count = 0;
    ret = listen(sockfd, 5); //max 5 connections allowed
    if(ret == -1)
    {
        perror("[SERVER SOCKET] Error listen!\n");
        return 1;
    }

    printf("[SERVER SOCKET] accepting connection... %d\n", ++count);
    //accept connection
    int new_socket = accept(sockfd, (struct sockaddr*)&servAddr, (socklen_t*)&addrlen);
    if(new_socket == -1)
    {
        perror("[SERVER SOCKET] Error accept!\n");
        return 1;
    }

    // read data
    char data[DATASIZE] = {0}; //4K buffer
    int valread = 0;
    do
    {
        valread = read(new_socket, data, DATASIZE);
        //sleep(1);
        send(new_socket , data , strlen(data) , 0 );
    }while (valread);

    return 0;
}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Nest
{
	[JsonObject(MemberSerialization.OptIn)]
	[JsonConverter(typeof(ProcessorJsonConverter<ForeachProcessor>))]
	public interface IForeachProcessor : IProcessor
	{
		[JsonProperty("field")]
		Field Field { get; set; }

		[JsonProperty("processor")]
		IProcessor Processor { get; set; }
	}

	public class ForeachProcessor : ProcessorBase, IForeachProcessor
	{
		protected override string Name => "foreach";
		public Field Field { get; set; }
		public IProcessor Processor { get; set; }
	}

	public class ForeachProcessorDescriptor<T>
		: ProcessorDescriptorBase<ForeachProcessorDescriptor<T>, IForeachProcessor>, IForeachProcessor
		where T : class
	{
		protected override string Name => "foreach";

		Field IForeachProcessor.Field { get; set; }

		IProcessor IForeachProcessor.Processor { get; set; }

		public ForeachProcessorDescriptor<T> Field(Field field) => Assign(a => a.Field = field);

		public ForeachProcessorDescriptor<T> Field(Expression<Func<T, object>> objectPath) =>
			Assign(a => a.Field = objectPath);

		public ForeachProcessorDescriptor<T> Processor(Func<ProcessorsDescriptor, IPromise<IList<IProcessor>>> selector) =>
			Assign(a => a.Processor = selector?.Invoke(new ProcessorsDescriptor())?.Value?.FirstOrDefault());
	}
}


text:
Companies

Companies that have been started in the Capstone

            {% for post in site.posts reversed%}

{{ post.title }}

{{ post.subtitle }}

            {% endfor %}


text:
#ifndef __LIBS_ELF_H__
#define __LIBS_ELF_H__

#include <defs.h>

#define ELF_MAGIC   0x464C457FU         // "\x7FELF" in little endian

/* file header */
struct elfhdr {
    uint32_t e_magic;     // must equal ELF_MAGIC
    uint8_t e_elf[12];
    uint16_t e_type;      // 1=relocatable, 2=executable, 3=shared object, 4=core image
    uint16_t e_machine;   // 3=x86, 4=68K, etc.
    uint32_t e_version;   // file version, always 1
    uint32_t e_entry;     // entry point if executable
    uint32_t e_phoff;     // file position of program header or 0
    uint32_t e_shoff;     // file position of section header or 0
    uint32_t e_flags;     // architecture-specific flags, usually 0
    uint16_t e_ehsize;    // size of this elf header
    uint16_t e_phentsize; // size of an entry in program header
    uint16_t e_phnum;     // number of entries in program header or 0
    uint16_t e_shentsize; // size of an entry in section header
    uint16_t e_shnum;     // number of entries in section header or 0
    uint16_t e_shstrndx;  // section number that contains section name strings
};

/* program section header */
struct proghdr {
    uint32_t p_type;   // loadable code or data, dynamic linking info,etc.
    uint32_t p_offset; // file offset of segment
    uint32_t p_va;     // virtual address to map segment
    uint32_t p_pa;     // physical address, not used
    uint32_t p_filesz; // size of segment in file
    uint32_t p_memsz;  // size of segment in memory (bigger if contains bss)
    uint32_t p_flags;  // read/write/execute bits
    uint32_t p_align;  // required alignment, invariably hardware page size
};

/* values for Proghdr::p_type */
#define ELF_PT_LOAD                     1

/* flag bits for Proghdr::p_flags */
#define ELF_PF_X                        1
#define ELF_PF_W                        2
#define ELF_PF_R                        4

#endif /* !__LIBS_ELF_H__ */


text:
using System.ComponentModel.DataAnnotations;
using Abp.MultiTenancy;

namespace Todo.MainProject.Authorization.Accounts.Dto
{
    public class IsTenantAvailableInput
    {
        [Required]
        [MaxLength(AbpTenantBase.MaxTenancyNameLength)]
        public string TenancyName { get; set; }
    }
}


text:
#ifndef TGBOT_VIDEOCHATSTARTED_H
#define TGBOT_VIDEOCHATSTARTED_H

#include <memory>

namespace TgBot {

/**
 * @brief This object represents a service message about a video chat started in the chat.
 * Currently holds no information.
 *
 * @ingroup types
 */
class VideoChatStarted {

public:
    typedef std::shared_ptr<VideoChatStarted> Ptr;
};
}

#endif //TGBOT_VIDEOCHATSTARTED_H


text:
    Cédula

      <input [formControl]="id" type="text" class="form-control" id="inputId" placeholder="ID">
      Inválido.

    Nombre

      <input [formControl]="name" type="text" class="form-control" id="inputName" placeholder="Nombre">
      Inválido.

    Contraseña

      <input [formControl]="password" type="password" class="form-control" id="inputPassword" placeholder="Contraseña">
      Inválido.

    Confirmar Contraseña

      <input [formControl]="confirm_password" type="password" class="form-control" id="inputConfirmPassword" placeholder="Confirmar Contraseña">
      Inválido.

    Correo

      <input [formControl]="email" type="email" class="form-control" id="inputEmail" placeholder="Correo">
      Inválido.

    Teléfono

      <input [formControl]="phone" type="number" class="form-control" id="inputPhone" placeholder="Teléfono">
      Inválido.

    Empresa?

      <input [formControl]="bussines" type="checkbox" class="form-control" id="inputbussines">
      Inválido.

    RIF

      <input [formControl]="id" type="text" class="form-control" id="inputRif" placeholder="RIF">
      Inválido.

    Razón Social

      <input [formControl]="businessname" type="text" class="form-control" id="inputBusinessname" placeholder="Razón Social">
      Inválido.


text:
namespace Calibrus.SparkPortal.DataAccess.Infrastructure
{
    using System;

    public partial class GetVerifiedChartDetail_Result
    {
        public string Disposition { get; set; }
        public Nullable<int> Calls { get; set; }
    }
}


text:
package com.amazonaws.services.identitymanagement.model;

import java.io.Serializable;

/**
 *

 * Contains information about an X.509 signing certificate.
 *

 *

 * This data type is used as a response element in the
 * UploadSigningCertificate and ListSigningCertificates actions.
 *

 */
public class SigningCertificate implements Serializable, Cloneable {

    /**
     *

     * The name of the user the signing certificate is associated with.
     *

     */
    private String userName;
    /**
     *

     * The ID for the signing certificate.
     *

     */
    private String certificateId;
    /**
     *

     * The contents of the signing certificate.
     *

     */
    private String certificateBody;
    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     */
    private String status;
    /**
     *

     * The date when the signing certificate was uploaded.
     *

     */
    private java.util.Date uploadDate;

    /**
     * Default constructor for SigningCertificate object. Callers should use the
     * setter or fluent setter (with...) methods to initialize the object after
     * creating it.
     */
    public SigningCertificate() {
    }

    /**
     * Constructs a new SigningCertificate object. Callers should use the setter
     * or fluent setter (with...) methods to initialize any additional object
     * members.
     *
     * @param userName
     *        The name of the user the signing certificate is associated with.
     * @param certificateId
     *        The ID for the signing certificate.
     * @param certificateBody
     *        The contents of the signing certificate.
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     */
    public SigningCertificate(String userName, String certificateId,
            String certificateBody, String status) {
        setUserName(userName);
        setCertificateId(certificateId);
        setCertificateBody(certificateBody);
        setStatus(status);
    }

    /**
     * Constructs a new SigningCertificate object. Callers should use the setter
     * or fluent setter (with...) methods to initialize any additional object
     * members.
     *
     * @param userName
     *        The name of the user the signing certificate is associated with.
     * @param certificateId
     *        The ID for the signing certificate.
     * @param certificateBody
     *        The contents of the signing certificate.
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     */
    public SigningCertificate(String userName, String certificateId,
            String certificateBody, StatusType status) {
        setUserName(userName);
        setCertificateId(certificateId);
        setCertificateBody(certificateBody);
        setStatus(status.toString());
    }

    /**
     *

     * The name of the user the signing certificate is associated with.
     *

     *
     * @param userName
     *        The name of the user the signing certificate is associated with.
     */

    public void setUserName(String userName) {
        this.userName = userName;
    }

    /**
     *

     * The name of the user the signing certificate is associated with.
     *

     *
     * @return The name of the user the signing certificate is associated with.
     */

    public String getUserName() {
        return this.userName;
    }

    /**
     *

     * The name of the user the signing certificate is associated with.
     *

     *
     * @param userName
     *        The name of the user the signing certificate is associated with.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public SigningCertificate withUserName(String userName) {
        setUserName(userName);
        return this;
    }

    /**
     *

     * The ID for the signing certificate.
     *

     *
     * @param certificateId
     *        The ID for the signing certificate.
     */

    public void setCertificateId(String certificateId) {
        this.certificateId = certificateId;
    }

    /**
     *

     * The ID for the signing certificate.
     *

     *
     * @return The ID for the signing certificate.
     */

    public String getCertificateId() {
        return this.certificateId;
    }

    /**
     *

     * The ID for the signing certificate.
     *

     *
     * @param certificateId
     *        The ID for the signing certificate.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public SigningCertificate withCertificateId(String certificateId) {
        setCertificateId(certificateId);
        return this;
    }

    /**
     *

     * The contents of the signing certificate.
     *

     *
     * @param certificateBody
     *        The contents of the signing certificate.
     */

    public void setCertificateBody(String certificateBody) {
        this.certificateBody = certificateBody;
    }

    /**
     *

     * The contents of the signing certificate.
     *

     *
     * @return The contents of the signing certificate.
     */

    public String getCertificateBody() {
        return this.certificateBody;
    }

    /**
     *

     * The contents of the signing certificate.
     *

     *
     * @param certificateBody
     *        The contents of the signing certificate.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public SigningCertificate withCertificateBody(String certificateBody) {
        setCertificateBody(certificateBody);
        return this;
    }

    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     *
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     * @see StatusType
     */

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     *
     * @return The status of the signing certificate. Active means
     *         the key is valid for API calls, while Inactive means
     *         it is not.
     * @see StatusType
     */

    public String getStatus() {
        return this.status;
    }

    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     *
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see StatusType
     */

    public SigningCertificate withStatus(String status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     *
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see StatusType
     */

    public void setStatus(StatusType status) {
        this.status = status.toString();
    }

    /**
     *

     * The status of the signing certificate. Active means the key
     * is valid for API calls, while Inactive means it is not.
     *

     *
     * @param status
     *        The status of the signing certificate. Active means
     *        the key is valid for API calls, while Inactive means
     *        it is not.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     * @see StatusType
     */

    public SigningCertificate withStatus(StatusType status) {
        setStatus(status);
        return this;
    }

    /**
     *

     * The date when the signing certificate was uploaded.
     *

     *
     * @param uploadDate
     *        The date when the signing certificate was uploaded.
     */

    public void setUploadDate(java.util.Date uploadDate) {
        this.uploadDate = uploadDate;
    }

    /**
     *

     * The date when the signing certificate was uploaded.
     *

     *
     * @return The date when the signing certificate was uploaded.
     */

    public java.util.Date getUploadDate() {
        return this.uploadDate;
    }

    /**
     *

     * The date when the signing certificate was uploaded.
     *

     *
     * @param uploadDate
     *        The date when the signing certificate was uploaded.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */

    public SigningCertificate withUploadDate(java.util.Date uploadDate) {
        setUploadDate(uploadDate);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getUserName() != null)
            sb.append("UserName: " + getUserName() + ",");
        if (getCertificateId() != null)
            sb.append("CertificateId: " + getCertificateId() + ",");
        if (getCertificateBody() != null)
            sb.append("CertificateBody: " + getCertificateBody() + ",");
        if (getStatus() != null)
            sb.append("Status: " + getStatus() + ",");
        if (getUploadDate() != null)
            sb.append("UploadDate: " + getUploadDate());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof SigningCertificate == false)
            return false;
        SigningCertificate other = (SigningCertificate) obj;
        if (other.getUserName() == null ^ this.getUserName() == null)
            return false;
        if (other.getUserName() != null
                && other.getUserName().equals(this.getUserName()) == false)
            return false;
        if (other.getCertificateId() == null ^ this.getCertificateId() == null)
            return false;
        if (other.getCertificateId() != null
                && other.getCertificateId().equals(this.getCertificateId()) == false)
            return false;
        if (other.getCertificateBody() == null
                ^ this.getCertificateBody() == null)
            return false;
        if (other.getCertificateBody() != null
                && other.getCertificateBody().equals(this.getCertificateBody()) == false)
            return false;
        if (other.getStatus() == null ^ this.getStatus() == null)
            return false;
        if (other.getStatus() != null
                && other.getStatus().equals(this.getStatus()) == false)
            return false;
        if (other.getUploadDate() == null ^ this.getUploadDate() == null)
            return false;
        if (other.getUploadDate() != null
                && other.getUploadDate().equals(this.getUploadDate()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getUserName() == null) ? 0 : getUserName().hashCode());
        hashCode = prime
                * hashCode
                + ((getCertificateId() == null) ? 0 : getCertificateId()
                        .hashCode());
        hashCode = prime
                * hashCode
                + ((getCertificateBody() == null) ? 0 : getCertificateBody()
                        .hashCode());
        hashCode = prime * hashCode
                + ((getStatus() == null) ? 0 : getStatus().hashCode());
        hashCode = prime * hashCode
                + ((getUploadDate() == null) ? 0 : getUploadDate().hashCode());
        return hashCode;
    }

    @Override
    public SigningCertificate clone() {
        try {
            return (SigningCertificate) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
'use strict';

/* @preserve
 *
 * StickyStack
 *
 * A vanilla javascript sticky-element stacker
 *
 * For licence details and usage see:
 * https://github.com/jrsouth/stickystack
 *
 */

(function () {
    "use strict";

    var StickyStack = {

        mobileBreak: 768,
        list: [],
        number: 0,
        stackTop: 0,
        pageBottom: null,

        init: function init() {

            StickyStack.stopObserving();

            // Clean up if init already run
            if (StickyStack.pageBottom) {
                StickyStack.pageBottom.parentNode.removeChild(StickyStack.pageBottom);
            }

            for (var i = 0; i < StickyStack.number; i++) {

                var placeholder = StickyStack.list[i].placeholder;
                var currElement = StickyStack.list[i].element;

                placeholder.parentNode.removeChild(placeholder);
                StickyStack.removeClass(currElement, 'stickystack-stuck');

                currElement.style.position = null;
                currElement.style.top = null;
                currElement.style.left = null;
                currElement.style.width = null;
                currElement.style.marginTop = null;
                currElement.style.marginBottom = null;
            }

            // Create element to push bottom of the page up

            //

            StickyStack.pageBottom = document.createElement('div');
            StickyStack.pageBottom.style.height = 0;
            StickyStack.pageBottom.style.width = "100%";
            StickyStack.addClass(StickyStack.pageBottom, "js-stickystack");

            document.body.appendChild(StickyStack.pageBottom);

            // Reset StickyStack.number
            StickyStack.number = 0;

            // Get elements with 'js-stickystack' class
            var elementList = document.getElementsByClassName('js-stickystack');

            // If on a small screen, strip out elements marked
            // to _not_ stick on mobile (js-stickystack-nomobile)
            // TODO: Dynamically load/assign mobile breakpoint
            if (window.innerWidth <= StickyStack.mobileBreak) {
                var newElementList = [];
                for (var _i = 0; _i < elementList.length; _i++) {
                    if (!StickyStack.hasClass(elementList[_i], 'js-stickystack-nomobile')) {
                        newElementList.push(elementList[_i]);
                    }
                }
                elementList = newElementList;
            }

            StickyStack.number = elementList.length;
            StickyStack.list = [];
            StickyStack.stackTop = 0;

            for (var _i2 = 0; _i2 < StickyStack.number; _i2++) {

                // Get element's computed style
                // Used both to set up the placeholder and to get needed list[] values
                var style = window.getComputedStyle(elementList[_i2]);

                // Create placeholder block element, replicating all
                // layout-affecting properties of the sticky element
                var placeholderElement = document.createElement('div');
                placeholderElement.style.width = style.getPropertyValue("width");
                placeholderElement.style.height = style.getPropertyValue("height");
                placeholderElement.style.top = style.getPropertyValue("top");
                placeholderElement.style.right = style.getPropertyValue("right");
                placeholderElement.style.bottom = style.getPropertyValue("bottom");
                placeholderElement.style.left = style.getPropertyValue("left");
                placeholderElement.style.margin = style.getPropertyValue("margin");
                placeholderElement.style.padding = style.getPropertyValue("padding");
                placeholderElement.style.border = style.getPropertyValue("border");
                placeholderElement.style.float = style.getPropertyValue("float");
                placeholderElement.style.clear = style.getPropertyValue("clear");
                placeholderElement.style.position = style.getPropertyValue("position");

                // Hide the placeholder until it's needed
                // And have it invisible even when it IS needed
                placeholderElement.style.display = 'none';
                placeholderElement.style.visibility = 'hidden';

                // Add it to the DOM, immediately before the sticky element
                elementList[_i2].parentNode.insertBefore(placeholderElement, elementList[_i2]);

                var coords = StickyStack.getCoords(elementList[_i2]);

                StickyStack.list.push({
                    element: elementList[_i2],
                    top: coords.top,
                    left: coords.left - parseFloat(style.getPropertyValue("margin-left")),
                    width: parseFloat(style.getPropertyValue("width")),
                    placeholder: placeholderElement,
                    semistuck: StickyStack.hasClass(elementList[_i2], 'js-stickystack-semi'),
                    zIndex: 100 - _i2
                });
            }

            // Sort the list top down
            StickyStack.list.sort(StickyStack.sortByTop);

            // Set the stack top to (the top of) the highest-placed element
            // with the js-stickystack-top class. Note that this element
            // does not have to be sticky itself (otherwise we could just use the
            // existing vertically-sorted list).
            //
            // This allows other sticky elements (admin toolbars etc.) to
            // peacefully co-exist with StickyStack.
            //
            // Defaults to 0 (the top of the viewport) if no elements are found.

            StickyStack.stackTop = 0;

            elementList = document.getElementsByClassName('js-stickystack-top');
            for (var _i3 = 0; _i3 < elementList.length; _i3++) {
                var top = StickyStack.getCoords(elementList[_i3]).top;
                if (_i3 == 0) {
                    StickyStack.stackTop = top;
                } else {
                    StickyStack.stackTop = Math.min(StickyStack.stackTop, top);
                }
            }

            // Fire the initial calculation
            StickyStack.update();
            StickyStack.startObserving();
        },

        update: function update() {

            var stack = [[StickyStack.stackTop, 0, document.body.offsetWidth]];
            var pageOffset = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;

            for (var i = 0; i < StickyStack.number; i++) {

                var curr = StickyStack.list[i];

                var currElement = curr.element;
                var currPlaceholder = curr.placeholder;
                var currLeft = curr.left;
                var currTop = curr.top - pageOffset;
                var currWidth = curr.width;

                var overlapData = StickyStack.getOverlap([currTop, currLeft, currWidth], stack);

                if (overlapData.overlap > 0) {

                    currPlaceholder.style.display = 'block';

                    StickyStack.addClass(currElement, 'stickystack-stuck');

                    var scrollback = 0;

                    // Semi-sticky handling

                    // Only bother if this element is "semistuck" and there are
                    // further elements in the list.
                    if (StickyStack.list[i].semistuck && i + 1 < StickyStack.number) {

                        var tempStack = [[overlapData.absolute + currElement.offsetHeight, currLeft, currWidth]];

                        // Check each following element for collision/overlap
                        for (var j = i + 1; j < StickyStack.number; j++) {

                            var testBlock = [StickyStack.list[j].top - pageOffset, StickyStack.list[j].left, StickyStack.list[j].width];
                            var overlapSemiData = StickyStack.getOverlap(testBlock, tempStack);

                            if (overlapSemiData.overlap > 0) {
                                scrollback = overlapSemiData.overlap;
                                break;
                            }
                        }
                    }

                    currElement.style.position = 'fixed';
                    currElement.style.top = overlapData.absolute - scrollback + 'px';
                    currElement.style.left = currLeft + 'px';
                    currElement.style.width = currWidth + 'px';
                    currElement.style.zIndex = curr.zIndex;
                    currElement.style.marginTop = 0;
                    currElement.style.marginBottom = 0;

                    stack.push([overlapData.absolute + currElement.offsetHeight - scrollback, currElement.offsetLeft, currElement.offsetWidth]);
                } else {

                    StickyStack.removeClass(currElement, 'stickystack-stuck');

                    currElement.style.position = null;
                    currElement.style.top = null;
                    currElement.style.left = null;
                    currElement.style.width = null;
                    currElement.style.zIndex = null;
                    currElement.style.marginTop = null;
                    currElement.style.marginBottom = null;

                    currPlaceholder.style.display = 'none';
                }
            }
        },

        startObserving: function startObserving() {

            // If there's no existing MutationObserver object, create one to
            // trigger a recalulation on changes in the sticky elements.
            // If there is one, stop it.
            if (!StickyStack.observer) {
                var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
                StickyStack.observer = new MutationObserver(StickyStack.init);
            } else {
                StickyStack.observer.disconnect();
            }

            // Since any change to the document might require a re-layout, observe EVERYTHING
            // TODO: Check performance penalty, if any.
            StickyStack.observer.observe(document.body, {
                attributes: true,
                characterData: true,
                subtree: true
            });
        },

        stopObserving: function stopObserving() {
            if (StickyStack.observer) {
                StickyStack.observer.disconnect();
            }
        },

        getOverlap: function getOverlap(block, stack) {
            var overlap = 0;
            var absolute = 0;
            for (var i = 0; i < stack.length; i++) {
                if (block[0] < stack[i][0] && block[1] + block[2] > stack[i][1] && stack[i][1] + stack[i][2] > block[1]) {
                    overlap = Math.max(overlap, stack[i][0] - block[0]);
                    absolute = Math.max(absolute, stack[i][0]);
                }
            }
            return { overlap: overlap, absolute: absolute };
        },

        sortByTop: function sortByTop(a, b) {
            return a.top - b.top;
        },

        getCoords: function getCoords(el) {
            // From http://stackoverflow.com/a/26230989

            var box = el.getBoundingClientRect();

            var body = document.body;
            var docEl = document.documentElement;

            var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
            var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

            var clientTop = docEl.clientTop || body.clientTop || 0;
            var clientLeft = docEl.clientLeft || body.clientLeft || 0;

            var top = box.top + scrollTop - clientTop;
            var left = box.left + scrollLeft - clientLeft;

            return { top: Math.round(top), left: Math.round(left) };
        },

        // Helper-functions pilfered wholesale from
        // http://jaketrent.com/post/addremove-classes-raw-javascript/

        hasClass: function hasClass(el, className) {
            if (el.classList) {
                return el.classList.contains(className);
            } else {
                return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
            }
        },

        addClass: function addClass(el, className) {
            if (el.classList) {
                el.classList.add(className);
            } else if (!StickyStack.hasClass(el, className)) {
                el.className += " " + className;
            }
        },

        removeClass: function removeClass(el, className) {
            if (el.classList) {
                el.classList.remove(className);
            } else if (StickyStack.hasClass(el, className)) {
                var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
                el.className = el.className.replace(reg, ' ');
            }
        }

    };

    // Set up listeners to fire on load
    window.addEventListener('DOMContentLoaded', StickyStack.init);
    window.addEventListener('load', StickyStack.init);
    window.addEventListener('resize', StickyStack.init);

    // Set up listeners to fire on scroll
    window.addEventListener('scroll', StickyStack.update);
    window.addEventListener('touchmove', StickyStack.update);

    // Add a hacky empty function to cause iOS to update the scroll offset value while scrolling
    // Still doesn't update during momentum scrolling
    // From https://remysharp.com/2012/05/24/issues-with-position-fixed-scrolling-on-ios/
    // TODO: Check if needed now that touchmove event has update() attached
    window.ontouchstart = function () {};

    // Trigger delayed extra recalculations, in case elements change
    // size as a result of the first init() call.
    window.addEventListener('DOMContentLoaded', function () {
        setTimeout(function () {
            StickyStack.update();
        }, 500);
    });
    window.addEventListener('load', function () {
        setTimeout(function () {
            StickyStack.update();
        }, 500);
    });
})();


text:
package com.eden.orchid.api.theme;

import com.caseyjbrooks.clog.Clog;
import com.eden.common.json.JSONElement;
import com.eden.common.util.EdenUtils;
import com.eden.orchid.Orchid;
import com.eden.orchid.api.OrchidContext;
import com.eden.orchid.api.converters.BooleanConverter;
import com.eden.orchid.api.events.On;
import com.eden.orchid.api.events.OrchidEventListener;
import com.eden.orchid.api.options.annotations.Description;
import com.eden.orchid.api.theme.assets.AssetManager;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import org.json.JSONObject;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

/**
 * @since v1.0.0
 * @orchidApi services
 */
@Description(value = "How Orchid manages your site's themes.", name = "Themes")
public final class ThemeServiceImpl implements ThemeService, OrchidEventListener {

    private final BooleanConverter booleanConverter;

    private OrchidContext context;
    private final AssetManager assetManager;

    private ThemeHolder<Theme> themes;
    private ThemeHolder<AdminTheme> adminThemes;

    private final String defaultTheme;
    private final String defaultAdminTheme;

    private Provider<Set<Theme>> themesProvider;
    private Provider<Set<AdminTheme>> adminThemesProvider;

    @Inject
    public ThemeServiceImpl(
            BooleanConverter booleanConverter,
            AssetManager assetManager,
            Provider<Set<Theme>> themesProvider,
            @Named("theme") String defaultTheme,
            Provider<Set<AdminTheme>> adminThemesProvider,
            @Named("adminTheme") String defaultAdminTheme) {
        this.booleanConverter = booleanConverter;
        this.assetManager = assetManager;
        this.defaultTheme = defaultTheme;
        this.themesProvider = themesProvider;

        this.defaultAdminTheme = defaultAdminTheme;
        this.adminThemesProvider = adminThemesProvider;
    }

    @Override
    public void initialize(OrchidContext context) {
        this.context = context;

        Theme emptyTheme = new Theme(context, "Default", 1) { };
        AdminTheme emptyAdminTheme = new AdminTheme(context, "Default", 1) { };

        themes = new ThemeHolder<>(booleanConverter, context, defaultTheme, "theme", themesProvider.get(), emptyTheme);
        adminThemes = new ThemeHolder<>(booleanConverter, context, defaultAdminTheme, "adminTheme", adminThemesProvider.get(), emptyAdminTheme);
    }

    @Override
    public void onStart() {
        themes.pushTheme(themes.getDefaultTheme());
        adminThemes.pushTheme(adminThemes.getDefaultTheme());
    }

    @Override
    public AssetManager getAssetManager() {
        return assetManager;
    }

// Interface Implementation
//----------------------------------------------------------------------------------------------------------------------

    @Override public Theme getTheme()                                      { return themes.getTheme(); }
    @Override public Theme getDefaultTheme()                               { return themes.getDefaultTheme(); }
    @Override public Theme findTheme(String theme)                         { return themes.findTheme(theme); }
    @Override public void  pushTheme(Theme theme)                          { themes.pushTheme(theme); }
    @Override public void  pushTheme(Theme theme, Map<String, Object> themeOptions) { themes.pushTheme(theme, themeOptions); }
    @Override public void  popTheme()                                      { themes.popTheme(); }
    @Override public void  clearThemes()                                   { themes.clearThemes(); }
    @Override public Theme doWithTheme(Object theme, Runnable cb)          { return themes.doWithTheme(theme, cb); }

    @Override public AdminTheme getAdminTheme()                                           { return adminThemes.getTheme(); }
    @Override public AdminTheme getDefaultAdminTheme()                                    { return adminThemes.getDefaultTheme(); }
    @Override public AdminTheme findAdminTheme(String theme)                              { return adminThemes.findTheme(theme); }
    @Override public void       pushAdminTheme(AdminTheme theme)                          { adminThemes.pushTheme(theme); }
    @Override public void       pushAdminTheme(AdminTheme theme, Map<String, Object> themeOptions) { adminThemes.pushTheme(theme, themeOptions); }
    @Override public void       popAdminTheme()                                           { adminThemes.popTheme(); }
    @Override public void       clearAdminThemes()                                        { adminThemes.clearThemes(); }

// Delegate interface calls to inner class
//----------------------------------------------------------------------------------------------------------------------

    private static class ThemeHolder<T extends AbstractTheme> {

        private final BooleanConverter booleanConverter;
        private OrchidContext context;

        private String defaultThemeKey;
        private String defaultOptionsKey;
        private T defaultTheme;
        private Stack<T> themeStack;
        private Set<T> availableThemes;

        ThemeHolder(BooleanConverter booleanConverter, OrchidContext context, String defaultTheme, String defaultOptionsKey, Set<T> availableThemes, T emptyTheme) {
            this.booleanConverter = booleanConverter;
            this.context = context;
            this.defaultThemeKey = defaultTheme;
            this.defaultOptionsKey = defaultOptionsKey;
            this.availableThemes = availableThemes;
            this.defaultTheme = findTheme(this.defaultThemeKey);
            this.themeStack = new Stack<>();
            if(this.defaultTheme == null) {
                this.defaultTheme = emptyTheme;
            }
        }

        T getTheme() {
            return (themeStack.size() > 0) ? themeStack.peek() : defaultTheme;
        }

        T getDefaultTheme() {
            return defaultTheme;
        }

        T findTheme(String themeKey) {
            if(availableThemes.size() > 0) {
                T foundTheme = availableThemes
                        .stream()
                        .sorted()
                        .filter(theme -> theme.getKey().equals(themeKey))
                        .findFirst()
                        .orElse(null);

                if (foundTheme != null) {
                    return (T) context.getInjector().getInstance(foundTheme.getClass());
                }
                else {
                    Clog.e("Could not find theme [{}-{}]", defaultOptionsKey, themeKey);
                    return null;
                }
            }
            else {
                return null;
            }
        }

        void pushTheme(T theme) {
            boolean isolated = false;
            Map<String, Object> actualThemeOptions = new HashMap<>();

            JSONElement defaultThemeOptions = context.query(defaultOptionsKey);
            JSONElement themeOptions = context.query(theme.getKey());

            if(EdenUtils.elementIsObject(themeOptions)) {
                JSONObject themeOptionsObject = (JSONObject) themeOptions.getElement();
                if(themeOptionsObject.has("isolate") && booleanConverter.convert(boolean.class, themeOptionsObject.get("isolate")).second) {
                    isolated = true;
                }
            }

            if(EdenUtils.elementIsObject(defaultThemeOptions) && !isolated) {
                actualThemeOptions = EdenUtils.merge(actualThemeOptions, ((JSONObject) defaultThemeOptions.getElement()).toMap());
            }
            if(EdenUtils.elementIsObject(themeOptions)) {
                actualThemeOptions = EdenUtils.merge(actualThemeOptions, ((JSONObject) themeOptions.getElement()).toMap());
            }

            pushTheme(theme, actualThemeOptions);
        }

        void pushTheme(T theme, Map<String, Object> themeOptions) {
            theme.clearCache();
            theme.initialize();

            theme.extractOptions(context, themeOptions);

            themeStack.push(theme);
        }

        void popTheme() {
            themeStack.pop();
        }

        void clearThemes() {
            themeStack.clear();
            pushTheme(this.defaultTheme);
        }

        T doWithTheme(Object themeObject, Runnable cb) {
            T theme = null;
            Object themeKey = null;
            Map<String, Object> themeOptions = null;

            if(themeObject != null) {
                if(themeObject instanceof String) {
                    themeOptions = null;
                    themeKey = themeObject;
                    theme = findTheme((String) themeKey);
                }
                else if(themeObject instanceof JSONObject) {
                    themeOptions = ((JSONObject) themeObject).toMap();
                    themeKey = themeOptions.get("key");
                    if(themeKey != null) {
                        themeKey = themeKey.toString();
                    }
                    theme = findTheme((String) themeKey);
                }
                else if(themeObject instanceof Map) {
                    themeOptions = (Map<String, Object>) themeObject;
                    themeKey = themeOptions.get("key");
                    if(themeKey != null) {
                        themeKey = themeKey.toString();
                    }
                    theme = findTheme((String) themeKey);
                }
            }

            if (theme != null) {
                if(themeOptions != null) {
                    pushTheme(theme, themeOptions);
                }
                else {
                    pushTheme(theme);
                }
                cb.run();
                theme.renderAssets();
                popTheme();
                return theme;
            }
            else {
                cb.run();
                return null;
            }
        }
    }

    @On(Orchid.Lifecycle.ClearCache.class)
    public void onClearCache(Orchid.Lifecycle.ClearCache event) {
        assetManager.clearAssets();
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.hobsoft.hamcrest.compose;

import java.util.function.Function;

import org.hamcrest.Matcher;

import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;

import static org.hamcrest.CoreMatchers.equalTo;

/**
 * Factory for Hamcrest Compose matchers.
 */
public final class ComposeMatchers
{
	// ----------------------------------------------------------------------------------------------------------------
	// constructors
	// ----------------------------------------------------------------------------------------------------------------

	private ComposeMatchers()
	{
		throw new AssertionError();
	}

	// ----------------------------------------------------------------------------------------------------------------
	// public methods
	// ----------------------------------------------------------------------------------------------------------------

	/**
	 * Returns a matcher that logically ANDs the specified matcher with any number of further matchers.
	 *

	 * For example:
	 *

	 * assertThat("ham", compose(startsWith("h")).and(containsString("a")).and(endsWith("m")));
	 *

	 * See {@code ConjunctionMatcher} as to how this matcher differs from {@code allOf} and {@code both}.
	 *
	 * @param matcher
	 *            the first matcher to compose
	 * @param <T>
	 *            the type of the object to be matched
	 * @return a matcher that can compose itself with further matchers
	 * @see ConjunctionMatcher
	 */
	public static <T> ConjunctionMatcher<T> compose(Matcher<T> matcher)
	{
		return compose(null, matcher);
	}

	/**
	 * Returns a matcher that logically ANDs the specified matcher with any number of further matchers.
	 *

	 * For example:
	 *

	 * assertThat("ham", compose("a word with", startsWith("h")).and(containsString("a")).and(endsWith("m")));
	 *

	 * See {@code ConjunctionMatcher} as to how this matcher differs from {@code allOf} and {@code both}.
	 *
	 * @param compositeDescription
	 *            a description of this composite used by {@code describeTo}
	 * @param matcher
	 *            the first matcher to compose
	 * @param <T>
	 *            the type of the object to be matched
	 * @return a matcher that can compose itself with further matchers
	 * @see ConjunctionMatcher
	 */
	public static <T> ConjunctionMatcher<T> compose(String compositeDescription, Matcher<T> matcher)
	{
		requireNonNull(matcher, "matcher");

		return compose(compositeDescription, singletonList(matcher));
	}

	/**
	 * Returns a matcher that logically ANDs the specified matchers with any number of further matchers.
	 *

	 * For example:
	 *

	 * assertThat("ham", compose(asList(startsWith("h"), containsString("a"))).and(endsWith("m")));
	 *

	 * See {@code ConjunctionMatcher} as to how this matcher differs from {@code allOf} and {@code both}.
	 *
	 * @param matchers
	 *            the initial matchers to compose
	 * @param <T>
	 *            the type of the object to be matched
	 * @return a matcher that can compose itself with further matchers
	 * @see ConjunctionMatcher
	 */
	public static <T> ConjunctionMatcher<T> compose(Iterable<Matcher<T>> matchers)
	{
		return compose(null, matchers);
	}

	/**
	 * Returns a matcher that logically ANDs the specified matchers with any number of further matchers.
	 *

	 * For example:
	 *

	 * assertThat("ham", compose("a word with", asList(startsWith("h"), containsString("a"))).and(endsWith("m")));
	 *

	 * See {@code ConjunctionMatcher} as to how this matcher differs from {@code allOf} and {@code both}.
	 *
	 * @param compositeDescription
	 *            a description of this composite used by {@code describeTo}
	 * @param matchers
	 *            the initial matchers to compose
	 * @param <T>
	 *            the type of the object to be matched
	 * @return a matcher that can compose itself with further matchers
	 * @see ConjunctionMatcher
	 */
	public static <T> ConjunctionMatcher<T> compose(String compositeDescription, Iterable<Matcher<T>> matchers)
	{
		requireNonNull(matchers, "matchers");

		return new ConjunctionMatcher<>(compositeDescription, matchers);
	}

	/**
	 * Returns a matcher that matches the specified feature of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeature(String::length, equalTo(3)));
	 *

	 *
	 * @param featureFunction
	 *            a function to extract the feature from the object. The string representation of this function is used
	 *            as the feature name for {@code describeTo} and {@code describeMismatch}.
	 * @param featureMatcher
	 *            the matcher to apply to the specified feature
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeature(Function<T, U> featureFunction, Matcher<? super U> featureMatcher)
	{
		return hasFeature(featureFunction.toString(), featureFunction, featureMatcher);
	}

	/**
	 * Returns a matcher that matches the specified feature of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeature("string length", String::length, equalTo(3)));
	 *

	 *
	 * @param featureName
	 *            the name of this feature used by {@code describeTo} and {@code describeMismatch}
	 * @param featureFunction
	 *            a function to extract the feature from the object
	 * @param featureMatcher
	 *            the matcher to apply to the specified feature
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeature(String featureName, Function<T, U> featureFunction,
		Matcher<? super U> featureMatcher)
	{
		return hasFeature(featureName, featureName, featureFunction, featureMatcher);
	}

	/**
	 * Returns a matcher that matches the specified feature of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeature("a string with length", "string length", String::length, equalTo(3)));
	 *

	 *
	 * @param featureDescription
	 *            a description of this feature used by {@code describeTo}
	 * @param featureName
	 *            the name of this feature used by {@code describeMismatch}
	 * @param featureFunction
	 *            a function to extract the feature from the object
	 * @param featureMatcher
	 *            the matcher to apply to the specified feature
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeature(String featureDescription, String featureName,
		Function<T, U> featureFunction, Matcher<? super U> featureMatcher)
	{
		return new HasFeatureMatcher<>(featureDescription, featureName, featureFunction, featureMatcher);
	}

	/**
	 * Returns a matcher that matches the specified feature value of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeatureValue(String::length, 3));
	 *

	 *

	 * This is equivalent to {@code hasFeature(featureFunction, equalTo(featureValue))}.
	 *
	 * @param featureFunction
	 *            a function to extract the feature from the object. The string representation of this function is used
	 *            as the feature name for {@code describeTo} and {@code describeMismatch}.
	 * @param featureValue
	 *            the feature value to match
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeatureValue(Function<T, U> featureFunction, U featureValue)
	{
		return hasFeature(featureFunction, equalTo(featureValue));
	}

	/**
	 * Returns a matcher that matches the specified feature value of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeatureValue("string length", String::length, 3));
	 *

	 *

	 * This is equivalent to {@code hasFeature(featureName, featureFunction, equalTo(featureValue))}.
	 *
	 * @param featureName
	 *            the name of this feature used by {@code describeTo} and {@code describeMismatch}
	 * @param featureFunction
	 *            a function to extract the feature from the object
	 * @param featureValue
	 *            the feature value to match
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeatureValue(String featureName, Function<T, U> featureFunction, U featureValue)
	{
		return hasFeature(featureName, featureFunction, equalTo(featureValue));
	}

	/**
	 * Returns a matcher that matches the specified feature value of an object.
	 *

	 * For example:
	 *

	 * assertThat("ham", hasFeatureValue("a string with length", "string length", String::length, 3));
	 *

	 *

	 * This is equivalent to {@code hasFeature(featureDescription, featureName, featureFunction,
	 * equalTo(featureValue))}.
	 *
	 * @param featureDescription
	 *            a description of this feature used by {@code describeTo}
	 * @param featureName
	 *            the name of this feature used by {@code describeMismatch}
	 * @param featureFunction
	 *            a function to extract the feature from the object
	 * @param featureValue
	 *            the feature value to match
	 * @param <T>
	 *            the type of the object to be matched
	 * @param
	 *            the type of the feature to be matched
	 * @return the feature matcher
	 */
	public static <T, U> Matcher<T> hasFeatureValue(String featureDescription, String featureName,
		Function<T, U> featureFunction, U featureValue)
	{
		return hasFeature(featureDescription, featureName, featureFunction, equalTo(featureValue));
	}
}


text:
This page has moved to:

- [JLBP-7 Make breaking transitions easy](https://googlecloudplatform.github.io/cloud-opensource-java/JLBP-7.html)