text:
package org.wso2.carbon.streaming.integrator.core.ha;

import io.siddhi.core.SiddhiAppRuntime;
import io.siddhi.core.SiddhiManager;
import io.siddhi.core.exception.CannotRestoreSiddhiAppStateException;
import io.siddhi.core.stream.input.InputHandler;
import io.siddhi.core.stream.input.source.SourceHandler;
import io.siddhi.core.stream.input.source.SourceHandlerManager;
import io.siddhi.core.stream.output.sink.SinkHandler;
import io.siddhi.core.stream.output.sink.SinkHandlerManager;
import io.siddhi.core.table.record.RecordTableHandler;
import io.siddhi.core.table.record.RecordTableHandlerManager;
import io.siddhi.core.util.transport.BackoffRetryCounter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.cluster.coordinator.commons.node.NodeDetail;
import org.wso2.carbon.cluster.coordinator.service.ClusterCoordinator;
import org.wso2.carbon.databridge.commons.ServerEventListener;
import org.wso2.carbon.streaming.integrator.common.HAStateChangeListener;
import org.wso2.carbon.streaming.integrator.core.DeploymentMode;
import org.wso2.carbon.streaming.integrator.core.NodeInfo;
import org.wso2.carbon.streaming.integrator.core.event.queue.EventListMapManager;
import org.wso2.carbon.streaming.integrator.core.ha.tcp.TCPServer;
import org.wso2.carbon.streaming.integrator.core.ha.transport.EventSyncConnectionPoolManager;
import org.wso2.carbon.streaming.integrator.core.ha.util.HAConstants;
import org.wso2.carbon.streaming.integrator.core.internal.SiddhiAppData;
import org.wso2.carbon.streaming.integrator.core.internal.StreamProcessorDataHolder;
import org.wso2.carbon.streaming.integrator.core.internal.beans.DeploymentConfig;
import org.wso2.carbon.streaming.integrator.core.internal.beans.EventSyncClientPoolConfig;
import org.wso2.carbon.streaming.integrator.core.persistence.PersistenceManager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Class that manages Active and Passive nodes in a 2 node minimum HA configuration
 */
public class HAManager {

    private ClusterCoordinator clusterCoordinator;
    private boolean isActiveNode;
    private String nodeId;
    private String clusterId;
    private HACoordinationSourceHandlerManager sourceHandlerManager;
    private HACoordinationSinkHandlerManager sinkHandlerManager;
    private HACoordinationRecordTableHandlerManager recordTableHandlerManager;
    private TCPServer tcpServerInstance = TCPServer.getInstance();
    private EventListMapManager eventListMapManager;
    private DeploymentConfig deploymentConfig;
    private EventSyncClientPoolConfig eventSyncClientPoolConfig;
    private BackoffRetryCounter backoffRetryCounter = new BackoffRetryCounter();
    private boolean passiveNodeAdded;
    private String host;
    private int port;

    private final static Map<String, Object> passiveNodeDetailsPropertiesMap = new HashMap<>();
    private static final Logger log = LoggerFactory.getLogger(HAManager.class);

    public HAManager(ClusterCoordinator clusterCoordinator, String nodeId, String clusterId,
                     DeploymentConfig deploymentConfig) {
        this.clusterCoordinator = clusterCoordinator;
        this.nodeId = nodeId;
        this.clusterId = clusterId;
        this.eventListMapManager = new EventListMapManager();
        this.deploymentConfig = deploymentConfig;
        this.eventSyncClientPoolConfig = deploymentConfig.getTcpClientPoolConfig();
    }

    public void start() {
        sourceHandlerManager = new HACoordinationSourceHandlerManager();
        sinkHandlerManager = new HACoordinationSinkHandlerManager();
        recordTableHandlerManager = new HACoordinationRecordTableHandlerManager();

        StreamProcessorDataHolder.setSinkHandlerManager(sinkHandlerManager);
        StreamProcessorDataHolder.setSourceHandlerManager(sourceHandlerManager);
        StreamProcessorDataHolder.setRecordTableHandlerManager(recordTableHandlerManager);
        SiddhiManager siddhiManager = StreamProcessorDataHolder.getSiddhiManager();
        siddhiManager.setSourceHandlerManager(StreamProcessorDataHolder.getSourceHandlerManager());
        siddhiManager.setSinkHandlerManager(StreamProcessorDataHolder.getSinkHandlerManager());
        siddhiManager.setRecordTableHandlerManager(StreamProcessorDataHolder.getRecordTableHandlerManager());

        clusterCoordinator.registerEventListener(new HAEventListener());

        //Give time for the cluster to normalize
        while (clusterCoordinator.getLeaderNode() == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                log.warn("Error in waiting for leader node");
            }
        }

        isActiveNode = clusterCoordinator.isLeaderNode();

        if (isActiveNode) {
            log.info("HA Deployment: Starting up as Active Node");
            //notify the HAStateChangeListener as becameActive
            List<HAStateChangeListener> haStateChangeListeners = StreamProcessorDataHolder.
                    getHaStateChangeListenerList();
            for (HAStateChangeListener listener : haStateChangeListeners) {
                listener.becameActive();
            }
            //if active node restarted before the heart beat become old then node will be still active and then,
            // we need to initialize connections to passive node because we are not getting a passive member added
            // event. This will happen if and only if passive node already exist
            Map passiveNodePropertyMap = null;
            for (NodeDetail node : clusterCoordinator.getAllNodeDetails()) {
                if (!node.getNodeId().equals(nodeId)) {
                    passiveNodePropertyMap = node.getPropertiesMap();
                }
            }

            if (null != passiveNodePropertyMap) {
                setPassiveNodeAdded(true);
                setPassiveNodeHostPort(getHost(passiveNodePropertyMap),
                        getPort(passiveNodePropertyMap));
                initializeEventSyncConnectionPool();
                for (SourceHandler sourceHandler : sourceHandlerManager.getRegsiteredSourceHandlers().values()) {
                    ((HACoordinationSourceHandler) sourceHandler).setPassiveNodeAdded(true);
                }
                new PersistenceManager().run();
            }
        } else {
            log.info("HA Deployment: Starting up as Passive Node");
            //initialize passive queue
            passiveNodeDetailsPropertiesMap.put(HAConstants.HOST, deploymentConfig.eventSyncServerConfigs().getHost());
            passiveNodeDetailsPropertiesMap.put(HAConstants.PORT, deploymentConfig.eventSyncServerConfigs().getPort());
            passiveNodeDetailsPropertiesMap.put(HAConstants.ADVERTISED_HOST, deploymentConfig.eventSyncServerConfigs()
                    .getAdvertisedHost());
            passiveNodeDetailsPropertiesMap.put(HAConstants.ADVERTISED_PORT, deploymentConfig.eventSyncServerConfigs()
                    .getAdvertisedPort());
            clusterCoordinator.setPropertiesMap(passiveNodeDetailsPropertiesMap);
            EventListMapManager.initializeEventListMap();

            //notify the HAStateChangeListener as becamePassive
            List<HAStateChangeListener> listeners = StreamProcessorDataHolder.getHaStateChangeListenerList();
            for (HAStateChangeListener listener : listeners) {
                listener.becamePassive();
            }
        }

        //start tcp server
        tcpServerInstance.start(deploymentConfig);

        NodeInfo nodeInfo = StreamProcessorDataHolder.getNodeInfo();
        nodeInfo.setMode(DeploymentMode.MINIMUM_HA);
        nodeInfo.setNodeId(nodeId);
        nodeInfo.setGroupId(clusterId);
        nodeInfo.setActiveNode(isActiveNode);
        if (StreamProcessorDataHolder.isStatisticsEnabled()) {
            StreamProcessorDataHolder.getStatisticsManager().startReporting();
        }
    }

    /**
     * Sync state from persisted information
     * Playback events
     * Start siddhi app runtimes
     * Start databridge servers
     */
    void changeToActive() {
        if (!isActiveNode) {
            log.info("HA Deployment: This Node is now becoming the Active Node");
            isActiveNode = true;
            createSiddhiAppRuntimes();
            for (SourceHandler sourceHandler : sourceHandlerManager.getRegsiteredSourceHandlers().values()) {
                try {
                    ((HACoordinationSourceHandler) sourceHandler).setPlayBack(true);
                    ((HACoordinationSourceHandler) sourceHandler).setAsActive();
                } catch (Throwable t) {
                    log.error("HA Deployment: Error when connecting to source " + sourceHandler.getId() +
                            " while changing from passive state to active, skipping the source. ", t);
                    continue;
                }
            }
            log.info("Registered source handlers set to active");
            changeSiddhiAppState(true);
            NodeInfo nodeInfo = StreamProcessorDataHolder.getNodeInfo();
            nodeInfo.setActiveNode(isActiveNode);
            syncState();

            //Give time for byte buffer queue to be empty
            if (null != tcpServerInstance.getEventSyncServer().getEventByteBufferQueue()) {
                while (tcpServerInstance.getEventSyncServer().getEventByteBufferQueue().peek() != null) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        log.warn("Error in checking byte buffer queue empty");
                    }
                }
            }
            log.info("Successfully retrieved all the events from event sync server");

            //change the system clock to work with event time
            enableEventTimeClock(true);
            startSiddhiAppRuntimeWithoutSources();
            try {
                eventListMapManager.trimAndSendToInputHandler();
            } catch (InterruptedException e) {
                log.warn("Error in sending events to input handler." + e.getMessage());
            }
            log.info("Successfully playback all the events");
            for (SourceHandler sourceHandler : sourceHandlerManager.getRegsiteredSourceHandlers().values()) {
                try {
                    ((HACoordinationSourceHandler) sourceHandler).setPlayBack(false);
                } catch (Throwable t) {
                    log.error("HA Deployment: Error when connecting to source " + sourceHandler.getId() +
                            " while changing from passive state to active, skipping the source. ", t);
                    continue;
                }
            }
            //change the system clock to work with current time
            enableEventTimeClock(false);

            //here before starting the sources need to enable sinks and record table handlers
            // so that new events will process accordingly
            for (SinkHandler sinkHandler : sinkHandlerManager.getRegisteredSinkHandlers().values()) {
                try {
                    HACoordinationSinkHandler handler = (HACoordinationSinkHandler) sinkHandler;
                    if (handler != null) {
                        handler.setAsActive();
                    }
                } catch (Throwable t) {
                    log.error("HA Deployment: Error when connecting to sink " + sinkHandler.getId() +
                            " while changing from passive state to active, skipping the sink. ", t);
                    continue;
                }
            }
            log.info("Registered sink handlers set to active");

            for (RecordTableHandler recordTableHandler : recordTableHandlerManager.getRegisteredRecordTableHandlers().
                    values()) {
                try {
                    ((HACoordinationRecordTableHandler) recordTableHandler).setAsActive();
                } catch (Throwable e) {
                    backoffRetryCounter.reset();
                    log.error("HA Deployment: Error in connecting to table " + ((HACoordinationRecordTableHandler)
                            recordTableHandler).getTableId() + " while changing from passive" +
                            " state to active, will retry in " + backoffRetryCounter.getTimeInterval(), e);
                    ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
                    backoffRetryCounter.increment();
                    scheduledExecutorService.schedule(new RetryRecordTableConnection(backoffRetryCounter,
                                    recordTableHandler, scheduledExecutorService),
                            backoffRetryCounter.getTimeIntervalMillis(), TimeUnit.MILLISECONDS);
                }
            }
            log.info("Registered record table handlers set to active ");

            startSiddhiAppRuntimeSources();

            //start the databridge servers
            List<ServerEventListener> listeners = StreamProcessorDataHolder.getServerListeners();
            for (ServerEventListener listener : listeners) {
                listener.start();
            }

            //notify the HAStateChangeListener as becameActive
            List<HAStateChangeListener> haStateChangeListeners = StreamProcessorDataHolder.
                    getHaStateChangeListenerList();
            for (HAStateChangeListener listener : haStateChangeListeners) {
                listener.becameActive();
            }
            log.info("HAStateChangeListener notified as active ");
            log.info("Successfully Changed to Active Mode ");
        }
    }

    /**
     * Stop thrift/binary servers
     * Stop siddhi app runtimes
     * Initialize eventEventListMap
     */
    void changeToPassive() {
        log.info("HA Deployment: This Node is now becoming the Passive Node");
        SinkHandlerManager sinkHandlerManager = StreamProcessorDataHolder.getSinkHandlerManager();
        Map<String, SinkHandler> registeredSinkHandlers = sinkHandlerManager.getRegisteredSinkHandlers();
        SourceHandlerManager sourceHandlerManager = StreamProcessorDataHolder.getSourceHandlerManager();
        Map<String, SourceHandler> registeredSourceHandlers = sourceHandlerManager.
                getRegsiteredSourceHandlers();
        RecordTableHandlerManager recordTableHandlerManager = StreamProcessorDataHolder.
                getRecordTableHandlerManager();
        Map<String, RecordTableHandler> registeredRecordTableHandlers = recordTableHandlerManager.
                getRegisteredRecordTableHandlers();
        for (Map.Entry<String, SinkHandler> entry : registeredSinkHandlers.entrySet()) {
            HACoordinationSinkHandler handler = (HACoordinationSinkHandler) entry.getValue();
            if (handler != null) {
                handler.setAsPassive();
            }
        }
        log.info("Registered sink handlers set to passive");
        for (SourceHandler sourceHandler : registeredSourceHandlers.values()) {
            ((HACoordinationSourceHandler) sourceHandler).setAsPassive();
        }
        log.info("Registered source handlers set to passive");
        for (RecordTableHandler recordTableHandler : registeredRecordTableHandlers.values()) {
            ((HACoordinationRecordTableHandler) recordTableHandler).setAsPassive();
        }
        log.info("Registered record table handlers set to passive");
        //stop the databridge servers
        List<ServerEventListener> listeners = StreamProcessorDataHolder.getServerListeners();
        for (ServerEventListener listener : listeners) {
            listener.stop();
        }
        sourceHandlerManager.getRegsiteredSourceHandlers().clear();
        log.info("Starting to stop siddhi app runtimes");
        stopSiddhiAppRuntimes();
        log.info("Successfully stopped siddhi app runtimes");
        isActiveNode = false;
        changeSiddhiAppState(false);
        setPassiveNodeAdded(false);

        //initialize event list map
        EventListMapManager.initializeEventListMap();

        NodeInfo nodeInfo = StreamProcessorDataHolder.getNodeInfo();
        nodeInfo.setActiveNode(isActiveNode);

        //notify the HAStateChangeListener as becamePassive
        List<HAStateChangeListener> haStateChangeListeners = StreamProcessorDataHolder.
                getHaStateChangeListenerList();
        for (HAStateChangeListener listener : haStateChangeListeners) {
            listener.becamePassive();
        }
        log.info("HAStateChangeListener notified as passive");

        try {
            if (EventSyncConnectionPoolManager.getConnectionPool() != null) {
                EventSyncConnectionPoolManager.getConnectionPool().close();
            }
        } catch (Exception e) {
            log.error("Error closing tcp client connection pool. " + e.getMessage(), e);
        } finally {
            EventSyncConnectionPoolManager.uninitializeConnectionPool();
        }
        log.info("Event sync client connection pool is closed");
        registeredSinkHandlers.clear();
        registeredRecordTableHandlers.clear();
        registeredSourceHandlers.clear();
        log.info("Successfully Changed to Passive Mode ");
    }

    public void createSiddhiAppRuntimes() {
        Map<String, SiddhiAppData> siddhiAppDataMap
                = StreamProcessorDataHolder.getStreamProcessorService().getSiddhiAppMap();
        SiddhiManager siddhiManager = StreamProcessorDataHolder.getSiddhiManager();

        siddhiAppDataMap.forEach((siddhiAppName, siddhiAppData) -> {

            SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiAppData.getSiddhiApp());
            Set<String> streamNames = siddhiAppRuntime.getStreamDefinitionMap().keySet();
            Map<String, InputHandler> inputHandlerMap =
                    new ConcurrentHashMap<String, InputHandler>(streamNames.size());
            for (String streamName : streamNames) {
                inputHandlerMap.put(streamName, siddhiAppRuntime.getInputHandler(streamName));
            }
            siddhiAppData.setInputHandlerMap(inputHandlerMap);
            siddhiAppData.setActive(true);
            siddhiAppData.setSiddhiAppRuntime(siddhiAppRuntime);
        });
    }

    private void syncState() {
        ConcurrentMap<String, SiddhiAppRuntime> siddhiAppRuntimeMap
                = StreamProcessorDataHolder.getSiddhiManager().getSiddhiAppRuntimeMap();

        siddhiAppRuntimeMap.forEach((siddhiAppName, siddhiAppRuntime) -> {
            if (log.isDebugEnabled()) {
                log.debug("Restoring state of Siddhi Application " +
                        siddhiAppRuntime.getName());
            }
            try {
                siddhiAppRuntime.restoreLastRevision();
                StreamProcessorDataHolder.getNodeInfo().setLastSyncedTimestamp(System.currentTimeMillis());
                StreamProcessorDataHolder.getNodeInfo().setInSync(true);
            } catch (CannotRestoreSiddhiAppStateException e) {
                log.error("Error in restoring Siddhi Application: " + siddhiAppRuntime.getName(), e);
            }
        });
        log.info("Successfully Synced the state");
    }

    private void enableEventTimeClock(boolean enablePlayBack) {
        ConcurrentMap<String, SiddhiAppRuntime> siddhiAppRuntimeMap
                = StreamProcessorDataHolder.getSiddhiManager().getSiddhiAppRuntimeMap();

        siddhiAppRuntimeMap.forEach((siddhiAppName, siddhiAppRuntime) -> {
            if (log.isDebugEnabled()) {
                log.debug("Changed Event Play back mode '" + enablePlayBack + "' for Siddhi Application " +
                        siddhiAppRuntime.getName());
            }
            siddhiAppRuntime.enablePlayBack(enablePlayBack, null, null);
        });
    }

    private void startSiddhiAppRuntimeWithoutSources() {
        ConcurrentMap<String, SiddhiAppRuntime> siddhiAppRuntimeMap
                = StreamProcessorDataHolder.getSiddhiManager().getSiddhiAppRuntimeMap();

        siddhiAppRuntimeMap.forEach((siddhiAppName, siddhiAppRuntime) -> {
            if (log.isDebugEnabled()) {
                log.debug("Starting without sources of Siddhi Application " + siddhiAppRuntime.getName());
            }
            siddhiAppRuntime.startWithoutSources();
        });
    }

    private void startSiddhiAppRuntimeSources() {
        ConcurrentMap<String, SiddhiAppRuntime> siddhiAppRuntimeMap
                = StreamProcessorDataHolder.getSiddhiManager().getSiddhiAppRuntimeMap();

        siddhiAppRuntimeMap.forEach((siddhiAppName, siddhiAppRuntime) -> {
            if (log.isDebugEnabled()) {
                log.debug("Starting sources of Siddhi Application " + siddhiAppRuntime.getName());
            }
            siddhiAppRuntime.startSources();
        });
    }

    private void stopSiddhiAppRuntimes() {
        ConcurrentMap<String, SiddhiAppRuntime> siddhiAppRuntimeMap
                = StreamProcessorDataHolder.getSiddhiManager().getSiddhiAppRuntimeMap();

        siddhiAppRuntimeMap.forEach((siddhiAppName, siddhiAppRuntime) -> {
            if (log.isDebugEnabled()) {
                log.debug("Stopping Siddhi Application " +
                        siddhiAppRuntime.getName());
            }
            siddhiAppRuntime.shutdown();
        });
    }

    private void changeSiddhiAppState(boolean state) {
        Map<String, SiddhiAppData> siddhiAppMap = StreamProcessorDataHolder.getStreamProcessorService().
                getSiddhiAppMap();

        siddhiAppMap.forEach((siddhiAppName, siddhiAppData) -> {
            if (log.isDebugEnabled()) {
                log.debug("Changed Siddhi Application " + siddhiAppName + " state to " +
                        state);
            }
            siddhiAppData.setActive(state);
        });
    }

    private String getHost(Map nodePropertiesMap) {
        Object host = nodePropertiesMap.get(HAConstants.ADVERTISED_HOST);
        if (host == null) {
            host = nodePropertiesMap.get(HAConstants.HOST);
        }
        return (String) host;
    }

    private int getPort(Map nodePropertiesMap) {
        int port = 0;
        try {
            port = (int) nodePropertiesMap.get(HAConstants.ADVERTISED_PORT);
        } catch (Exception e) {
            log.warn("Error in getting the advertisedPort from deployment yaml. Hence using port as the " +
                    "advertisedPort" + e.getMessage());
        }
        if (port == 0) {
            port = (int) nodePropertiesMap.get(HAConstants.PORT);
        }
        return port;
    }

    public void initializeEventSyncConnectionPool() {
        EventSyncConnectionPoolManager.initializeConnectionPool(host, port, deploymentConfig);
    }

    public void setPassiveNodeHostPort(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public boolean isActiveNode() {
        return isActiveNode;
    }

    public boolean isPassiveNodeAdded() {
        return passiveNodeAdded;
    }

    public void setPassiveNodeAdded(boolean passiveNodeAdded) {
        this.passiveNodeAdded = passiveNodeAdded;
    }

    public String getNodeId () {
        return nodeId;
    }

    public DeploymentConfig getDeploymentConfig() {
        return deploymentConfig;
    }
}


text:
from collections import OrderedDict
import os

from app.common.cluster_service import ClusterService
from app.master.build import Build
from app.master.build_request import BuildRequest
from app.master.build_request_handler import BuildRequestHandler
from app.master.build_scheduler_pool import BuildSchedulerPool
from app.master.slave import Slave
from app.master.slave_allocator import SlaveAllocator
from app.slave.cluster_slave import SlaveState
from app.util.conf.configuration import Configuration
from app.util.exceptions import BadRequestError, ItemNotFoundError, ItemNotReadyError
from app.util import fs
from app.util.log import get_logger

class ClusterMaster(ClusterService):
    """
    The ClusterRunner Master service: This is the main application class that the web framework/REST API sits on top of.
    """

    API_VERSION = 'v1'

    def __init__(self):
        self._logger = get_logger(__name__)
        self._master_results_path = Configuration['results_directory']
        self._all_slaves_by_url = {}
        self._all_builds_by_id = OrderedDict()
        self._scheduler_pool = BuildSchedulerPool()
        self._build_request_handler = BuildRequestHandler(self._scheduler_pool)
        self._build_request_handler.start()
        self._slave_allocator = SlaveAllocator(self._scheduler_pool)
        self._slave_allocator.start()

        # Asynchronously delete (but immediately rename) all old builds when master starts.
        # Remove this if/when build numbers are unique across master starts/stops
        if os.path.exists(self._master_results_path):
            fs.async_delete(self._master_results_path)

        fs.create_dir(self._master_results_path)

    def _get_status(self):
        """
        Just returns a dumb message and prints it to the console.

        :rtype: str
        """
        return 'Master service is up.'

    def api_representation(self):
        """
        Gets a dict representing this resource which can be returned in an API response.
        :rtype: dict [str, mixed]
        """
        slaves_representation = [slave.api_representation() for slave in self.all_slaves_by_id().values()]
        return {
            'status': self._get_status(),
            'slaves': slaves_representation,
        }

    def builds(self):
        """
        Returns a list of all builds
        :rtype: list[Build]
        """
        return self._all_builds_by_id.values()

    def active_builds(self):
        """
        Returns a list of incomplete builds
        :rtype: list[Build]
        """
        return [build for build in self.builds() if not build.is_finished]

    def all_slaves_by_id(self):
        """
        Retrieve all connected slaves
        :rtype: dict [int, Slave]
        """
        slaves_by_slave_id = {}
        for slave in self._all_slaves_by_url.values():
            slaves_by_slave_id[slave.id] = slave
        return slaves_by_slave_id

    def get_slave(self, slave_id=None, slave_url=None):
        """
        Get the instance of given slave by either the slave's id or url. Only one of slave_id or slave_url should be
        specified.

        :param slave_id: The id of the slave to return
        :type slave_id: int
        :param slave_url: The url of the slave to return
        :type slave_url: str
        :return: The instance of the slave
        :rtype: Slave
        """
        if (slave_id is None) == (slave_url is None):
            raise ValueError('Only one of slave_id or slave_url should be specified to get_slave().')

        if slave_id is not None:
            for slave in self._all_slaves_by_url.values():
                if slave.id == slave_id:
                    return slave
        else:
            if slave_url in self._all_slaves_by_url:
                return self._all_slaves_by_url[slave_url]

        raise ItemNotFoundError('Requested slave ({}) does not exist.'.format(slave_id))

    def connect_slave(self, slave_url, num_executors, slave_session_id=None):
        """
        Connect a slave to this master.

        :type slave_url: str
        :type num_executors: int
        :type slave_session_id: str | None
        :return: The response with the slave id of the slave.
        :rtype: dict[str, str]
        """
        # todo: Validate arg types for this and other methods called via API.
        # If a slave had previously been connected, and is now being reconnected, the cleanest way to resolve this
        # bookkeeping is for the master to forget about the previous slave instance and start with a fresh instance.
        if slave_url in self._all_slaves_by_url:
            old_slave = self._all_slaves_by_url.get(slave_url)
            self._logger.warning('Slave requested to connect to master, even though previously connected as {}. ' +
                                 'Removing existing slave instance from the master\'s bookkeeping.', old_slave)

            # If a slave has requested to reconnect, we have to assume that whatever build the dead slave was
            # working on no longer has valid results.
            if old_slave.current_build_id is not None:
                self._logger.info('{} has build [{}] running on it. Attempting to cancel build.', old_slave,
                                  old_slave.current_build_id)
                try:
                    build = self.get_build(old_slave.current_build_id)
                    build.cancel()
                    self._logger.info('Cancelled build {} due to dead slave {}', old_slave.current_build_id,
                                      old_slave)
                except ItemNotFoundError:
                    self._logger.info('Failed to find build {} that was running on {}', old_slave.current_build_id,
                                      old_slave)

        slave = Slave(slave_url, num_executors, slave_session_id)
        self._all_slaves_by_url[slave_url] = slave
        self._slave_allocator.add_idle_slave(slave)
        self._logger.info('Slave on {} connected to master with {} executors. (id: {})',
                          slave_url, num_executors, slave.id)
        return {'slave_id': str(slave.id)}

    def handle_slave_state_update(self, slave, new_slave_state):
        """
        Execute logic to transition the specified slave to the given state.

        :type slave: Slave
        :type new_slave_state: SlaveState
        """
        slave_transition_functions = {
            SlaveState.DISCONNECTED: self._disconnect_slave,
            SlaveState.SHUTDOWN: self._graceful_shutdown_slave,
            SlaveState.IDLE: self._slave_allocator.add_idle_slave,
            SlaveState.SETUP_COMPLETED: self._handle_setup_success_on_slave,
            SlaveState.SETUP_FAILED: self._handle_setup_failure_on_slave,
        }

        if new_slave_state not in slave_transition_functions:
            raise BadRequestError('Invalid slave state "{}". Valid states are: {}.'
                                  .format(new_slave_state, ', '.join(slave_transition_functions.keys())))

        do_transition = slave_transition_functions.get(new_slave_state)
        do_transition(slave)

    def set_shutdown_mode_on_slaves(self, slave_ids):
        """
        :type slave_ids: list[int]
        """
        # Find all the slaves first so if an invalid slave_id is specified, we 404 before shutting any of them down.
        slaves = [self.get_slave(slave_id) for slave_id in slave_ids]
        for slave in slaves:
            self.handle_slave_state_update(slave, SlaveState.SHUTDOWN)

    def _graceful_shutdown_slave(self, slave):
        """
        Puts slave in shutdown mode so it cannot receive new builds. The slave will be killed when finished with any
        running builds.
        :type slave: Slave
        """
        slave.set_shutdown_mode()
        self._logger.info('Slave on {} was put in shutdown mode. (id: {})', slave.url, slave.id)

    def _disconnect_slave(self, slave):
        """
        Mark a slave dead.

        :type slave: Slave
        """
        # Mark slave dead. We do not remove it from the list of all slaves. We also do not remove it from idle_slaves;
        # that will happen during slave allocation.
        slave.mark_dead()
        # todo: Fail/resend any currently executing subjobs still executing on this slave.
        self._logger.info('Slave on {} was disconnected. (id: {})', slave.url, slave.id)

    def _handle_setup_success_on_slave(self, slave):
        """
        Respond to successful build setup on a slave. This starts subjob executions on the slave. This should be called
        once after the specified slave has already run build_setup commands for the specified build.

        :type slave: Slave
        """
        build = self.get_build(slave.current_build_id)
        scheduler = self._scheduler_pool.get(build)
        scheduler.begin_subjob_executions_on_slave(slave)

    def _handle_setup_failure_on_slave(self, slave):
        """
        Respond to failed build setup on a slave. This should put the slave back into a usable state.

        :type slave: Slave
        """
        raise BadRequestError('Setup failure handling on the master is not yet implemented.')

    def handle_request_for_new_build(self, build_params):
        """
        Creates a new Build object and adds it to the request queue to be processed.

        :param build_params:
        :type build_params: dict[str, str]
        :rtype tuple [bool, dict [str, str]]
        """
        build_request = BuildRequest(build_params)
        success = False

        if build_request.is_valid():
            build = Build(build_request)
            self._all_builds_by_id[build.build_id()] = build
            build.generate_project_type()  # WIP(joey): This should be internal to the Build object.
            self._build_request_handler.handle_build_request(build)
            response = {'build_id': build.build_id()}
            success = True
        elif not build_request.is_valid_type():
            response = {'error': 'Invalid build request type.'}
        else:
            required_params = build_request.required_parameters()
            response = {'error': 'Missing required parameter. Required parameters: {}'.format(required_params)}

        return success, response  # todo: refactor to use exception instead of boolean

    def handle_request_to_update_build(self, build_id, update_params):
        """
        Updates the state of a build with the values passed in.  Used for cancelling running builds.

        :type build_id: int
        :param update_params: The fields that should be updated and their new values
        :type update_params: dict [str, str]
        :return: The success/failure and the response we want to send to the requestor
        :rtype: tuple [bool, dict [str, str]]
        """
        build = self._all_builds_by_id.get(int(build_id))
        if build is None:
            raise ItemNotFoundError('Invalid build id.')

        success, response = build.validate_update_params(update_params)
        if not success:
            return success, response
        return build.update_state(update_params), {}

    def handle_result_reported_from_slave(self, slave_url, build_id, subjob_id, payload=None):
        """
        Process the result and dispatch the next subjob
        :type slave_url: str
        :type build_id: int
        :type subjob_id: int
        :type payload: dict
        :rtype: str
        """
        self._logger.info('Results received from {} for subjob. (Build {}, Subjob {})', slave_url, build_id, subjob_id)
        build = self._all_builds_by_id[int(build_id)]
        slave = self._all_slaves_by_url[slave_url]
        # If the build has been canceled, don't work on the next subjob.
        if not build.is_finished:  # WIP(joey): This check should be internal to the Build object.
            try:
                build.complete_subjob(subjob_id, payload)
            finally:
                scheduler = self._scheduler_pool.get(build)
                scheduler.execute_next_subjob_or_free_executor(slave)

    def get_build(self, build_id):
        """
        Returns a build by id
        :param build_id: The id for the build whose status we are getting
        :type build_id: int
        :rtype: Build
        """
        build = self._all_builds_by_id.get(build_id)
        if build is None:
            raise ItemNotFoundError('Invalid build id: {}.'.format(build_id))

        return build

    def get_path_for_build_results_archive(self, build_id):
        """
        Given a build id, get the absolute file path for the archive file containing the build results.

        :param build_id: The build id for which to retrieve the artifacts archive file
        :type build_id: int
        :return: The path to the archived results file
        :rtype: str
        """
        build = self._all_builds_by_id.get(build_id)
        if build is None:
            raise ItemNotFoundError('Invalid build id.')

        archive_file = build.artifacts_archive_file
        if archive_file is None:
            raise ItemNotReadyError('Build artifact file is not yet ready. Try again later.')

        return archive_file

redpajama_set_name: RedPajamaGithub


text:
package de.bps.olat.modules.cl;

import java.util.List;

import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.Controller;
import org.olat.core.gui.control.DefaultController;
import org.olat.core.gui.control.WindowControl;
import org.olat.course.ICourse;
import org.olat.course.nodes.CourseNode;
import org.olat.util.logging.activity.LoggingResourceable;

/**
 * Description:

 * This Factory provides a set of specific checklist views.
 *
 *

 * Initial Date:  22.07.2009

 * @author bja <bja@bps-system.de>
 */
public class ChecklistUIFactory {

	public static CheckpointComparator comparatorTitleAsc = new CheckpointComparator(1, true);
	public static CheckpointComparator comparatorTitleDesc = new CheckpointComparator(1, false);
	public static CheckpointComparator comparatorDescriptionAsc = new CheckpointComparator(2, true);
	public static CheckpointComparator comparatorDescriptionDesc = new CheckpointComparator(2, false);
	public static CheckpointComparator comparatorModeAsc = new CheckpointComparator(3, true);
	public static CheckpointComparator comparatorModeDesc = new CheckpointComparator(3, false);

	/** singleton */
	private static ChecklistUIFactory INSTANCE = new ChecklistUIFactory();

	private ChecklistUIFactory() {
		// constructor
	}

	public static ChecklistUIFactory getInstance() {
		return INSTANCE;
	}

	/**
	 * Create run view of this checklist for course context.
	 * @param ureq
	 * @param wControl
	 * @param checklist
	 * @param filter
	 * @param canEdit
	 * @param canManage
	 * @param course
	 * @return controller
	 */
	public Controller createDisplayController(UserRequest ureq, WindowControl wControl, Checklist checklist, List<ChecklistFilter> filter, boolean canEdit, boolean canManage, ICourse course, CourseNode coursenode) {
		DefaultController checklistController = new ChecklistDisplayController(ureq, wControl, checklist, filter, canEdit, canManage, course);
		checklistController.addLoggingResourceable(LoggingResourceable.wrap(coursenode));
		return checklistController;
	}

	/**
	 * Create run view of this checklist.
	 * @param ureq
	 * @param wControl
	 * @param checklist
	 * @param filter
	 * @return controller
	 */
	public Controller createDisplayController(UserRequest ureq, WindowControl wControl, Checklist checklist, List<ChecklistFilter> filter) {
		return new ChecklistDisplayController(ureq, wControl, checklist, filter, false, false, null);
	}

	/**
	 * Create edit view of this checklist.
	 * @param ureq
	 * @param wControl
	 * @param checklist
	 * @param filter
	 * @param extendedAccess
	 * @return controller
	 */
	public Controller createEditCheckpointsController(UserRequest ureq, WindowControl wControl, Checklist checklist, String submitKey, CheckpointComparator checkpointComparator) {
		return new ChecklistEditCheckpointsController(ureq, wControl, checklist, submitKey, checkpointComparator);
	}

	/**
	 * Create manage view of this checklist.
	 * @param ureq
	 * @param wControl
	 * @param checklist
	 * @param course
	 * @return controller
	 */
	public Controller createManageCheckpointsController(UserRequest ureq, WindowControl wControl, Checklist checklist, ICourse course) {
		return new ChecklistManageCheckpointsController(ureq, wControl, checklist, course);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Joke.iml" filepath="$PROJECT_DIR$/Joke.iml" />
    </modules>
  </component>
</project>


text:
package org.scalatra.metrics

import org.scalatra.ScalatraServlet
import org.scalatra.test.scalatest.ScalatraFlatSpec

class HealthCheckSupportSpec extends ScalatraFlatSpec {

  class TestServlet extends ScalatraServlet with HealthChecksSupport {
    get("/") {
      val test = checkHealth("database") { true }
      test.execute()
    }
  }

  addServlet(new TestServlet, "/")

  "The HealthCheck support" should "not error out using a health check" in {
    get("/") {
      status should equal(200)
    }
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>../src/materials/standardMaterial.js</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for:

APIs

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

LS.Animation

LS.Animation.Track

LS.ComponentContainer

LS.Components.Camera

LS.Components.CameraController

LS.Components.CameraFX

LS.Components.FollowNode

LS.Components.FXGraphComponent

LS.Components.GeometricPrimitive

LS.Components.GraphComponent

LS.Components.Knob

LS.Components.Light

LS.Components.LightFX

LS.Components.NodeManipulator

LS.Components.PlayAnimation

LS.Components.Poser

LS.Components.RealtimeReflector

LS.Components.Spherize

LS.Components.Target

LS.Components.Transform

LS.CompositePattern

LS.Context

LS.LS

LS.LScript

LS.Material

LS.Physics

LS.PhysicsInstance

LS.Picking

LS.Prefab

LS.Renderer

LS.RenderInstance

LS.RenderOptions

LS.ResourcesManager

LS.SceneNode

LS.SceneTree

LS.StandardMaterial

LS.WBin

Rotator

VRCameraController

        Show:

            <input type="checkbox" id="api-show-inherited" checked>
            Inherited

            <input type="checkbox" id="api-show-protected">
            Protected

            <input type="checkbox" id="api-show-private">
            Private

            <input type="checkbox" id="api-show-deprecated">
            Deprecated

File: ../src/materials/standardMaterial.js

//StandardMaterial class **************************
/* Warning: a material is not a component, because it can be shared by multiple nodes */

/**
* StandardMaterial class improves the material class
* @namespace LS
* @class StandardMaterial
* @constructor
* @param {String} object to configure from
*/

function StandardMaterial(o)
{
	Material.call(this,null); //do not pass the object

	this.createProperty("ambient", new Float32Array([1.0,1.0,1.0]), "color" );
	this.createProperty("emissive", new Float32Array(3), "color" );
	//this.emissive = new Float32Array([0.0,0.0,0.0]);
	this.backlight_factor = 0;

	this.specular_ontop = false;
	this.reflection_factor = 0.0;
	this.reflection_fresnel = 1.0;
	this.reflection_additive = false;
	this.reflection_specular = false;
	this.createProperty( "velvet", new Float32Array([0.5,0.5,0.5]), "color" );
	this.velvet_exp = 0.0;
	this.velvet_additive = false;
	this._velvet_info = vec4.create();
	this._detail = new Float32Array([0.0, 10, 10]);
	this._extra_data = vec4.create();

	this.normalmap_factor = 1.0;
	this.displacementmap_factor = 0.1;
	this.bumpmap_factor = 1.0;
	this.use_scene_ambient = true;

	//used for special fx
	this.extra_surface_shader_code = "";

	this.extra_uniforms = {};

	if(o)
		this.configure(o);
}

Object.defineProperty( StandardMaterial.prototype, 'detail_factor', {
	get: function() { return this._detail[0]; },
	set: function(v) { this._detail[0] = v; },
	enumerable: true
});

Object.defineProperty( StandardMaterial.prototype, 'detail_scale', {
	get: function() { return this._detail.subarray(1,3); },
	set: function(v) { this._detail[1] = v[0]; this._detail[2] = v[1]; },
	enumerable: true
});

Object.defineProperty( StandardMaterial.prototype, 'extra_factor', {
	get: function() { return this._extra_data[3]; },
	set: function(v) { this._extra_data[3] = v; },
	enumerable: true
});

Object.defineProperty( StandardMaterial.prototype, 'extra_color', {
	get: function() { return this._extra_data.subarray(0,3); },
	set: function(v) { this._extra_data.set( v ); },
	enumerable: true
});

StandardMaterial.DETAIL_TEXTURE = "detail";
StandardMaterial.NORMAL_TEXTURE = "normal";
StandardMaterial.DISPLACEMENT_TEXTURE = "displacement";
StandardMaterial.BUMP_TEXTURE = "bump";
StandardMaterial.REFLECTIVITY_TEXTURE = "reflectivity";
StandardMaterial.IRRADIANCE_TEXTURE = "irradiance";
StandardMaterial.EXTRA_TEXTURE = "extra";

StandardMaterial.texture_channels = [ Material.COLOR_TEXTURE, Material.OPACITY_TEXTURE, Material.AMBIENT_TEXTURE, Material.SPECULAR_TEXTURE, Material.EMISSIVE_TEXTURE, StandardMaterial.DETAIL_TEXTURE, StandardMaterial.NORMAL_TEXTURE, StandardMaterial.DISPLACEMENT_TEXTURE, StandardMaterial.BUMP_TEXTURE, StandardMaterial.REFLECTIVITY_TEXTURE, Material.ENVIRONMENT_TEXTURE, StandardMaterial.IRRADIANCE_TEXTURE, StandardMaterial.EXTRA_TEXTURE ];
StandardMaterial.available_shaders = ["default","lowglobal","phong_texture","flat","normal","phong","flat_texture"];

StandardMaterial.coding_help = "\
Input IN -> info about the mesh\n\
SurfaceOutput o -> info about the surface properties of this pixel\n\
\n\
struct Input {\n\
	vec4 color;\n\
	vec3 vertex;\n\
	vec3 normal;\n\
	vec2 uv;\n\
	vec2 uv1;\n\
	\n\
	vec3 camPos;\n\
	vec3 viewDir;\n\
	vec3 worldPos;\n\
	vec3 worldNormal;\n\
	vec4 screenPos;\n\
};\n\
\n\
struct SurfaceOutput {\n\
	vec3 Albedo;\n\
	vec3 Normal;\n\
	vec3 Ambient;\n\
	vec3 Emission;\n\
	float Specular;\n\
	float Gloss;\n\
	float Alpha;\n\
	float Reflectivity;\n\
};\n\
";

// RENDERING METHODS
StandardMaterial.prototype.fillSurfaceShaderMacros = function(scene)
{
	var macros = {};

	//iterate through textures in the material
	for(var i in this.textures)
	{
		var texture_info = this.getTextureSampler(i);
		if(!texture_info) continue;
		var texture_uvs = texture_info.uvs || Material.DEFAULT_UVS[i] || "0";

		var texture = Material.getTextureFromSampler( texture_info );
		if(!texture) //loading or non-existant
			continue;

		/*
		if(i == "environment")
		{
			if(this.reflection_factor <= 0)
				continue;
		}
		else */

		if(i == "normal")
		{
			if(this.normalmap_factor != 0.0 && (!this.normalmap_tangent || (this.normalmap_tangent && gl.derivatives_supported)) )
			{
				macros.USE_NORMAL_TEXTURE = "uvs_" + texture_uvs;
				if(this.normalmap_factor != 0.0)
					macros.USE_NORMALMAP_FACTOR = "";
				if(this.normalmap_tangent && gl.derivatives_supported)
					macros.USE_TANGENT_NORMALMAP = "";
			}
			continue;
		}
		else if(i == "displacement")
		{
			if(this.displacementmap_factor != 0.0 && gl.derivatives_supported )
			{
				macros.USE_DISPLACEMENT_TEXTURE = "uvs_" + texture_uvs;
				if(this.displacementmap_factor != 1.0)
					macros.USE_DISPLACEMENTMAP_FACTOR = "";
			}
			continue;
		}
		else if(i == "bump")
		{
			if(this.bump_factor != 0.0 && gl.derivatives_supported )
			{
				macros.USE_BUMP_TEXTURE = "uvs_" + texture_uvs;
				if(this.bumpmap_factor != 1.0)
					macros.USE_BUMP_FACTOR = "";
			}
			continue;
		}

		macros[ "USE_" + i.toUpperCase() + (texture.texture_type == gl.TEXTURE_2D ? "_TEXTURE" : "_CUBEMAP") ] = "uvs_" + texture_uvs;
	}

	if(this.velvet && this.velvet_exp) //first light only
		macros.USE_VELVET = "";

	if(this.emissive_material) //dont know whats this
		macros.USE_EMISSIVE_MATERIAL = "";

	if(this.specular_ontop)
		macros.USE_SPECULAR_ONTOP = "";
	if(this.specular_on_alpha)
		macros.USE_SPECULAR_ON_ALPHA = "";
	if(this.reflection_specular)
		macros.USE_SPECULAR_IN_REFLECTION = "";
	if(this.backlight_factor > 0.001)
		macros.USE_BACKLIGHT = "";

	if(this.reflection_factor > 0.0)
		macros.USE_REFLECTION = "";

	//extra code
	if(this.extra_surface_shader_code)
	{
		var code = null;
		if(this._last_extra_surface_shader_code != this.extra_surface_shader_code)
		{
			code = Material.processShaderCode( this.extra_surface_shader_code );
			this._last_processed_extra_surface_shader_code = code;
		}
		else
			code = this._last_processed_extra_surface_shader_code;
		if(code)
			macros.USE_EXTRA_SURFACE_SHADER_CODE = code;
	}

	//extra macros
	if(this.extra_macros)
		for(var im in this.extra_macros)
			macros[im] = this.extra_macros[im];

	this._macros = macros;
}

StandardMaterial.prototype.fillSurfaceUniforms = function( scene, options )
{
	var uniforms = {};
	var samplers = {};

	uniforms.u_material_color = this._color;

	//uniforms.u_ambient_color = node.flags.ignore_lights ? [1,1,1] : [scene.ambient_color[0] * this.ambient[0], scene.ambient_color[1] * this.ambient[1], scene.ambient_color[2] * this.ambient[2]];
	if(this.use_scene_ambient && scene.info)
		uniforms.u_ambient_color = vec3.fromValues(scene.info.ambient_color[0] * this.ambient[0], scene.info.ambient_color[1] * this.ambient[1], scene.info.ambient_color[2] * this.ambient[2]);
	else
		uniforms.u_ambient_color = this.ambient;

	uniforms.u_emissive_color = this.emissive || vec3.create();
	uniforms.u_specular = this._specular_data;
	uniforms.u_reflection_info = [ (this.reflection_additive ? -this.reflection_factor : this.reflection_factor), this.reflection_fresnel ];
	uniforms.u_backlight_factor = this.backlight_factor;
	uniforms.u_normalmap_factor = this.normalmap_factor;
	uniforms.u_displacementmap_factor = this.displacementmap_factor;
	uniforms.u_bumpmap_factor = this.bumpmap_factor;

	this._velvet_info.set( this.velvet );
	this._velvet_info[3] = this.velvet_additive ? this.velvet_exp : -this.velvet_exp;
	uniforms.u_velvet_info = this._velvet_info;

	uniforms.u_detail_info = this._detail;

	uniforms.u_extra_data = this._extra_data;

	uniforms.u_texture_matrix = this.uvs_matrix;

	//iterate through textures in the material
	for(var i in this.textures)
	{
		var sampler = this.getTextureSampler(i);
		if(!sampler)
			continue;

		var texture = sampler.texture;
		if(!texture)
			continue;

		if(texture.constructor === String)
			texture = LS.ResourcesManager.textures[texture];
		else if (texture.constructor != Texture)
			continue;

		if(!texture)  //loading or non-existant
			sampler = { texture: ":missing" };
		else
			samplers[ i + (texture.texture_type == gl.TEXTURE_2D ? "_texture" : "_cubemap") ] = sampler;

		var texture_uvs = sampler.uvs || Material.DEFAULT_UVS[i] || "0";
		//last_slot += 1;

		if(texture)
		{
			if(i == "irradiance" && texture.type == gl.TEXTURE_2D)
			{
				texture.bind(0);
				texture.setParameter( gl.TEXTURE_MIN_FILTER, gl.LINEAR );
				texture.setParameter( gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
				texture.setParameter( gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
				//texture.min_filter = gl.GL_LINEAR;
			}
		}
	}

	//add extra uniforms
	for(var i in this.extra_uniforms)
		uniforms[i] = this.extra_uniforms[i];

	this._uniforms = uniforms;
	this._samplers = samplers;
}

/**
* assign a value to a property in a safe way
* @method setProperty
* @param {Object} object to configure from
*/
StandardMaterial.prototype.setProperty = function(name, value)
{
	//redirect to base material
	if( Material.prototype.setProperty.call(this,name,value) )
		return true;

	//regular
	switch(name)
	{
		//numbers
		case "backlight_factor":
		case "reflection_factor":
		case "reflection_fresnel":
		case "velvet_exp":
		case "velvet_additive":
		case "normalmap_tangent":
		case "normalmap_factor":
		case "displacementmap_factor":
		case "extra_factor":
		case "detail_factor":
		//strings
		//bools
		case "specular_ontop":
		case "normalmap_tangent":
		case "reflection_specular":
		case "use_scene_ambient":
		case "extra_surface_shader_code":
			this[name] = value;
			break;
		//vectors
		case "ambient":
		case "emissive":
		case "velvet":
		case "detail_scale":
		case "extra_color":
			if(this[name].length == value.length)
				this[name].set(value);
			break;
		case "extra_uniforms":
			this.extra_uniforms = LS.cloneObject(value);
			break;
		default:
			return false;
	}
	return true;
}

/**
* gets all the properties and its types
* @method getProperties
* @return {Object} object with name:type
*/
StandardMaterial.prototype.getProperties = function()
{
	//get from the regular material
	var o = Material.prototype.getProperties.call(this);

	//add some more
	o.merge({
		backlight_factor:"number",
		reflection_factor:"number",
		reflection_fresnel:"number",
		velvet_exp:"number",

		normalmap_factor:"number",
		displacementmap_factor:"number",
		extra_factor:"number",
		extra_surface_shader_code:"string",

		ambient:"vec3",
		emissive:"vec3",
		velvet:"vec3",
		extra_color:"vec3",
		detail_factor:"number",
		detail_scale:"vec2",

		specular_ontop:"boolean",
		normalmap_tangent:"boolean",
		reflection_specular:"boolean",
		use_scene_ambient:"boolean",
		velvet_additive:"boolean"
	});

	return o;
}

LS.registerMaterialClass( StandardMaterial );
LS.StandardMaterial = StandardMaterial;


text:
program_name="mpris-ctrl"
version=0.0.3
versionDate="2022-05-14"
mp_object="/org/mpris/MediaPlayer2"
executable="$0"

function show-help {
echo "$0 - Control MPRIS Players

USAGE:
$0 [OPTIONS]
$0 PLAYER COMMAND [ARGUMENTS]

OPTIONS:
-h, --help              Show help
-v, --version           Print version information
-l, --list              Lists available NAME targets

COMMANDS (ROOT):
raise                   Raises player window
quit                    Quits player

COMMANDS (PLAYER):
play                    Issues play command
pause                   Issues pause command
stop                    Issues stop command
play-pause              Toggles between playing and pausing
next                    Plays next item in playlist
prev[ious]              Plays previous item in playlist
status                  Displays the status of the player
volumeup [VALUE]        Increase volume level by [VALUE].
volumedown [VALUE]      Decrease volume level by [VALUE].
                        VALUE should be in range [0.1, 1.0].
                        If no [VALUE] is set then the default is 0.05
volume                  Get volume level.
volume [LEVEL]          Set volume level.
                        LEVEL should be in range [0.0, 1.0]

COMMANDS (PLAYLIST):
tracks                  Displays tracks
add-track PATH [PLAY]   Appends file PATH to playlist.
                        PLAY should be one of {true, false(default)}
                        If true: append and skip to this item in the playlist.
                        If false, append the item to the playlist.

PLAYER:
Typically this should be the player to control, e.g. 'spotify', 'vlc'.
If this exists as a MPRIS DBus destination of org.mpris.MediaPlayer2.[PLAYER],
then everything should work fine.

When using VLC, PLAYER=vlc is valid if you start VLC with 'vlc --control dbus'
If not, you have to specify the process ID, and set PLAYER=vlc.instance[PID].
For instance, pausing the VLC window with process ID 3300:
  $0 -p vlc.instance3300 pause

To see which PLAYER values are valid, use
  $0 --list

Notes:
This utility relies entirely on the PLAYER implementation of the MPRIS DBus
interface. Some commands might not work properly, e.g. spotify ignores the
'play' command, does not support org.mpris.MediaPlayer2.PlayList, and volume
level is always returned as 0 when queried.

Future improvements:
 - Work around individual player's incomplete support of MPRIS.
   E.g. if PLAYER=spotify COMMAND=play then:
           if PlaybackStatus is 'Pause', issue a PlayPause instead

Mainted at: https://gist.github.com/swarminglogic/??
Author:     Roald Fernandez (github@swarminglogic.com)
Version:    $version ($versionDate)
License:    CC-zero (public domain)
"
    exit $1
}

function list-valid-player-targets {
    echo "$(dbus-send --session --dest=org.freedesktop.DBus \
        --type=method_call --print-reply /org/freedesktop/DBus \
        org.freedesktop.DBus.ListNames | grep org.mpris.MediaPlayer2 |
        awk -F\" '{print $2}' | cut -d '.' -f4- | sort )"
}

# $1 the player name to verify.
function is-valid-player {
    if list-valid-player-targets | grep -qP '^'$1'$' ; then
        return 0
    else
        return 1
    fi
}

function parse-parameters {
    while test $# -gt 0; do
        case "$1" in
            -h|--help)
                show-help 0 ;;
            -v|--version)
                echo "$program_name $version" ; exit 0 ;;
            -l|--list)
                list-valid-player-targets ; exit 0 ;;
            *)
                player=$1 ; shift
                command=$1 ; shift ;
                leftovers="$@" ; break ;;
        esac
    done
}

# $1 interface_path
# $2 function_name
# $3..# parameters
function dbus-any-command {
    local interface_path=$1
    local function_name=$2
    shift 2
    local parameters="$@"
    dbus-send --print-reply --session \
        --dest=org.mpris.MediaPlayer2.${player} \
        $mp_object ${interface_path}.${function_name} ${parameters}
}

# For dbus-{root,player,tracklist}-command
# $1:function_name
# $2..#:parameters
function dbus-root-command {
    dbus-any-command "org.mpris.MediaPlayer2" "${1}" "${@:2}"
}
function dbus-player-command {
    dbus-any-command "org.mpris.MediaPlayer2.Player" "${1}" "${@:2}"
}
function dbus-tracklist-command {
    dbus-any-command "org.mpris.MediaPlayer2.TrackList" "${1}" "${@:2}"
}

# $1:interface_path
# $2:property_name
function dbus-get-any-property {
    dbus-send --print-reply --session \
        --dest=org.mpris.MediaPlayer2.${player} \
        $mp_object org.freedesktop.DBus.Properties.Get \
        string:"$1" string:"$2"
}

# For dbus-get-{root,player,tracklist}-property
# $1:property_name
function dbus-get-root-property {
    dbus-get-any-property "org.mpris.MediaPlayer2" "${1}"
}
function dbus-get-player-property {
    dbus-get-any-property "org.mpris.MediaPlayer2.Player" "${1}"
}
function dbus-get-tracklist-property {
    dbus-get-any-property "org.mpris.MediaPlayer2.TrackList" "${1}"
}

# $1:interface_path
# $2:property_name
# $3..#:parameters
function dbus-set-any-property {
    local interface_path=$1
    local property_name=$2
    shift 2
    local parameters="$@"
    dbus-send --print-reply --session \
        --dest=org.mpris.MediaPlayer2.${player} \
        $mp_object org.freedesktop.DBus.Properties.Set \
        string:"$interface_path" string:"$property_name" "$parameters"
}

# For dbus-set-{root,player,tracklist}-property
# $1:property_name
# $2..#:parameters
function dbus-set-root-property {
    dbus-set-any-property "org.mpris.MediaPlayer2" "${1}" "${@:2}"
}
function dbus-set-player-property {
    dbus-set-any-property "org.mpris.MediaPlayer2.Player" "${1}" "${@:2}"
}
function dbus-set-tracklist-property {
    dbus-set-any-property "org.mpris.MediaPlayer2.TrackList" "${1}" "${@:2}"
}

function execute-command {
    case $1 in
        raise)
            dbus-root-command Raise       > /dev/null ;;
        quit)
            dbus-root-command Quit        > /dev/null ;;
        play)
            dbus-player-command Play      > /dev/null ;;
        pause)
            dbus-player-command Pause     > /dev/null ;;
        stop)
            dbus-player-command Stop      > /dev/null ;;
        play-pause)
            dbus-player-command PlayPause > /dev/null ;;
        next)
            dbus-player-command Next      > /dev/null ;;
        prev|previous)
            dbus-player-command Previous  > /dev/null ;;
        volumeup)
            set -- $@
            if [ -z "${2}" ];then
                volumestep="0.05"
            else
                volumestep="${2}"
            fi
            volume_current="$(dbus-get-player-property Volume | grep double | awk '{print $3}')"
            vulumeset="$(echo - | awk "{print "${volume_current}" + "${volumestep}"}")"
            dbus-set-player-property Volume variant:double:"${vulumeset}" >/dev/null
            ;;
        volumedown)
            set -- $@
            if [ -z "${2}" ];then
                volumestep="0.05"
            else
                volumestep="${2}"
            fi
            volume_current="$(dbus-get-player-property Volume | grep double | awk '{print $3}')"
            vulumeset="$(echo - | awk "{print "${volume_current}" - "${volumestep}"}")"
            dbus-set-player-property Volume variant:double:"${vulumeset}" >/dev/null
            ;;
        volume)
            set -- $@
            if [ $# -eq 2 ] ; then
                dbus-set-player-property Volume variant:double:$2 >/dev/null
            else
                dbus-get-player-property Volume | grep double | awk '{print $3}'
            fi
            ;;
        status)
            status=$(dbus-get-player-property PlaybackStatus)
            <<<"$status" grep string | awk -F\" '{print $2}'
            ;;
        tracks)
            tracks=$(dbus-get-tracklist-property Tracks)
            <<<"$tracks" grep object | awk -F\" '{print $2}'
            ;;
        add-track)
            set -- $@
            play=false
            [ $# -ge 2 ] && file="$2"
            [ $# -eq 3 ] && play="$3"
            absolute_file=$(dirname $(readlink -e "$file"))/$(basename "$file")
            lastTrack=$($executable $player tracks | tail -n 1)
            [ -z "$lastTrack" ] && lastTrack="/org/mpris/MediaPlayer2/TrackList/NoTrack"
            if [ -f "$absolute_file" ] ; then
                dbus-tracklist-command AddTrack string:"file://${absolute_file}" \
                    objpath:$lastTrack \
                    boolean:$play > /dev/null
            fi
            ;;
        *)
            echo "'$1' is not a valid command"
            exit 1
            ;;
    esac
}

# Parse parameters, or exit with help if none
if [ $# -gt 0 ] ; then parse-parameters "$@" ; else
    echo "Error: Missing parameters" >&2
    show-help 1
fi

# Validate the specified player
if ! is-valid-player "$player" ; then
    echo "PLAYER '$player' is not a valid MPRIS target."
    echo "List of valid MPRIS targets: "
    list-valid-player-targets
    exit 1
fi

execute-command "$command" "$leftovers"


text: Presentation with browser


text:
/*
 * @test
 * @bug 4955222
 * @summary Test that the releaseMBeanServer(MBeanServer mbeanServer) method
 *          throws IllegalArgumentException as expected
 * @author Luis-Miguel Alventosa
 * @run clean ReleaseMBeanServerTest
 * @run build ReleaseMBeanServerTest
 * @run main ReleaseMBeanServerTest
 */

/* Check that the releaseMBeanServer(MBeanServer mbeanServer) method throws
   IllegalArgumentException if mbeanServer was not generated by one of the
   createMBeanServer methods, or if releaseMBeanServer was already called
   on it. */

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;

public class ReleaseMBeanServerTest {

    private static final String DOMAIN = "TestDomain";

    public static void main(String[] args) throws Exception {

        System.out.println("--------------------------------------" +
                           "-----------------------------------------");
        System.out.println("- Testing IllegalArgumentException in " +
                           "MBeanServerFactory.releaseMBeanServer() -");
        System.out.println("--------------------------------------" +
                           "-----------------------------------------");

        System.out.println("TEST_0: Call releaseMBeanServer() with " +
                           "a null MBeanServer reference.");
        try {
            MBeanServerFactory.releaseMBeanServer(null);
            System.err.println("Didn't get expected IllegalArgumentException!");
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("Got expected IllegalArgumentException!");
        }

        System.out.println("TEST_1: Call releaseMBeanServer() with an " +
                           "MBeanServer reference corresponding to an " +
                           "MBeanServer created using newMBeanServer().");
        MBeanServer mbs1 = MBeanServerFactory.newMBeanServer();
        try {
            MBeanServerFactory.releaseMBeanServer(mbs1);
            System.err.println("Didn't get expected IllegalArgumentException!");
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("Got expected IllegalArgumentException!");
        }

        System.out.println("TEST_2: Call releaseMBeanServer() with an " +
                           "MBeanServer reference corresponding to an " +
                           "MBeanServer created using newMBeanServer(String).");
        MBeanServer mbs2 = MBeanServerFactory.newMBeanServer(DOMAIN);
        try {
            MBeanServerFactory.releaseMBeanServer(mbs2);
            System.err.println("Didn't get expected IllegalArgumentException!");
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("Got expected IllegalArgumentException!");
        }

        System.out.println("TEST_3: Call releaseMBeanServer() twice with an " +
                           "MBeanServer reference corresponding to an MBean" +
                           "Server created using createMBeanServer().");
        MBeanServer mbs3 = MBeanServerFactory.createMBeanServer();
        MBeanServerFactory.releaseMBeanServer(mbs3);
        try {
            MBeanServerFactory.releaseMBeanServer(mbs3);
            System.err.println("Didn't get expected IllegalArgumentException!");
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("Got expected IllegalArgumentException!");
        }

        System.out.println("TEST_4: Call releaseMBeanServer() twice with an " +
                           "MBeanServer reference corresponding to an MBean" +
                           "Server created using createMBeanServer(String).");
        MBeanServer mbs4 = MBeanServerFactory.createMBeanServer(DOMAIN);
        MBeanServerFactory.releaseMBeanServer(mbs4);
        try {
            MBeanServerFactory.releaseMBeanServer(mbs4);
            System.err.println("Didn't get expected IllegalArgumentException!");
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.out.println("Got expected IllegalArgumentException!");
        }
    }
}


text:
#pragma once
#include <aws/lookoutmetrics/LookoutMetrics_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/lookoutmetrics/model/AnomalyGroupStatistics.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/lookoutmetrics/model/AnomalyGroupSummary.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace LookoutMetrics
{
namespace Model
{
  class AWS_LOOKOUTMETRICS_API ListAnomalyGroupSummariesResult
  {
  public:
    ListAnomalyGroupSummariesResult();
    ListAnomalyGroupSummariesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListAnomalyGroupSummariesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
A list of anomaly group summaries.

     */
    inline const Aws::Vector<AnomalyGroupSummary>& GetAnomalyGroupSummaryList() const{ return m_anomalyGroupSummaryList; }

    /**
     *
A list of anomaly group summaries.

     */
    inline void SetAnomalyGroupSummaryList(const Aws::Vector<AnomalyGroupSummary>& value) { m_anomalyGroupSummaryList = value; }

    /**
     *
A list of anomaly group summaries.

     */
    inline void SetAnomalyGroupSummaryList(Aws::Vector<AnomalyGroupSummary>&& value) { m_anomalyGroupSummaryList = std::move(value); }

    /**
     *
A list of anomaly group summaries.

     */
    inline ListAnomalyGroupSummariesResult& WithAnomalyGroupSummaryList(const Aws::Vector<AnomalyGroupSummary>& value) { SetAnomalyGroupSummaryList(value); return *this;}

    /**
     *
A list of anomaly group summaries.

     */
    inline ListAnomalyGroupSummariesResult& WithAnomalyGroupSummaryList(Aws::Vector<AnomalyGroupSummary>&& value) { SetAnomalyGroupSummaryList(std::move(value)); return *this;}

    /**
     *
A list of anomaly group summaries.

     */
    inline ListAnomalyGroupSummariesResult& AddAnomalyGroupSummaryList(const AnomalyGroupSummary& value) { m_anomalyGroupSummaryList.push_back(value); return *this; }

    /**
     *
A list of anomaly group summaries.

     */
    inline ListAnomalyGroupSummariesResult& AddAnomalyGroupSummaryList(AnomalyGroupSummary&& value) { m_anomalyGroupSummaryList.push_back(std::move(value)); return *this; }

    /**
     *
Aggregated details about the anomaly groups.

     */
    inline const AnomalyGroupStatistics& GetAnomalyGroupStatistics() const{ return m_anomalyGroupStatistics; }

    /**
     *
Aggregated details about the anomaly groups.

     */
    inline void SetAnomalyGroupStatistics(const AnomalyGroupStatistics& value) { m_anomalyGroupStatistics = value; }

    /**
     *
Aggregated details about the anomaly groups.

     */
    inline void SetAnomalyGroupStatistics(AnomalyGroupStatistics&& value) { m_anomalyGroupStatistics = std::move(value); }

    /**
     *
Aggregated details about the anomaly groups.

     */
    inline ListAnomalyGroupSummariesResult& WithAnomalyGroupStatistics(const AnomalyGroupStatistics& value) { SetAnomalyGroupStatistics(value); return *this;}

    /**
     *
Aggregated details about the anomaly groups.

     */
    inline ListAnomalyGroupSummariesResult& WithAnomalyGroupStatistics(AnomalyGroupStatistics&& value) { SetAnomalyGroupStatistics(std::move(value)); return *this;}

    /**
     *
The pagination token that's included if more results are available.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListAnomalyGroupSummariesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListAnomalyGroupSummariesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The pagination token that's included if more results are available.

     */
    inline ListAnomalyGroupSummariesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    Aws::Vector<AnomalyGroupSummary> m_anomalyGroupSummaryList;

    AnomalyGroupStatistics m_anomalyGroupStatistics;

    Aws::String m_nextToken;
  };

} // namespace Model
} // namespace LookoutMetrics
} // namespace Aws


text:
#region MIT
//
// Gorgon.
// Copyright (C) 2020 Michael Winsor
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Created: March 6, 2020 1:37:30 PM
//
#endregion

using Gorgon.Editor.UI;

namespace Gorgon.Editor.ImageEditor
{
    /// <summary>
    /// The settings view model for the sharpen effects.
    /// </summary>
    internal interface IFxSharpen
        : IHostedPanelViewModel
    {
        /// <summary>
        /// Property to set or return the amount to sharpen.
        /// </summary>
        int Amount
        {
            get;
            set;
        }
    }
}


text:
'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'     Runtime Version:2.0.50727.3603
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict Off
Option Explicit On

Namespace DTIAdminPanelTestProject

    '''<summary>
    '''Test2 class.
    '''</summary>
    '''<remarks>
    '''Auto-generated class.
    '''</remarks>
    Partial Public Class Test2
    End Class
End Namespace


text:
package dk.frankbille.jsonformatter;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
import javax.swing.SwingWorker.StateValue;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

public class MainWindow extends JFrame {
    private static final long serialVersionUID = 1L;

    private static final String PROPERTY_SOURCE = "sourcefile";
    private static final String PROPERTY_DESTINATION = "destinationfile";

    private JTextField sourceField;
    private JTextField destinationField;
    private JProgressBar progressBar;
    private JButton formatButton;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainWindow frame = new MainWindow();
                    frame.setVisible(true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MainWindow() throws FileNotFoundException, IOException {
        final File configFile = new File(System.getProperty("user.home"), ".jsonformatter");

        final Properties properties = new Properties();
        if (configFile.exists()) {
            properties.load(new FileReader(configFile));
        }

        setBounds(100, 100, 640, 240);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new FormLayout(new ColumnSpec[] {
                FormFactory.RELATED_GAP_COLSPEC,
                FormFactory.DEFAULT_COLSPEC,
                FormFactory.RELATED_GAP_COLSPEC,
                FormFactory.GLUE_COLSPEC,
                FormFactory.RELATED_GAP_COLSPEC,
                FormFactory.DEFAULT_COLSPEC,
                FormFactory.RELATED_GAP_COLSPEC,},
            new RowSpec[] {
                FormFactory.RELATED_GAP_ROWSPEC,
                FormFactory.DEFAULT_ROWSPEC,
                FormFactory.RELATED_GAP_ROWSPEC,
                FormFactory.DEFAULT_ROWSPEC,
                FormFactory.GLUE_ROWSPEC,
                FormFactory.DEFAULT_ROWSPEC,
                FormFactory.RELATED_GAP_ROWSPEC,
                FormFactory.DEFAULT_ROWSPEC,}));

        JLabel lblSourceJson = new JLabel(Messages.getString("MainWindow.lblSourceJson.text")); //$NON-NLS-1$
        getContentPane().add(lblSourceJson, "2, 2, right, default");

        sourceField = new JTextField(properties.getProperty(PROPERTY_SOURCE));
        getContentPane().add(sourceField, "4, 2, fill, default");
        sourceField.setColumns(10);

        JButton selectSourceButton = new JButton("...");
        selectSourceButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                selectFile(sourceField);
            }
        });
        getContentPane().add(selectSourceButton, "6, 2");

        JLabel lblDestinationJson = new JLabel(Messages.getString("MainWindow.lblDestinationJson.text")); //$NON-NLS-1$
        getContentPane().add(lblDestinationJson, "2, 4, right, default");

        destinationField = new JTextField(properties.getProperty(PROPERTY_DESTINATION));
        getContentPane().add(destinationField, "4, 4, fill, default");
        destinationField.setColumns(10);

        JButton selectDestinationButton = new JButton("...");
        selectDestinationButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                selectFile(destinationField);
            }
        });
        getContentPane().add(selectDestinationButton, "6, 4");

        formatButton = new JButton(Messages.getString("MainWindow.formatButton.text")); //$NON-NLS-1$
        formatButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
            	formatButton.setEnabled(false);

                final File sourceFile = new File(sourceField.getText());
                final File destinationFile = new File(destinationField.getText());

                final JsonFormatterWorker worker = new JsonFormatterWorker(sourceFile, destinationFile, progressBar);
                worker.addPropertyChangeListener(new PropertyChangeListener() {
					@Override
					public void propertyChange(PropertyChangeEvent changeEvent) {
						if ("state".equals(changeEvent.getPropertyName()) && ((StateValue) changeEvent.getNewValue()) == StateValue.DONE) {
							if (worker.hasErrors() == false) {
								properties.setProperty(PROPERTY_SOURCE, sourceFile.getAbsolutePath());
								properties.setProperty(PROPERTY_DESTINATION, destinationFile.getAbsolutePath());
								try {
									properties.store(new FileWriter(configFile), null);
								} catch (IOException e) {
									throw new RuntimeException(e);
								}
							}

							formatButton.setEnabled(true);
						}
					}
				});
                worker.execute();
            }
        });

        progressBar = new JProgressBar();
        progressBar.setStringPainted(true);
        getContentPane().add(progressBar, "2, 6, 5, 1");
        getContentPane().add(formatButton, "2, 8, 5, 1");

        // Center on screen
        setLocationRelativeTo(null);
    }

    private void selectFile(JTextField field) {
        JFileChooser selectFile = new JFileChooser();
        selectFile.setMultiSelectionEnabled(false);
        selectFile.setFileSelectionMode(JFileChooser.FILES_ONLY);
        selectFile.setFileFilter(new FileNameExtensionFilter(Messages.getString("SelectFile.jsonExtensionDescription"), "json"));
        File file = new File(field.getText());
        selectFile.setSelectedFile(file);
        if (selectFile.showDialog(MainWindow.this, Messages.getString("SelectFile.buttonText")) == JOptionPane.OK_OPTION) {
            field.setText(selectFile.getSelectedFile().getAbsolutePath());
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<mode>
<info extension="html" mode="text" name="*"/>
<info extension="tx" mode="binary" name="*.pot"/>
<info extension="txt" mode="text" name="*.tdd"/>
<info extension="shtml" mode="text" name="*"/>
<info extension="cf" mode="binary" name="*"/>
<info extension="wvr" mode="binary" name="*"/>
<info extension="tdd" mode="binary" name="*"/>
<info extension="edb" mode="binary" name="*"/>
<info extension="htm" mode="text" name="*"/>
<info extension="pot" mode="binary" name="*"/>
<info extension="wva" mode="binary" name="*"/>
</mode>


text:
"""

Revision ID: 0210_remove_monthly_billing
Revises: 0209_add_cancelled_status
Create Date: 2018-07-31 16:43:00.568972

"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision = "0210_remove_monthly_billing"
down_revision = "0209_add_cancelled_status"

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index("ix_monthly_billing_service_id", table_name="monthly_billing")
    op.drop_table("monthly_billing")
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "monthly_billing",
        sa.Column("id", postgresql.UUID(), autoincrement=False, nullable=False),
        sa.Column("service_id", postgresql.UUID(), autoincrement=False, nullable=False),
        sa.Column(
            "notification_type",
            postgresql.ENUM("email", "sms", "letter", name="notification_type"),
            autoincrement=False,
            nullable=False,
        ),
        sa.Column("monthly_totals", postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=False),
        sa.Column("updated_at", postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
        sa.Column("start_date", postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
        sa.Column("end_date", postgresql.TIMESTAMP(), autoincrement=False, nullable=False),
        sa.ForeignKeyConstraint(["service_id"], ["services.id"], name="monthly_billing_service_id_fkey"),
        sa.PrimaryKeyConstraint("id", name="monthly_billing_pkey"),
        sa.UniqueConstraint("service_id", "start_date", "notification_type", name="uix_monthly_billing"),
    )
    op.create_index("ix_monthly_billing_service_id", "monthly_billing", ["service_id"], unique=False)
    # ### end Alembic commands ###


text:
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import "ADALTokenCacheItem.h"

@class ADALAuthenticationError;
@class ADALAuthenticationResult;

@interface ADALTokenCacheItem ()

@property (readonly) NSDictionary * additionalServer;

// Intune Enrollment ID. Application trying to retrieve access token from cache will need to present a valid intune enrollment ID to complete cache lookup.
@property (nonatomic) NSString *enrollmentId;

// Unique app identifier used for cases when access token storage needs to be partitioned per application
@property (nonatomic) NSString *applicationIdentifier;

@end

@interface ADALTokenCacheItem ()

@property NSString *storageAuthority;

@end

@interface ADALTokenCacheItem (Internal)

/*!
 This indicates whether the request was executed on a ring serving SPE traffic.
 An empty string indicates this occurred on an outer ring,
 and the string "I" indicated the request occurred on the inner ring.
 */
@property (readonly) NSString *speInfo;

- (void)logMessage:(NSString *)message
             level:(MSIDLogLevel)level
     correlationId:(NSUUID*)correlationId;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.google</groupId>
		<artifactId>google</artifactId>
		<version>5</version>
	</parent>
	<groupId>com.google.apis-samples</groupId>
	<artifactId>analytics</artifactId>
	<version>1</version>
	<name>Example for the Google Google Analytics API v3 using OAuth 2.0.</name>
	<packaging>war</packaging>
	<url>http://code.google.com/p/google-api-java-client/</url>

	<inceptionYear>2013</inceptionYear>

	<prerequisites>
		<maven>2.0.9</maven>
	</prerequisites>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>exec-maven-plugin</artifactId>
				<version>1.1</version>
				<executions>
					<execution>
						<goals>
							<goal>java</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<mainClass>com.google.api.services.samples.analytics.cmdline.AnalyticsSample</mainClass>
					<systemProperties>
						<systemProperty>
							<key>java.util.logging.config.file</key>
							<value>logging.properties</value>
						</systemProperty>
					</systemProperties>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<webResources>
						<resource>
							<!-- this is relative to the pom.xml directory -->
							<directory>credentials</directory>
						</resource>
					</webResources>
				</configuration>
      		</plugin>
		</plugins>
		<finalName>analytics</finalName>
	</build>
	<dependencies>
		<dependency>
			<groupId>com.google.apis</groupId>
			<artifactId>google-api-services-analytics</artifactId>
			<version>v3-rev96-1.18.0-rc</version>
		</dependency>
		<dependency>
			<groupId>com.google.http-client</groupId>
			<artifactId>google-http-client-jackson2</artifactId>
			<version>${project.http.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.oauth-client</groupId>
			<artifactId>google-oauth-client-jetty</artifactId>
			<version>${project.oauth.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>com.wut</groupId>
			<artifactId>core</artifactId>
			<version>1.0-SNAPSHOT</version>
			<scope>compile</scope>
		</dependency>

	</dependencies>
	<properties>
		<project.http.version>1.18.0-rc</project.http.version>
		<project.oauth.version>1.18.0-rc</project.oauth.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
</project>