text:
package io.fabric8.mq.fabric;

import java.beans.PropertyEditorManager;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jms.ConnectionFactory;

import io.fabric8.api.Container;
import io.fabric8.api.FabricService;
import io.fabric8.groups.Group;
import io.fabric8.groups.GroupListener;
import io.fabric8.mq.fabric.discovery.FabricDiscoveryAgent;
import io.fabric8.utils.NamedThreadFactory;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.LockableServiceSupport;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.network.DiscoveryNetworkConnector;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.spring.SpringBrokerContext;
import org.apache.activemq.spring.Utils;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.util.IntrospectionSupport;
import org.apache.activemq.util.ServiceSupport;
import org.apache.curator.framework.CuratorFramework;
import org.apache.xbean.classloader.MultiParentClassLoader;
import org.apache.xbean.spring.context.ResourceXmlApplicationContext;
import org.apache.xbean.spring.context.impl.URIEditor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;

import static io.fabric8.mq.fabric.discovery.FabricDiscoveryAgent.ActiveMQNode;

public class ActiveMQServiceFactory  {

    public static final Logger LOG = LoggerFactory.getLogger(ActiveMQServiceFactory.class);
    public static final ThreadLocal<Properties> CONFIG_PROPERTIES = new ThreadLocal<Properties>();
    public static final int SHUTDOWN_TIMEOUT_IN_SECONDS = 60;

    BundleContext bundleContext;

    // Pool management

    private Set<String> ownedPools = new HashSet<String>();

    // Maintain a registry of configuration based on ManagedServiceFactory events.
    private Map<String, ClusteredConfiguration> configurations = new HashMap<String, ClusteredConfiguration>();

    volatile FabricService fabricService;
    private ConfigThread config_thread;
    CuratorFramework curator;

    public ActiveMQServiceFactory() {
        // code that was inlined through all Scala ActiveMQServiceFactory class
        config_thread = new ConfigThread();
        config_thread.setName("ActiveMQ Configuration Watcher");
        config_thread.start();
    }

    /* statics - from Scala object */

    static {
        PropertyEditorManager.registerEditor(URI.class, URIEditor.class);
    }

//    public static void info(String str) {
//        if (LOG.isInfoEnabled()) {
//            LOG.info(str);
//        }
//    }
//
//    public static void info(String str, Object... args) {
//        if (LOG.isInfoEnabled()) {
//            LOG.info(String.format(str, args));
//        }
//    }
//
//    public static void debug(String str) {
//        if (LOG.isDebugEnabled()) {
//            LOG.debug(str);
//        }
//    }
//
//    public static void debug(String str, Object... args) {
//        if (LOG.isDebugEnabled()) {
//            LOG.debug(String.format(str, args));
//        }
//    }
//
//    public static void warn(String str) {
//        if (LOG.isWarnEnabled()) {
//            LOG.warn(str);
//        }
//    }
//
//    public static void warn(String str, Object... args) {
//        if (LOG.isWarnEnabled()) {
//            LOG.warn(String.format(str, args));
//        }
//    }

    public static Dictionary<String, Object> toDictionary(Properties properties) {
        Hashtable<String, Object> answer = new Hashtable<String, Object>();
        for (String k : properties.stringPropertyNames()) {
            answer.put(k, properties.getProperty(k));
        }
        return answer;
    }

    public static <T> T arg_error(String msg) {
        throw new IllegalArgumentException(msg);
    }

    public ServerInfo createBroker(String uri, Properties properties) throws Exception {
        CONFIG_PROPERTIES.set(properties);
        try {
            ClassLoader classLoader = new MultiParentClassLoader("xbean", new URL[0], new ClassLoader[] {
                this.getClass().getClassLoader(),
                BrokerService.class.getClassLoader()
            });
            Thread.currentThread().setContextClassLoader(classLoader);

            Resource resource = Utils.resourceFromString(uri);

            // To work around ENTESB-2761, lets wait up to 10 seconds for the broker.xml
            // to get deployed before trying to start the broker.
            for( int i=0; !resource.exists() && i < 100; i++ ) {
               Thread.sleep(100);
            }

            ResourceXmlApplicationContext ctx = new ResourceXmlApplicationContext(resource) {
                @Override
                protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
                    reader.setValidating(false);
                }
            };

            String[] names = ctx.getBeanNamesForType(BrokerService.class);
            BrokerService broker = null;
            for (String name : names) {
                broker = (BrokerService) ctx.getBean(name, BrokerService.class);
                if (broker != null) {
                    break;
                }
            }
            if (broker == null) {
                arg_error("Configuration did not contain a BrokerService");
            }

            String networks = properties.getProperty("network", "");
            String[] networksTab = networks.split(",");
            for (String name : networksTab) {
                if (!name.isEmpty()) {
                    LOG.info("Adding network connector " + name);
                    NetworkConnector nc = createNetworkConnector(new URI("fabric:" + name),properties);
                    nc.setName("fabric-" + name);
                    if (broker != null) {
                        // and if it's null, then exception was thrown already. It's just IDEA complaining
                        broker.addNetworkConnector(nc);
                    }
                }
            }

            //static network connectors
            String staticNetworks = properties.getProperty("static-network", "");
            networksTab = staticNetworks.split(",");
            for (String name : networksTab) {
                if (!name.isEmpty()) {
                    LOG.info("Adding static network connector " + name);
                    NetworkConnector nc = createNetworkConnector(new URI("static:(" + name + ")"),properties);
                    nc.setName("static-"+ name);
                    if (broker != null) {
                        broker.addNetworkConnector(nc);
                    }
                }
            }

            SpringBrokerContext brokerContext = new SpringBrokerContext();
            brokerContext.setConfigurationUrl(resource.getURL().toExternalForm());
            brokerContext.setApplicationContext(ctx);
            if (broker != null) {
                broker.setBrokerContext(brokerContext);
            }
            return new ServerInfo(ctx, broker, resource);
        } finally {
            CONFIG_PROPERTIES.remove();
        }
    }

    /* now non-static members from Scala class */

    public synchronized boolean can_own_pool(ClusteredConfiguration cc) {
        return cc.pool == null || !ownedPools.contains(cc.pool);
    }

    public synchronized boolean take_pool(ClusteredConfiguration cc) {
        if (cc.pool == null) {
            return true;
        } else {
            if (ownedPools.contains(cc.pool)) {
                return false;
            } else {
                ownedPools.add(cc.pool);
                fire_pool_change(cc);
                return true;
            }
        }
    }

    public synchronized void return_pool(ClusteredConfiguration cc) {
        if (cc.pool != null) {
            ownedPools.remove(cc.pool);
            fire_pool_change(cc);
        }
    }

    private void fire_pool_change(final ClusteredConfiguration cc) {
        (new Thread() {
            @Override
            public void run() {
                synchronized (ActiveMQServiceFactory.this) {
                    for (ClusteredConfiguration c : configurations.values()) {
                        if (c != cc && c != null && c.pool != null && c.pool.equals(cc.pool)) {
                            c.update_pool_state();
                        }
                    }
                }
            }
        }).start();
    }

    BrokerService getBrokerService(String name) {
        synchronized (ActiveMQServiceFactory.this) {
            for (ClusteredConfiguration c : configurations.values()) {
                if( name.equals(c.name) ) {
                    if( c.server == null ) {
                        return null;
                    }
                    return c.server.getBroker();
                }
            }
        }
        return null;
    }

    // ManagedServiceFactory implementation

    public synchronized void updated(String pid, Properties properties) throws ConfigurationException {
        try {
            deleted(pid);
            configurations.put(pid, new ClusteredConfiguration(properties));
        } catch (Exception e) {
            ConfigurationException configurationException = new ConfigurationException(null, "Unable to parse ActiveMQ configuration: " + e.getMessage());
            configurationException.initCause(e);
            throw configurationException;
        }
    }

    public synchronized void deleted(String pid) {
        ClusteredConfiguration cc = configurations.remove(pid);
        if (cc != null) {
            try {
                cc.close();
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }

    // Lifecycle
    public synchronized void destroy() throws InterruptedException {
        config_thread.running = false;
        config_thread.interrupt();
        config_thread.join();
        for (String pid : configurations.keySet()) {
            deleted(pid);
        }
    }

    private NetworkConnector createNetworkConnector(URI uri,Properties properties) throws URISyntaxException, IOException {
        NetworkConnector nc = new DiscoveryNetworkConnector(uri);
        Map<String, Object> networkProperties = new HashMap<String, Object>();
        // use default credentials for network connector (if none was specified)
        networkProperties.put("network.userName", "admin");
        networkProperties.put("network.password", properties.getProperty("zookeeper.password"));

        for (String k : properties.stringPropertyNames()) {
            networkProperties.put(k, properties.getProperty(k));
        }

        IntrospectionSupport.setProperties(nc, networkProperties, "network.");
        return nc;
    }

    /**
     * 3 items that define Broker
     */
    private static class ServerInfo {

        private /*_1*/ ResourceXmlApplicationContext context;
        private /*_2*/ BrokerService broker;
        private /*_3*/ Resource resource;

        public ServerInfo(ResourceXmlApplicationContext context, BrokerService broker, Resource resource) {
            this.context = context;
            this.broker = broker;
            this.resource = resource;
        }

        public ResourceXmlApplicationContext getContext() {
            return context;
        }

        public BrokerService getBroker() {
            return broker;
        }

        public Resource getResource() {
            return resource;
        }

    }

    private class ClusteredConfiguration {

        private Properties properties;
        String name;
        private String data;
        private String config;
        private String group;
        private String pool;
        private String[] connectors;
        private boolean replicating;
        private boolean standalone;
        private boolean registerService;
        private boolean configCheck;

        private boolean pool_enabled = false;
        private long lastModified = -1L;

        volatile ServerInfo server;

        private FabricDiscoveryAgent discoveryAgent = null;

        private final AtomicBoolean started = new AtomicBoolean();

        private ExecutorService executor = Executors.newSingleThreadExecutor(new NamedThreadFactory("AMQ"));

        private Future<?> start_future = null;
        private Future<?> stop_future = null;

        private ServiceRegistration<javax.jms.ConnectionFactory> cfServiceRegistration = null;

        ClusteredConfiguration(Properties properties) throws Exception {
            this.properties = properties;

            this.name = properties.getProperty("broker-name");
            if (this.name == null)
                this.name = System.getProperty("runtime.id");

            this.data = properties.getProperty("data");
            if (this.data == null)
                this.data = "data" + System.getProperty("file.separator") + this.name;

            this.config = properties.getProperty("config");
            if (this.config == null)
                ActiveMQServiceFactory.arg_error("config property must be set");

            this.group = properties.getProperty("group");
            if (this.group == null)
                this.group = "default";

            this.pool = properties.getProperty("standby.pool");
            if (this.pool == null)
                this.pool = "default";

            String connectorsProperty = properties.getProperty("connectors", "");
            this.connectors = connectorsProperty.split("\\s");

            this.replicating = "true".equalsIgnoreCase(properties.getProperty("replicating"));
            this.standalone = "true".equalsIgnoreCase(properties.getProperty("standalone"));
            this.registerService = "true".equalsIgnoreCase(properties.getProperty("registerService"));
            this.configCheck = "true".equalsIgnoreCase(properties.getProperty("config.check"));

            // code directly invoked in Scala case class
            ensure_broker_name_is_set();

            if (standalone) {
                if (started.compareAndSet(false, true)) {
                    LOG.info("Standalone broker " + name + " is starting.");
                    start();
                }
            } else {
                updateCurator(curator);
            }
        }

        private void ensure_broker_name_is_set() {
            if (!properties.containsKey("broker-name")) {
                properties.setProperty("broker-name", name);
            }
            if (!properties.containsKey("data")) {
                properties.setProperty("data", data);
            }
        }

        public void update_pool_state() {
            synchronized (ActiveMQServiceFactory.this) {
                boolean value = can_own_pool(this);
                if (pool_enabled != value) {
                    try {
                        pool_enabled = value;
                        if (value) {
                            if (pool != null) {
                                LOG.info("Broker " + name + " added to pool " + pool +".");
                            }
                            discoveryAgent.start();
                        } else {
                            if (pool != null) {
                                LOG.info("Broker " + name + " removed from pool " + pool + ".");
                            }
                            discoveryAgent.stop();
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                }
            }
        }

        public void osgiRegister(BrokerService broker) {
            final javax.jms.ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + broker.getBrokerName() + "?create=false");
            Hashtable<String, String> properties = new Hashtable<String, String>();
            properties.put("name", broker.getBrokerName());
            cfServiceRegistration = bundleContext.registerService(ConnectionFactory.class/*.getName()*/, connectionFactory, properties);
            LOG.debug("registerService of type " + javax.jms.ConnectionFactory.class.getName()  + " as: " + connectionFactory + " with name: " + broker.getBrokerName() + "; " + cfServiceRegistration);
        }

        public void osgiUnregister(BrokerService broker) {
            if (cfServiceRegistration != null) {
                cfServiceRegistration.unregister();
            }
            LOG.debug("unregister connection factory for: " + broker.getBrokerName() + "; " + cfServiceRegistration);
        }

        private void start() {
            if (start_future == null || start_future.isDone()) {
                LOG.info("Broker " + name + " is being started.");
                start_future = executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        boolean started = false;
                        while (!started) {
                            try {
                                doStart();
                                if (server != null && server.getResource() != null) {
                                    lastModified = server.getResource().lastModified();
                                }
                                started = true;
                            } catch (Throwable e) {
                                if (start_future.isCancelled() || Thread.currentThread().isInterrupted()) {
                                    LOG.info("Broker " + name + " interrupted while starting");
                                    break;
                                }
                                LOG.info("Broker " + name + " failed to start.  Will try again in 10 seconds");
                                LOG.error("Exception on start: " + e, e);
                                try {
                                    Thread.sleep(1000 * 10);
                                } catch (InterruptedException ignore) {
                                    LOG.info("Broker " + name + " interrupted while starting");
                                    break;
                                }
                            }
                        }
                    }
                });
            }
        }

        private void doStart() throws Exception {
            // If we are in a fabric, let pass along the zk password in the props.
            FabricService fs = fabricService;
            if (fs != null) {
                Container container = fs.getCurrentContainer();
                if (!properties.containsKey("container.id")) {
                    properties.setProperty("container.id", container.getId());
                }
                if (!properties.containsKey("container.ip")) {
                    properties.setProperty("container.ip", container.getIp());
                }
                if (!properties.containsKey("zookeeper.url")) {
                    properties.setProperty("zookeeper.url", fs.getZookeeperUrl());
                }
                if (!properties.containsKey("zookeeper.password")) {
                    properties.setProperty("zookeeper.password", fs.getZookeeperPassword());
                }
            }
            // ok boot up the server..
            LOG.info("booting up a broker from: " + config);
            server = createBroker(config, properties);
            // configure ports
            for (TransportConnector t : server.getBroker().getTransportConnectors()) {
                String portKey = t.getName() + "-port";
                if (properties.containsKey(portKey)) {
                    URI template = t.getUri();
                    t.setUri(new URI(template.getScheme(), template.getUserInfo(), template.getHost(),
                        Integer.valueOf("" + properties.get(portKey)),
                        template.getPath(), template.getQuery(), template.getFragment()));
                }
            }

            server.getBroker().start();
            LOG.info("Broker " + name + " has started.");

            server.getBroker().waitUntilStarted();
            server.getBroker().addShutdownHook(new Runnable() {
                @Override
                public void run() {
                    // Start up the server again if it shutdown.  Perhaps
                    // it has lost a Locker and wants a restart.
                    if (started.get() && server != null) {
                        if (server.getBroker().isRestartAllowed() && server.getBroker().isRestartRequested()) {
                            LOG.info("Restarting broker '" + name + "' after shutdown on restart request");
                            if (!standalone) {
                                discoveryAgent.setServices(new String[0]);
                            }
                            start();
                        } else if (stop_future == null || stop_future.isDone()) {
                            // abnormal exit
                            LOG.info("Broker '" + name + "' shut down, giving up being master");
                            try {
                                updateCurator(curator);
                            } catch (Exception e) {
                                throw new RuntimeException(e.getMessage(), e);
                            }
                        }
                    }
                }
            });

            // we only register once broker startup has completed.
            if (replicating) {
                discoveryAgent.start();
            }

            // Update the advertised endpoint URIs that clients can use.
            if (!standalone || replicating) {
                registerConnectors();
            }

            if (registerService) {
                osgiRegister(server.getBroker());
            }
        }

        private void registerConnectors() throws Exception {
            List<String> services = new LinkedList<String>();
            for (String name : connectors) {
                TransportConnector connector = server.getBroker().getConnectorByName(name);
                if (connector == null) {
                    LOG.warn("ActiveMQ broker '" + server.getBroker().getBrokerName() + "' does not have a connector called '" + name + "'");
                } else {
                    String ip = (String) properties.get("container.ip");
                    if( ip==null ) {
                        ip = "${zk:" + System.getProperty("runtime.id") + "/ip}";
                    }
                    services.add(connector.getConnectUri().getScheme() + "://" + ip + ":" + connector.getPublishableConnectURI().getPort());
                }
            }
            discoveryAgent.setServices(services.toArray(new String[services.size()]));
        }

        public void close() throws Exception {
            LOG.debug(this + " close");
            synchronized (ActiveMQServiceFactory.this) {
                if (pool_enabled) {
                    return_pool(this);
                }
                if (discoveryAgent != null) {
                    discoveryAgent.stop();
                }
            }
            disconnect();
            // we need to let any possible stop task execute
            executor.shutdown();
            executor.awaitTermination(SHUTDOWN_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
        }

        public void stop() throws ExecutionException, InterruptedException {
            synchronized (ActiveMQServiceFactory.this) {
                interruptAndWaitForStart();
                if (stop_future == null || stop_future.isDone()) {
                    stop_future = executor.submit(new Runnable() {
                        @Override
                        public void run() {
                            doStop();
                        }
                    });
                }
            }
        }

        private void doStop() {
            final ServerInfo s = server; // working with a volatile
            if (s != null) {
                try {
                    s.getBroker().stop();
                    s.getBroker().waitUntilStopped();
                    if (!standalone || replicating) {
                        // clear out the services as we are no longer alive
                        discoveryAgent.setServices(new String[0]);
                    }
                    if (registerService) {
                        osgiUnregister(s.getBroker());
                    }
                } catch (Throwable e) {
                    LOG.debug("Exception on stop: " + e.getMessage(),  e);
                }
                try {
                    s.getContext().close();
                } catch (Throwable e) {
                    LOG.debug("Exception on close: " + e.getMessage(), e);
                }
                server = null;
            }
        }

        private void waitForStop() throws ExecutionException, InterruptedException {
            if (stop_future != null) {
                try {
                    stop_future.get(SHUTDOWN_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
                } catch (TimeoutException e) {
                    LOG.error("Unable to shutdown ActiveMQ in the allotted {} seconds.", SHUTDOWN_TIMEOUT_IN_SECONDS);
                } catch (CancellationException ignore) {
                }
            }
        }

        private void interruptAndWaitForStart() throws ExecutionException, InterruptedException {
            if (start_future != null && !start_future.isDone()) {
                start_future.cancel(false);
                long timeOutSeconds = SHUTDOWN_TIMEOUT_IN_SECONDS;
                if (server != null && server.broker != null) {
                    // slave possibly blocked on store lock, wait for store locker start before calling stop
                    try {

                        PersistenceAdapter persistenceAdapter = server.broker.getPersistenceAdapter();
                        if (persistenceAdapter != null && persistenceAdapter instanceof LockableServiceSupport) {
                            LockableServiceSupport lockableServiceSupport = (LockableServiceSupport) persistenceAdapter;
                            if (lockableServiceSupport.isUseLock() && lockableServiceSupport.getLocker() instanceof ServiceSupport) {
                                ServiceSupport lockService = ((ServiceSupport)lockableServiceSupport.getLocker());
                                while (!lockService.isStarted() && timeOutSeconds > 0) {
                                    TimeUnit.SECONDS.sleep(1);
                                    timeOutSeconds--;
                                }
                                LOG.info("broker stop on active async start, blocked on store lock:" + lockService.isStarted());
                                server.broker.stop();
                            }
                        }
                    } catch (Exception e) {
                        LOG.warn("Call to stop failed with exception:" + e.getLocalizedMessage());
                    }
                }
                try {
                   start_future.get(timeOutSeconds, TimeUnit.SECONDS);
                } catch (TimeoutException e) {
                    LOG.error("Unable to cancel startup ActiveMQ in the allotted {} seconds.", SHUTDOWN_TIMEOUT_IN_SECONDS);
                } catch (CancellationException ignore) {
                }
            }
        }

        public void updateCurator(CuratorFramework curator) throws Exception {
            if (!standalone) {
                synchronized (ActiveMQServiceFactory.this) {
                    if (discoveryAgent != null) {
                        discoveryAgent.stop();
                        discoveryAgent = null;
                        if (started.compareAndSet(true, false)) {
                            LOG.info("Lost zookeeper service for broker " + name + ", stopping the broker.");
                            stop();
                            waitForStop();
                            return_pool(this);
                            pool_enabled = false;
                        }
                    }
                    waitForStop();
                    if (curator != null) {
                        LOG.info("Found zookeeper service for broker " + name + ".");
                        discoveryAgent = new FabricDiscoveryAgent();
                        discoveryAgent.setAgent(System.getProperty("runtime.id"));
                        discoveryAgent.setId(name);
                        discoveryAgent.setGroupName(group);
                        discoveryAgent.setCurator(curator);
                        if (replicating) {
                            if (started.compareAndSet(false, true)) {
                                LOG.info("Replicating broker " + name + " is starting.");
                                start();
                            }
                        } else {
                            discoveryAgent.getGroup().add(new GroupListener<ActiveMQNode>() {
                                @Override
                                public void groupEvent(Group<ActiveMQNode> group, GroupEvent event) {
                                    try {
                                        LOG.trace("Event:" + event + ", started:" + started.get());
                                        if (event.equals(GroupEvent.CONNECTED) || event.equals(GroupEvent.CHANGED)) {
                                            if (discoveryAgent.getGroup().isMaster(name)) {
                                                if (started.compareAndSet(false, true)) {
                                                    if (take_pool(ClusteredConfiguration.this)) {
                                                        LOG.info("Broker " + name + " is now the master, starting the broker.");
                                                        start();
                                                    } else {
                                                        update_pool_state();
                                                        started.set(false);
                                                    }
                                                } else {
                                                    if (discoveryAgent.getServices().isEmpty() && server != null && server.getBroker() != null && server.getBroker().isStarted()) {
                                                        LOG.info("Reconnected to the group " + name);
                                                        registerConnectors();
                                                    }
                                                }
                                            } else {
                                                if (started.compareAndSet(true, false)) {
                                                    return_pool(ClusteredConfiguration.this);
                                                    LOG.info("Broker " + name + " is now a slave, stopping the broker.");
                                                    stop();
                                                } else {
                                                    if (event.equals(GroupEvent.CHANGED)) {
                                                        LOG.info("Broker " + name + " is slave");
                                                        if (!discoveryAgent.getServices().isEmpty()) {
                                                            discoveryAgent.setServices(new String[0]);
                                                        }
                                                    }
                                                }
                                            }
                                        } else if (event.equals(GroupEvent.DISCONNECTED)) {
                                            LOG.info("Disconnected from the group " + name);
                                            disconnect();
                                        }
                                    } catch (Exception e) {
                                        throw new RuntimeException(e.getMessage(), e);
                                    }
                                }
                            });

                            LOG.info("Broker " + name + " is waiting to become the master");
                            update_pool_state();
                        }
                    } else {
                        LOG.info("Lost zookeeper service for broker " + name);
                        disconnect();
                    }
                }
            }
        }

        private void disconnect() throws Exception {
            if (started.compareAndSet(true, false)) {
              return_pool(ClusteredConfiguration.this);
              LOG.info("Stopping the broker " + name + ".");
              stop();
            } else {
              LOG.info("Disconnecting the broker " + name + ".");
              discoveryAgent.setServices(new String[0]);
              pool_enabled = false;
            }
        }

    }

    private class ConfigThread extends Thread {

        private boolean running = true;

        @Override
        public void run() {
            while (running) {
                for (ClusteredConfiguration c: configurations.values()) {
                    try {
                        if (c.configCheck && c.lastModified != -1 && c.server != null) {
                            long lm = c.server.getResource().lastModified();
                            if (lm != c.lastModified) {
                                c.lastModified = lm;
                                LOG.info("updating " + c.properties);
                                updated((String) c.properties.get("service.pid"), c.properties);
                            }
                        }
                    } catch (Throwable t) {
                        // ?
                    }
                }
                try {
                    Thread.sleep(5 * 1000);
                } catch (InterruptedException e) {
                    // ?
                }
            }
        }

    }

}


text:
The flex-object is a powerful suite of utilities based on the
flexible box layout module.
These utilities can replace the need for a grid system in many instances,
but can also be combined with the Basscss grid for even more possibilities.

Note: browser support for the flexible box layout module is limited. See http://caniuse.com/#feat=flexbox

## .flex
To begin, add the `.flex` class to a parent element.
This sets the element to `display: flex` and enables a flex context for all direct child elements.
```html
<div class="flex">
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
```

## .flex-wrap
To wrap elements, use the `.flex-wrap` utility.
```html
<div class="flex flex-wrap">
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
```

## .flex-column
To arrange items vertically, use the `.flex-column` utility.
```html
<div class="flex flex-column">
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
```

## Alignment
Use these utilities to control vertical alignment of child elements.

### .flex-center
To vertically center child elements, add the `.flex-center` class to the parent element.
```html
<div class="flex flex-center">
  <div class="flex-auto px2 py4 blue border">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="px2 blue border">Hot dog</div>
</div>
```

### .flex-stretch
To stretch all elements to fill the height of the parent, use the `.flex-stretch` utility.
```html
<div class="flex flex-stretch">
  <div class="flex-auto px2 py4 blue border">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="px2 blue border">Hot dog</div>
</div>
```

### .flex-stretch with nested content
To ensure nested elements stretch as well, add the `.flex` class to relevant elements.
```html
<div class="flex flex-stretch">
  <div class="flex-auto px2 py4 blue border">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="flex blue border">
    <div class="px2 white bg-blue">
      Hot dog
    </div>
  </div>
</div>
```

### .flex-baseline
To align child elements to their baseline, use the `.flex-baseline` utility.

```html
<div class="flex flex-baseline blue border-bottom">
  <div class="flex-auto px2">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="px2">Hot dog</div>
</div>
```

### .flex-start
To align child elements to the top, use the `.flex-start` utility.

```html
<div class="flex flex-start blue border-top">
  <div class="flex-auto px2">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="px2">Hot dog</div>
</div>
```

### .flex-end
To align child elements to the bottom, use the `.flex-end` utility.

```html
<div class="flex flex-end blue border-bottom">
  <div class="flex-auto px2">
    <h1 class="m0">Hamburger</h1>
  </div>
  <div class="px2">Hot dog</div>
</div>
```

## Justify

To automatically fill the space between child elements, use `.flex-justify`.

```html
<div class="flex flex-justify">
  <div class="p1 border">Burger</div>
  <div class="p1 border">Burger</div>
  <div class="p1 py1 border">Burger</div>
</div>
```

## Responsive Utilities
To set display flex only at certain breakpoints and up,
use the breakpoint-prefixed versions of `.flex`.
All other utilities will only work at the set breakpoint.

```html
<div class="sm-flex flex-center mb2 blue">
  <div class="p1 border">
    <h2 class="m0">.sm-flex</h2>
  </div>
  <div class="flex-auto p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
<div class="md-flex flex-center mb2 blue">
  <div class="p1 border">
    <h2 class="m0">.md-flex</h2>
  </div>
  <div class="flex-auto p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
<div class="lg-flex flex-center mb2 blue">
  <div class="p1 border">
    <h2 class="m0">.lg-flex</h2>
  </div>
  <div class="flex-auto p1 border">Hamburger</div>
  <div class="p1 border">Hamburger</div>
</div>
```

## Child elements
To control the size and behavior of child elements, use these utilities.

### .flex-auto
To make an element grow or shrink as needed, use the `.flex-auto` utility.
```html
<div class="flex">
  <div class="px2 py1 border">Hamburger</div>
  <div class="px2 py1 border">Hamburger</div>
  <div class="flex-auto blue border"></div>
  <div class="px2 py1 border">Hamburger</div>
</div>
```

### .flex-grow
To make an element grow, but not shrink, use the `.flex-grow` utility.
```html
<div class="flex">
  <div class="px2 py1 border">Hamburger</div>
  <div class="px2 py1 border">Hamburger</div>
  <div class="flex-grow blue border"></div>
  <div class="px2 py1 border">Hamburger</div>
</div>
```

### .flex-none
To prevent an element from growing or shrinking, use the `.flex-none` utility.
```html
<div class="flex">
  <div class="flex-auto px2 py1 border">Hamburger</div>
  <div class="flex-auto px2 py1 border">Hamburger</div>
  <div class="flex-none px2 py1 border">Hamburger</div>
</div>
```

## Ordering
To change the order of child elements, use the `.flex-first` and `.flex-last` utilities.

### .flex-first
```html
<div class="flex">
  <div class="px2 py1 border">Hamburger</div>
  <div class="flex-first px2 py1 border">First Hamburger</div>
  <div class="px2 py1 border">Hamburger</div>
</div>
```

### .flex-last
```html
<div class="flex">
  <div class="px2 py1 border">Hamburger</div>
  <div class="flex-last px2 py1 border">Last Hamburger</div>
  <div class="px2 py1 border">Hamburger</div>
</div>
```

## Parent Element Utilities

```css
.flex          { display: flex }
.flex-column   { flex-direction: column }
.flex-wrap     { flex-wrap: wrap }
.flex-center   { align-items: center }
.flex-baseline { align-items: baseline }
.flex-stretch  { align-items: stretch }
.flex-start    { align-items: flex-start }
.flex-end      { align-items: flex-end }
```

## Child Element Utilities

```css
.flex-first { order: -1 }
.flex-last  { order: 1024 }
.flex-auto  { flex: 1 1 auto }
.flex-grow  { flex: 1 0 auto }
.flex-none  { flex: none }
```

redpajama_set_name: RedPajamaGithub


text:
package message

import (
	"reflect"
	"testing"
)

// Used for testing
type MockScreen struct {
	buffer []byte
}

func (s *MockScreen) Write(data []byte) (n int, err error) {
	s.buffer = append(s.buffer, data...)
	return len(data), nil
}

func (s *MockScreen) Read(p *[]byte) (n int, err error) {
	*p = s.buffer
	s.buffer = []byte{}
	return len(*p), nil
}

func TestScreen(t *testing.T) {
	var actual, expected []byte

	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Got: %v; Expected: %v", actual, expected)
	}

	actual = []byte("foo")
	expected = []byte("foo")
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Got: %v; Expected: %v", actual, expected)
	}

	s := &MockScreen{}

	expected = nil
	s.Read(&actual)
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Got: %v; Expected: %v", actual, expected)
	}

	expected = []byte("hello, world")
	s.Write(expected)
	s.Read(&actual)
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Got: %v; Expected: %v", actual, expected)
	}
}


text:
 jQuery(document).ready(function($){

 	$(".carousel").carousel({
        interval: 5000 //changes the speed
	});

	$('.nm_widget_box ul').addClass('list-group');
	$('.nm_widget_box ul li').addClass('list-group-item');
	$('.nm_widget_box table').addClass('table');
 });


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/chrome_render_frame_observer.h"

#include "chrome/common/chrome_render_frame.mojom.h"
#include "testing/gtest/include/gtest/gtest.h"

class ChromeRenderFrameObserverTest : public testing::Test {
 public:
  bool NeedsDownscale(const gfx::Size& original_image_size,
                      int32_t requested_image_min_area_pixels,
                      const gfx::Size& requested_image_max_size) {
    return ChromeRenderFrameObserver::NeedsDownscale(
        original_image_size, requested_image_min_area_pixels,
        requested_image_max_size);
  }

  bool NeedsEncodeImage(const std::string& image_extension,
                        chrome::mojom::ImageFormat image_format) {
    return ChromeRenderFrameObserver::NeedsEncodeImage(image_extension,
                                                       image_format);
  }
};

TEST_F(ChromeRenderFrameObserverTest,
       NeedsDownscale_RequestLargeThanOriginalReturnFalse) {
  EXPECT_FALSE(
      NeedsDownscale(/* original_image_size */ gfx::Size(10, 10),
                     /* requested_image_min_area_pixels */ 200,
                     /* requested_image_max_size */ gfx::Size(20, 20)));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsDownscale_SameSizeReturnFalse) {
  EXPECT_FALSE(
      NeedsDownscale(/* original_image_size */ gfx::Size(10, 10),
                     /* requested_image_min_area_pixels */ 100,
                     /* requested_image_max_size */ gfx::Size(10, 10)));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsDownscale_OnlyWidthShortReturnTrue) {
  EXPECT_TRUE(NeedsDownscale(/* original_image_size */ gfx::Size(10, 10),
                             /* requested_image_min_area_pixels */ 100,
                             /* requested_image_max_size */ gfx::Size(9, 10)));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsDownscale_OnlyAreaSmallReturnFalse) {
  EXPECT_FALSE(
      NeedsDownscale(/* original_image_size */ gfx::Size(10, 10),
                     /* requested_image_min_area_pixels */ 20,
                     /* requested_image_max_size */ gfx::Size(20, 20)));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsEncodeImage_JpegFormat) {
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".png",
                       /* image_format */ chrome::mojom::ImageFormat::JPEG));
  EXPECT_FALSE(
      NeedsEncodeImage(/* image_extension */ ".jpg",
                       /* image_format */ chrome::mojom::ImageFormat::JPEG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".gif",
                       /* image_format */ chrome::mojom::ImageFormat::JPEG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".bmp",
                       /* image_format */ chrome::mojom::ImageFormat::JPEG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".webp",
                       /* image_format */ chrome::mojom::ImageFormat::JPEG));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsEncodeImage_PngFormat) {
  EXPECT_FALSE(
      NeedsEncodeImage(/* image_extension */ ".png",
                       /* image_format */ chrome::mojom::ImageFormat::PNG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".jpg",
                       /* image_format */ chrome::mojom::ImageFormat::PNG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".gif",
                       /* image_format */ chrome::mojom::ImageFormat::PNG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".bmp",
                       /* image_format */ chrome::mojom::ImageFormat::PNG));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".webp",
                       /* image_format */ chrome::mojom::ImageFormat::PNG));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsEncodeImage_WebpFormat) {
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".png",
                       /* image_format */ chrome::mojom::ImageFormat::WEBP));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".jpg",
                       /* image_format */ chrome::mojom::ImageFormat::WEBP));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".gif",
                       /* image_format */ chrome::mojom::ImageFormat::WEBP));
  EXPECT_TRUE(
      NeedsEncodeImage(/* image_extension */ ".bmp",
                       /* image_format */ chrome::mojom::ImageFormat::WEBP));
  EXPECT_FALSE(
      NeedsEncodeImage(/* image_extension */ ".webp",
                       /* image_format */ chrome::mojom::ImageFormat::WEBP));
}

TEST_F(ChromeRenderFrameObserverTest, NeedsEncodeImage_OriginalFormat) {
  EXPECT_FALSE(NeedsEncodeImage(
      /* image_extension */ ".png",
      /* image_format */ chrome::mojom::ImageFormat::ORIGINAL));
  EXPECT_FALSE(NeedsEncodeImage(
      /* image_extension */ ".jpg",
      /* image_format */ chrome::mojom::ImageFormat::ORIGINAL));
  EXPECT_FALSE(NeedsEncodeImage(
      /* image_extension */ ".gif",
      /* image_format */ chrome::mojom::ImageFormat::ORIGINAL));
  EXPECT_TRUE(NeedsEncodeImage(
      /* image_extension */ ".bmp",
      /* image_format */ chrome::mojom::ImageFormat::ORIGINAL));
  EXPECT_TRUE(NeedsEncodeImage(
      /* image_extension */ ".webp",
      /* image_format */ chrome::mojom::ImageFormat::ORIGINAL));
}


text:
const path = require('path')
const process = require('process')
const should = require('should/as-function')
const sinon = require('sinon')
const options = require('../../src/cli/options.js')
const fixtures = require('../fixtures.js')

const BASE_ARGS = ['--input', 'photos', '--output', 'website']
const ospath = fixtures.ospath

describe('options', function () {
  before(() => {
    // all other modules use debug() which is already captured during tests
    // but options are parsed before log management so they use console.error
    sinon.stub(console, 'error')
  })

  after(() => {
    console.error.restore()
  })

  describe('parsing', () => {
    it('parses a single basic option', () => {
      const opts = options.get(BASE_ARGS)
      should(opts.input.endsWith('photos')).eql(true)
    })
    it('options with dashes are converted to camel case', () => {
      const opts = options.get(BASE_ARGS.concat(['--theme-path', 'foobar']))
      should(opts['theme-path']).eql(undefined)
      should(opts.themePath).eql('foobar')
    })
    it('can use --no to reverse a boolean', () => {
      const opts = options.get(BASE_ARGS.concat(['--no-usage-stats']))
      should(opts.usageStats).eql(false)
    })
    it('is case-sensitive for booleans', () => {
      const opts1 = options.get(BASE_ARGS.concat(['--include-videos', 'false']))
      should(opts1.includeVideos).eql(false)
      const opts2 = options.get(BASE_ARGS.concat(['--include-videos', 'FALSE']))
      should(opts2.includeVideos).eql(true)
    })
  })
  describe('paths', () => {
    it('--input is converted to an absolute path', () => {
      const opts = options.get(BASE_ARGS)
      should(opts.input).eql(path.join(process.cwd(), 'photos'))
    })
    it('--output is converted to an absolute path', () => {
      const opts = options.get(BASE_ARGS)
      should(opts.output).eql(path.join(process.cwd(), 'website'))
    })
  })
  describe('--albums-from', () => {
    it('can be specified once', () => {
      const args = BASE_ARGS.concat(['--albums-from', '%path'])
      const opts = options.get(args)
      should(opts.albumsFrom).eql(['%path'])
    })
    it('can be specified multiple times', () => {
      const args = BASE_ARGS.concat([
        '--albums-from', '%path',
        '--albums-from', '%keywords'
      ])
      const opts = options.get(args)
      should(opts.albumsFrom).eql(['%path', '%keywords'])
    })
  })
  describe('--sort-albums-direction', () => {
    it('can be specified with multiple arguments', () => {
      const args = BASE_ARGS.concat([
        '--sort-albums-direction', 'asc',
        '--sort-albums-direction', 'desc'
      ])
      const opts = options.get(args)
      should(opts.sortAlbumsDirection).eql(['asc', 'desc'])
    })
    it('can be specified multiple times  with a comma', () => {
      const args = BASE_ARGS.concat([
        '--sort-albums-direction', 'asc,desc'
      ])
      const opts = options.get(args)
      should(opts.sortAlbumsDirection).eql(['asc', 'desc'])
    })
  })
  describe('--gm-args', () => {
    it('is optional', () => {
      const opts = options.get(BASE_ARGS)
      should(opts.gmArgs).undefined()
    })
    it('prefixes with the required dash', () => {
      // we don't use the dash on the command line to avoid ambiguity
      // i.e. so the parser doesn't think "-modulate" is a thumbsup argument
      const args = BASE_ARGS.concat(['--gm-args', 'modulate 120'])
      const opts = options.get(args)
      should(opts.gmArgs).eql(['-modulate 120'])
    })
    it('can be specified multiple times', () => {
      const args = BASE_ARGS.concat([
        '--gm-args', 'equalize',
        '--gm-args', 'modulate 120'
      ])
      const opts = options.get(args)
      should(opts.gmArgs).eql(['-equalize', '-modulate 120'])
    })
  })
  describe('misc', () => {
    describe('database file path', () => {
      it('defaults to the output folder', () => {
        const opts = options.get(BASE_ARGS)
        should(opts.databaseFile).eql(path.resolve('website/thumbsup.db'))
      })
      it('can overridde with a relative url', () => {
        const args = BASE_ARGS.concat(['--database-file', 'album.db'])
        const opts = options.get(args)
        should(opts.databaseFile).eql(path.join(process.cwd(), 'album.db'))
      })
      itLinux('can be overridden with an absolute url (Linux)', () => {
        const args = BASE_ARGS.concat(['--database-file', '/media/album.db'])
        const opts = options.get(args)
        should(opts.databaseFile).eql('/media/album.db')
      })
      itWindows('can be overridden with an absolute url (Windows)', () => {
        const args = BASE_ARGS.concat(['--database-file', 'C:\\media\\album.db'])
        const opts = options.get(args)
        should(opts.databaseFile).eql('C:\\media\\album.db')
      })
    })
    describe('log file path', () => {
      it('defaults to the output folder', () => {
        const opts = options.get(BASE_ARGS)
        should(opts.logFile).eql(path.resolve('website/thumbsup.log'))
      })
      it('is written next to the database file if specified', () => {
        const args = BASE_ARGS.concat(['--database-file', 'album.db'])
        const opts = options.get(args)
        should(opts.logFile).eql(path.join(process.cwd(), 'album.log'))
      })
      it('can be specified explicitely', () => {
        const args = BASE_ARGS.concat(['--log-file', 'custom.log'])
        const opts = options.get(args)
        should(opts.logFile).eql(path.join(process.cwd(), 'custom.log'))
      })
    })
  })
  describe('deprecated', () => {
    it('--original-photos false', () => {
      const args = BASE_ARGS.concat(['--original-photos false'])
      const opts = options.get(args)
      should(opts.photoDownload).eql('resize')
    })
    it('--original-photos true', () => {
      const args = BASE_ARGS.concat(['--original-photos'])
      const opts = options.get(args)
      should(opts.photoDownload).eql('copy')
    })
    it('--original-videos false', () => {
      const args = BASE_ARGS.concat(['--original-videos false'])
      const opts = options.get(args)
      should(opts.videoDownload).eql('resize')
    })
    it('--original-videos true', () => {
      const args = BASE_ARGS.concat(['--original-videos'])
      const opts = options.get(args)
      should(opts.videoDownload).eql('copy')
    })
    it('--download-photos copy', () => {
      const args = BASE_ARGS.concat(['--download-photos', 'copy'])
      const opts = options.get(args)
      should(opts.photoDownload).eql('copy')
    })
    it('--download-videos copy', () => {
      const args = BASE_ARGS.concat(['--download-videos', 'copy'])
      const opts = options.get(args)
      should(opts.videoDownload).eql('copy')
    })
    it('--download-photos large', () => {
      const args = BASE_ARGS.concat(['--download-photos', 'large'])
      const opts = options.get(args)
      should(opts.photoDownload).eql('resize')
    })
    it('--download-videos large', () => {
      const args = BASE_ARGS.concat(['--download-videos', 'large'])
      const opts = options.get(args)
      should(opts.videoDownload).eql('resize')
    })
    it('--download-link-prefix url', () => {
      const args = BASE_ARGS.concat(['--download-link-prefix', 'url'])
      const opts = options.get(args)
      should(opts.linkPrefix).eql('url')
    })
    it('--albums-from folders', () => {
      const args = BASE_ARGS.concat(['--albums-from', 'folders'])
      const opts = options.get(args)
      should(opts.albumsFrom).eql(['%path'])
    })
    it('--albums-from folders (when several patterns)', () => {
      const args = BASE_ARGS.concat([
        '--albums-from', 'folders',
        '--albums-from', '%keywords'
      ])
      const opts = options.get(args)
      should(opts.albumsFrom).eql(['%path', '%keywords'])
    })
    it('--albums-from date', () => {
      const args = BASE_ARGS.concat([
        '--albums-from', 'date',
        '--albums-date-format', 'YYYY MMM'
      ])
      const opts = options.get(args)
      should(opts.albumsFrom).eql(['{YYYY MMM}'])
    })
    it('--css', () => {
      const args = BASE_ARGS.concat([
        '--css', 'path/to/custom.css'
      ])
      const opts = options.get(args)
      should(opts.themeStyle).eql(ospath('path/to/custom.css'))
    })
  })
})


text:
---
title: Singleton
localeTitle: Semifallo
---
El singleton es un patrón de diseño que restringe la creación de instancias de una clase a un objeto. Es útil cuando quiere dar a un solo objeto la capacidad de coordinar acciones en su aplicación.

## Singleton en Android

Singleton es un patrón de diseño utilizado a menudo en Android. Es fácilmente mal utilizado y, por lo tanto, puede hacer que la aplicación sea difícil de mantener. Es útil en Android porque viven a través de fragmentos, actividades y rotaciones.

*   Singletons se utilizan a menudo en Android para almacenar datos temporales
*   Permiten que la aplicación tenga un propietario de los datos y proporciona una manera fácil de pasar datos entre clases de controlador.
*   Los Singletons se destruyen cuando Android elimina tu aplicación de la memoria.
*   Singletons puede dificultar la prueba unitaria de su aplicación

```java
public class DataStore {
  private static DataStore sDataStore;
  private List<Data> mData;

  public static DataStore get(Context context) {
    if (sDataStore == null) {
      sDataStore = new DataStore(context);
    }
    return sDataStore;
  }

  // Make constructor private to prevent other classes from creating a DataStore instance
  private DataStore(Context context) {
    mData = new ArrayList<>();
  }

  // The only way for other classes to get data from DataStore
  public List<Data> getData() {
    return mData;
  }
 }
```

## Singleton en PHP

> Se utiliza un constructor privado para evitar la creación directa de objetos de la clase. La única forma de crear una instancia de la clase es mediante el uso de un método estático que crea el objeto solo si ya no se creó.

```php
Class Singleton {

  // Hold the class instance
  private static $instance = null;

  /**
  * The constructor is private
  * it is ensure the class can be initialized only from itself
  */
  private function __construct(){}

  /**
  * Return the singleton instance of this class
  *
  * @return Singleton
  */
  public static function getInstance()
  {
    if (self::$instance == null)
    {
      self::$instance = new Singleton();
    }

    return self::$instance;
  }

 }

 $obj1 = Singleton::getInstance();
 $obj2 = Singleton::getInstance();
```

## Singleton en C

La versión más elegante, simple y de alto rendimiento del patrón usando [System.Lazy \\](http://msdn.microsoft.com/en-us/library/dd642331.aspx) escriba desde .NET 4.0 o superior.

```csharp
public sealed class Singleton
 {
    private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
 }
```

## Singleton en Python3

Podemos usar metaclase para implementar Singleton en Python3.

```python
class Singleton(type):
    # Mapping from a class to its singleton instance
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in Singleton._instances:
            Singleton._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)

        return Singleton._instances[cls]

 class MyClass(metaclass=Singleton):
    pass
```

### Pruebas

```python
obj_0 = MyClass()
 obj_1 = MyClass()

 In [2]: obj_0
 Out[2]: <__main__.MyClass at 0x111130da0>

 In [3]: obj_1
 Out[3]: <__main__.MyClass at 0x111130da0>
```

## Singleton en iOS

```Swift4
class Singleton {
  static let sharedInstance = Singleton()

    init() {
        print("Singleton has been initialized")
    }

    //write your functions here
    func sampleFunction() {
    }
 }

 //Uses
 Singleton.sharedInstance.sampleFunction()
```

Este código simple es todo lo que hay para implementar un patrón de diseño de singleton en iOS usando Swift. Ponemos `static` porque es una propiedad de tipo, y su funcionalidad es crear solo una instancia de un objeto e impide que sus métodos se sobrescriban. El uso de `let` garantizará que el valor de sharedInstance no cambie.

Es importante tener en cuenta que las propiedades y los métodos `static` se inician de forma perezosa por defecto, lo que significa que no se creará una instancia hasta que se llame, por lo tanto, proporciona cierta optimización.

## Más información

Para más información, visite los siguientes enlaces:

*   [MSDN: Implementando Singleton en C #](https://msdn.microsoft.com/en-us/library/ff650316.aspx)
*   [C # en profundidad Implementando el patrón Singleton en C #](http://csharpindepth.com/Articles/General/Singleton.aspx)


text:
'use strict';

var gutil = require('gulp-util');
var iconfont = require('gulp-iconfont');
var iconfontCss = require('gulp-iconfont-css');

module.exports = function (gulp, opts) {
    return function () {
        gulp.src(opts.PROJECT_PATH.icons + '/**/*.svg')
            .pipe(iconfontCss({
                fontName: 'iconfont',
                appendUnicode: true,
                formats: ['ttf', 'eot', 'woff', 'svg'],
                fontPath: 'static/fonts/',
                path: opts.PROJECT_PATH.sass + '/libs/_iconfont.scss',
                targetPath: '../../../private/sass/layout/_iconography.scss'
            }))
            .pipe(iconfont({
                fontName: 'iconfont',
                normalize: true
            }))
            .on('glyphs', function (glyphs, options) {
                gutil.log.bind(glyphs, options);
            })
            .pipe(gulp.dest(opts.PROJECT_PATH.fonts));
    };
};


text:
<?php

require_once('ArchiveNews.php');

archiveWorldNews();

?>


text:
import logging
from flask import Flask
from flask_cors import CORS
from api.listings import ListingsView, CommentListView
from api.auth import register, login, whoami, logout

log = logging.getLogger(__name__)
app = Flask(__name__)

CORS(app)

app.add_url_rule('/login', view_func=login, methods=["POST"])
app.add_url_rule('/register', view_func=register, methods=["POST"])
app.add_url_rule('/whoami', view_func=whoami, methods=["GET"])
app.add_url_rule('/logout', view_func=logout, methods=["POST"])
app.add_url_rule('/listings', view_func=ListingsView.as_view(name="listings"))
app.add_url_rule('/listings/<listing_id>/comments', view_func=CommentListView.as_view(name="comments"))

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500

app.run()


text:
#ifndef _LUXCORE_FOR_BLENER_H
#define	_LUXCORE_FOR_BLENER_H

namespace luxcore {
namespace blender {

extern void ConvertFilmChannelOutput_3xFloat_To_4xUChar(const u_int width,
		const u_int height,	boost::python::object &objSrc, boost::python::object &objDst, const bool normalize);
extern boost::python::list ConvertFilmChannelOutput_3xFloat_To_3xFloatList(const u_int width,
		const u_int height,	boost::python::object &objSrc);
extern boost::python::list ConvertFilmChannelOutput_1xFloat_To_4xFloatList(const u_int width,
		const u_int height, boost::python::object &objSrc, const bool normalize);
extern boost::python::list ConvertFilmChannelOutput_2xFloat_To_4xFloatList(const u_int width,
		const u_int height,	boost::python::object &objSrc, const bool normalize);
extern boost::python::list ConvertFilmChannelOutput_3xFloat_To_4xFloatList(const u_int width,
		const u_int height, boost::python::object &objSrc, const bool normalize);

extern boost::python::list Scene_DefineBlenderMesh(luxcore::Scene *scene, const std::string &name,
		const size_t blenderFaceCount, const size_t blenderFacesPtr,
		const size_t blenderVertCount, const size_t blenderVerticesPtr,
		const size_t blenderUVsPtr, const size_t blenderColsPtr);
}
}

#endif


text:
class NavigationDemosController < ApplicationController
  def sample_nav_bar

  end
  def override_nav_bar

  end
  def routed_nav_bar
    @note = Note.last || Note.create!(:name => "yoo #{rand(100)}", :data => "wee #{rand(200)}")
  end

end


text:
<?php
namespace App\TestBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use App\TestBundle\Entity\AuthUser;
use App\TestBundle\Form\Type\AuthUserType;
use App\TestBundle\Form\Data\AuthUserFormData;
use App\TestBundle\Lib\AuthenticationMng;
use Symfony\Component\HttpFoundation\Response;

class UserController  extends Controller
{

    public function listAction()
    {
//        $users = $this->getDoctrine()->getRepository('AppTestBundle:AuthUser')->findAll();
        $em = $this->get('doctrine.orm.entity_manager');
        $dql = "SELECT a FROM AppTestBundle:AuthUser a";
        $query = $em->createQuery($dql);

        //pagerオブジェクト取得
        $paginator = $this->get('knp_paginator');
        $users = $paginator->paginate(
            $query,
            $this->get('request')->query->get('page', 1)/*page number*/,
            3/*limit per page*/
        );

        return $this->render('AppTestBundle:User:list.html.twig', array('users' => $users));
    }

    public function createAction(Request $request)
    {
        //
        $authuser = new AuthUser();

        //formクラスとformdataクラスを使用するパターン
//        $authuser_form = new AuthUserFormData();
        $authuser_form = $this->get('form.data.auth_user_form_data');
        $form = $this->createForm(new AuthUserType(), $authuser_form);

/*
        //formクラスを使用するパターン
        $form = $this->createForm(new AuthUserType(), $authuser);
*/
/*
        //createFormBuilderを使用するパターン
        $form = $this->createFormBuilder($authuser)
                ->add('username', 'text')
                ->add('password', 'password')
                ->add('authrole', 'entity', array(
                    'class' => 'App\TestBundle\Entity\AuthRole',
                    'property' => 'name',
                ))
                ->getForm();
*/

        //
        if ($request->getMethod() === 'POST')
        {
            $form->bindRequest($request);
            if($form->isValid())
            {
                //formデータ取得
                $formdata = $form->getData();

                //保存
                $em = $this->get('doctrine')->getEntityManager();
                $auth_mng = new AuthenticationMng($em);
                $auth_mng->insertUserForm($formdata);

/*
                //
                $authuser->setUsername($formdata->getUsername());
                $authuser->setPassword($formdata->getPassword());
                $authuser->setSalt('');
                $authuser->setAuthRole($formdata->getAuthRole());

                //
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($authuser);
                $em->flush();
*/
            }
        }

        return $this->render('AppTestBundle:User:create.html.twig', array('form' => $form->createView()));
    }

    public function checkUserName(Request $request)
    {
        $ret = array('result' => false, 'data' => array());
        //
        if ($request->getMethod() === 'POST' && $request->get('username') != null)
        {
            $authmng = $this->get('asauth.mng');
            if($authmng->isUsernameUnique($request->get('username')))
            {
                $ret['result'] = true;
                $ret['data']['isunique'] = true;
            }else
            {
                $ret['result'] = true;
                $ret['data']['isunique'] = false;
            }
        }else
        {
            $ret['result'] = false;
        }

        return $ret;
    }

    public function checkUserNameAction(Request $request)
    {
        $ret = $this->checkUserName($request);
        $return=json_encode($ret);
        return new Response($return, 200, array('Content-Type' => 'application/json; charset=utf-8'));
    }

    public function checkUserNameAjaxAction(Request $request)
    {
        $ret = $this->checkUserName($request);
        if(!$ret['result'])
        {
            return new Response();
        }
        return $this->render('AppTestBundle:User:ajax_check_username.html.twig', array('result' => $ret));
    }

}

?>


text:
require_relative '../../shared/rational/to_r'

describe "Rational#to_r" do
  it_behaves_like :rational_to_r, :to_r

  it "raises TypeError trying to convert BasicObject" do
    obj = BasicObject.new
    -> { Rational(obj) }.should raise_error(TypeError)
  end

  it "works when a BasicObject has to_r" do
    obj = BasicObject.new; def obj.to_r; 1 / 2.to_r end
    Rational(obj).should == Rational('1/2')
  end

  it "fails when a BasicObject's to_r does not return a Rational" do
    obj = BasicObject.new; def obj.to_r; 1 end
    -> { Rational(obj) }.should raise_error(TypeError)
  end
end


text:
import {
  TestComponentBuilder,
  describe,
  expect,
  injectAsync,
  it,
  beforeEachProviders
} from 'angular2/testing';
import {Location, Router, RouteRegistry, ROUTER_PRIMARY_COMPONENT} from 'angular2/router';
import {SpyLocation} from 'angular2/src/mock/location_mock';
import {RootRouter} from 'angular2/src/router/router';

import {Component, provide} from 'angular2/core';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';
import {ChartPage} from './chart';

export function main() {
  beforeEachProviders(() => [
    RouteRegistry,
    provide(Location, {useClass: SpyLocation}),
    provide(ROUTER_PRIMARY_COMPONENT, {useValue: ChartPage}),
    provide(Router, {useClass: RootRouter})
  ]);

  describe('chart component', () => {
    it('should work',
      injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb.createAsync(TestComponent)
          .then((rootTC) => {
            let chartDOMEl = rootTC.debugElement.children[0].nativeElement;

            expect(DOM.querySelectorAll(chartDOMEl, 'h1')[0].textContent).toEqual('Charts');
          });
      }));
  });
}

@Component({
  selector: 'test-cmp',
  directives: [ChartPage],
  template: '<chart-page></chart-page>'
})
class TestComponent {}


text:
import _ from 'lodash';

const reports = [];

function sendReport(requestBody, config, ipAddress) {
  return new Promise(resolve => {
    const data = _.assign({}, requestBody, {
      _meta: {
        config,
        ipAddress
      }
    });
    // use a timeout to emulate some amount of network latency for the report send
    // especially useful for class.test.js - proper timeout reporting
    setTimeout(() => {
      reports.push(data);
      resolve({
        status: 200
      });
    }, 10);
  });
}

export { reports, sendReport };


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

package com.google.enterprise.gsafeed;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;

import org.junit.Test;
import org.xmlunit.builder.DiffBuilder;
import org.xmlunit.diff.Diff;

/**
 * Test Metadata.
 */
public class MetadataTest {
  @Test
  public void testMetadata() throws Exception {
    String expected =
        "<metadata overwrite-acls='true'></metadata>";
    Metadata metadata = new Metadata()
        .setOverwriteAcls(true);
    Diff diff = DiffBuilder
        .compare(expected)
        .withTest(metadata)
        .checkForSimilar()
        .build();
    assertFalse(diff.toString(), diff.hasDifferences());
  }

  @Test
  public void testGetOverwriteAclsTrue() throws Exception {
    Metadata metadata = unmarshal("<metadata overwrite-acls='true'/>");
    assertEquals(true, metadata.getOverwriteAcls());
  }

  @Test
  public void testGetOverwriteAclsFalse() throws Exception {
    Metadata metadata = unmarshal("<metadata overwrite-acls='false'/>");
    assertEquals(false, metadata.getOverwriteAcls());
  }

  @Test
  public void testGetOverwriteAclsUnset() throws Exception {
    Metadata metadata = unmarshal("<metadata/>");
    assertEquals(null, metadata.getOverwriteAcls());
  }

  @Test
  public void setOverwriteAclsTrue() {
    String expected = "<metadata overwrite-acls='true'/>";
    Metadata metadata = new Metadata().setOverwriteAcls(true);
    assertNoDiffs(expected, metadata);
  }

  @Test
  public void setOverwriteAclsFalse() {
    String expected = "<metadata overwrite-acls='false'/>";
    Metadata metadata = new Metadata().setOverwriteAcls(false);
    assertNoDiffs(expected, metadata);
  }

  @Test
  public void setOverwriteAclsNull() {
    String expected = "<metadata/>";
    Metadata metadata1 = new Metadata().setOverwriteAcls(null);
    assertNoDiffs(expected, metadata1);
  }

  private void assertNoDiffs(String expected, Object actual) {
    Diff diff = DiffBuilder.compare(expected).withTest(actual)
        .checkForSimilar().build();
    assertFalse(diff.toString(), diff.hasDifferences());
  }

  private Metadata unmarshal(String value) throws Exception {
    return (Metadata) JaxbUtil.unmarshalGsafeedElement(value);
  }
}


text:
<?php

namespace FivePercent\Component\Converter\Property;

/**
 * All property converters should be implemented of this interface
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
interface PropertyConverterInterface
{
    /**
     * Is supported
     *
     * @param \ReflectionProperty $property
     */
    public function isSupported(\ReflectionProperty $property);

    /**
     * Convert value
     *
     * @param \ReflectionProperty $property
     * @param mixed               $value
     *
     * @return mixed
     */
    public function convert(\ReflectionProperty $property, $value);
}


text:
<?php

namespace History\Console\Commands;

use Illuminate\Contracts\Cache\Repository;
use Illuminate\Filesystem\Filesystem;
use Interop\Container\ContainerInterface;
use Symfony\Component\Console\Output\OutputInterface;

class CacheClearCommand extends AbstractCommand
{
    /**
     * @var Repository
     */
    protected $repository;
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @param ContainerInterface $container
     * @param Repository         $repository
     */
    public function __construct(ContainerInterface $container, Repository $repository)
    {
        $this->repository = $repository;
        $this->container = $container;
    }

    /**
     * Run the command.
     *
     * @param bool            $all
     * @param OutputInterface $output
     */
    public function run($all, OutputInterface $output)
    {
        $this->wrapOutput($output);

        // Empty standard cache
        if ($all) {
            $this->repository->flush();
        } else {
            $this->repository->tags('php')->flush();
        }

        // Empty filesystem cache
        $files = new Filesystem();
        $cache = $this->container->get('paths.cache');
        foreach ($files->directories($cache) as $directory) {
            $files->deleteDirectory($directory);
        }

        $this->output->success('Cache emptied');
    }
}


text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2019)

#ifndef DUNE_GDT_TEST_BURGERS_BASE_HH
#define DUNE_GDT_TEST_BURGERS_BASE_HH

#include <cmath>

#include <dune/xt/common/float_cmp.hh>
#include <dune/xt/common/fvector.hh>
#include <dune/xt/common/memory.hh>
#include <dune/xt/functions/generic/function.hh>
#include <dune/xt/grid/gridprovider/cube.hh>

#include <dune/gdt/interpolations.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/test/instationary-eocstudies/hyperbolic-nonconforming.hh>

namespace Dune {
namespace GDT {

template <class G>
struct BurgersProblem
{
  static constexpr size_t d = G::dimension;
  static_assert(d == 1, "Not implemented yet!");
  //  using DomainType = XT::Common::FieldVector<double, d>;

  const XT::Functions::GenericFunction<1, d, 1> flux;
  const double T_end;

  BurgersProblem()
    : flux(
        2,
        [&](const auto& u, const auto& /*param*/) { return 0.5 * u * u; },
        "burgers",
        {},
        [&](const auto& u, const auto& /*param*/) { return u; })
    , T_end(1.)
  {}

  XT::Grid::GridProvider<G> make_initial_grid() const
  {
    return XT::Grid::make_cube_grid<G>(0., 1., 16u);
  }

  template <class Vector, class GV>
  DiscreteFunction<Vector, GV> make_initial_values(const SpaceInterface<GV, 1>& space) const
  {
    // TODO: Use generic interpolate once implemented?
    return default_interpolation<Vector>(
        3,
        [&](const auto& xx, const auto& /*mu*/) {
          return std::exp(-std::pow(xx[0] - 0.33, 2) / (2 * std::pow(0.075, 2)));
        },
        space);
  }
}; // struct BurgersProblem

template <class G>
class BurgersTest
  : XT::Common::ConstStorageProvider<BurgersProblem<G>>
  , public GDT::Test::InstationaryNonconformingHyperbolicEocStudy<G, 1>
{
  using Problem = XT::Common::ConstStorageProvider<BurgersProblem<G>>;
  using BaseType = GDT::Test::InstationaryNonconformingHyperbolicEocStudy<G, 1>;

protected:
  using BaseType::d;
  using typename BaseType::BS;
  using typename BaseType::DF;
  using typename BaseType::F;
  using typename BaseType::GP;
  using typename BaseType::S;
  using typename BaseType::V;

public:
  BurgersTest(const std::string timestepping)
    : Problem(new BurgersProblem<G>())
    , BaseType(Problem::access().T_end,
               timestepping,
               [&](const auto& solution, const auto& prefix) {
                 const auto end_time =
                     std::min(this->T_end_, this->time_points_from_vector_array(solution.dof_vectors()).back());
                 for (size_t ii = 0; ii < this->visualization_steps_; ++ii) {
                   const double time = ii * (end_time / this->visualization_steps_);
                   solution.evaluate(time).visualize(XT::Common::Test::get_unique_test_name() + "__" + prefix
                                                     + "_solution_" + XT::Common::to_string(ii));
                 }
               })
    , visualization_steps_(0)
  {}

protected:
  const F& flux() const override
  {
    return Problem::access().flux;
  }

  DF make_initial_values(const S& space) override
  {
    return Problem::access().template make_initial_values<V>(space);
  }

  GP make_initial_grid() override
  {
    return Problem::access().make_initial_grid();
  }

protected:
  size_t visualization_steps_;
}; // class BurgersTest

template <class G>
class BurgersExplicitTest : public BurgersTest<G>
{
protected:
  using BaseType = BurgersTest<G>;
  using typename BaseType::BS;
  using typename BaseType::GP;
  using typename BaseType::S;
  using typename BaseType::V;

  BurgersExplicitTest()
    : BaseType("explicit/fixed")
  {
    this->num_refinements_ = 1;
    this->num_additional_refinements_for_reference_ = 2;
  }

  void compute_reference_solution() override
  {
    auto& self = *this;
    auto st = self.space_type_;
    self.space_type_ = "fv";
    BaseType::compute_reference_solution();
    self.space_type_ = st;
  }

  XT::LA::ListVectorArray<V> solve(const S& space, const double T_end) override
  {
    auto& self = *this;
    const auto fv_dt = self.estimate_fixed_explicit_fv_dt(space);
    // since estimate_fixed_explicit_dt_to_T_end might be costly, we allow to use a predefined dt here to speed up tests
    auto dt = DXTC_TEST_CONFIG_GET("setup.use_fixed_dt", -1.);
    if (dt < 0)
      dt = self.estimate_fixed_explicit_dt_to_T_end(
          space,
          DXTC_TEST_CONFIG_GET("setup.estimate_fixed_explicit_dt.min_dt", 1e-4),
          T_end,
          DXTC_TEST_CONFIG_GET("setup.estimate_fixed_explicit_dt.max_overshoot", 1.25));
    self.current_data_["quantity"]["dt"] = dt;
    self.current_data_["quantity"]["explicit_fv_dt"] = fv_dt;
    Timer timer;
    const auto u_0 = self.make_initial_values(space);
    const auto op = self.make_lhs_operator(space);
    /// TODO: investigate why the tested dt from above does not work!
    auto solution = GDT::Test::solve_instationary_system_explicit_euler(
        u_0, *op, T_end, DXTC_TEST_CONFIG_GET("setup.dt_factor", 0.99) * dt);
    self.current_data_["quantity"]["time to solution (s)"] = timer.elapsed();
    return solution;
  } // ... solve(...)
}; // class BurgersExplicitTest

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_TEST_BURGERS_BASE_HH


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Constant Field Values
</TITLE>

<META NAME="date" CONTENT="2013-10-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Constant Field Values

Contents

com.dtdsoftware.*

com.dtdsoftware.*

com.dtdsoftware.splunk.formatter.Formatter

public static final java.lang.String
META_HOST
"meta_host"

public static final java.lang.String
META_JVM_DESCRIPTION
"meta_description"

public static final java.lang.String
META_PROCESS_ID
"meta_processid"

      Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Timemap Synchronized with Google Earth</title>

    <link href="examples.css" type="text/css" rel="stylesheet"/>
    <link href="http://gmaps-utility-library-dev.googlecode.com/svn/trunk/extinfowindow/examples/css/simpleExampleWindow.css" type="text/css" rel="stylesheet"/>

Timemap Synchronized with Google Earth

    This example syncs a timemap with the Google Earth browser plugin. You have to do some timeout juggling in order to avoid a cyclical listener setup, but it seems to work reasonably well.


text:
"""

Creates a gridded seasonal plot

This module wraps the plot_gridded_seas.sh script found in git repository cwsl-ctools.

Part of the CWSLab VisTrails plugin.

Authors: Craig Heady, craig.heady@csiro.au
         Tim Bedin,   Tim.Bedin@csiro.au
         Tim Erwin,   Tim.Erwin@csiro.au

Copyright 2015 CSIRO

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

"""

import os

from vistrails.core.modules import vistrails_module
from vistrails.core.modules.basic_modules import String, List

from cwsl.configuration import configuration
from cwsl.core.process_unit import ProcessUnit
from cwsl.core.constraint import Constraint
from cwsl.core.pattern_generator import PatternGenerator

class PlotGriddedSeas(vistrails_module.Module):
    """
    Plots a gridded field(season).

    Required inputs:

    Other inputs:    infile (from dataset connector)
                     title (model name from dataset connector)

    Requires: python, cdat, cct, matplotlib, basemap

region's:
'AUS_PCCSP'
'PACIFIC'
'PACCSAP'
'VANUATU'
'AUSTRALIA'
'AUSTRALIA_NZ'
'AUSTRALIA_EXT'
'AUSTRALIA_EXT_NZ'
'SE_AUSTRALIA'
'QLD'
'SEQLD'
'BRISBANE'
'WORLD'
'WORLD360'
'STH_SULAWESI'
'MAKASSAR'
'INDONESIA'
'EAST_INDONESIA'
'NTB'
'ZOOM'
'AUREL_AND_LAWSON'
'MONSOONAL_NORTH'
'WET_NORTH'
'RANGELANDS'
'MURRAY_BASIN'
'EAST_COAST'
'SOUTHERN_SLOPES'
'S&SW_FLATLANDS'
'BBBASIN'
'INDIA'
'SOUTHASIA'
'australia_NRM-eval'
'australia_NRM-eval-psl'
    """

    # Define the module ports.
    _input_ports = [('in_dataset', 'csiro.au.cwsl:VtDataSet',
                     {'labels': str(['Input Dataset'])}),
                    ('variable', String, {"defaults": str([''])}),
                    ('plot_type', String, {"defaults": str(['pcolor'])}),
                    ('title', String, {"defaults": str([''])}),
                    ('region', String, {"defaults": str(['WORLD360'])}),
                    ('colormap', String, {"defaults": str([''])}),
                    ('ticks', String, {"defaults": str([''])}),
                    ('conv_units', String, {"defaults": str(['False'])}),
                   ]

    _output_ports = [('out_dataset', 'csiro.au.cwsl:VtDataSet',)]

    _execution_options = {'required_modules': ['cdo','python/2.7.5','python-cdat-lite/6.0rc2-py2.7.5',
                                               'cct/trunk','python/2.7.5-matplotlib',
                                               'python-basemap/1.0.7-py2.7']
                         }

    def __init__(self):

        super(PlotGriddedSeas, self).__init__()

        self.command = '${CWSL_CTOOLS}/visualisation/plot_gridded_seas.py'

        # Get the output pattern using the PatternGenerator object.
        # Gets the user infomation / authoritative path etc from the
        # user configuration.
        self.out_pattern = PatternGenerator('user', 'default').pattern

    def compute(self):

        # Required input
        in_dataset = self.getInputFromPort("in_dataset")

        variable = self.getInputFromPort("variable")
        #self.positional_args=[(variable_name, 0, 'raw')]

        plot_type = self.getInputFromPort("plot_type")
        #self.positional_args=[(plot_type, 1, 'raw')]

        title = self.getInputFromPort("title")
        #self.positional_args=[(title, 2, 'raw')]

        region = self.getInputFromPort("region")
        #self.positional_args=[(plot_type, 3, 'raw')]

        colormap = self.getInputFromPort("colormap")
        #self.positional_args=[(colormap, 4, 'raw')]

        ticks = self.getInputFromPort("ticks")
        #self.positional_args=[(plot_type, 5, 'raw')]

        conv_units = self.getInputFromPort("conv_units")
        #self.positional_args=[(conv_units, 6, 'raw')]

        cons_for_output = set([Constraint('suffix', ['png'])])

        run_opts = ''
        if variable:
            run_opts = run_opts + ' --variable %s' %variable
        if plot_type:
            run_opts = run_opts + ' --plot_type %s' %plot_type
        if title:
            run_opts = run_opts + ' --title %s' %title
        if region:
            run_opts = run_opts + ' --region %s' %region
        if colormap:
            run_opts = run_opts + ' --colourmap %s' %colormap
        if ticks:
            run_opts = run_opts + " --ticks '%s'" %ticks
        if conv_units:
            run_opts = run_opts + " --conv_units '%s'" %conv_units

        # Execute plotting process.
        this_process = ProcessUnit([in_dataset],
                                   self.out_pattern,
                                   self.command,
                                   cons_for_output,
                                   execution_options=self._execution_options,
                                   #positional_args=self.positional_args,
                                   kw_string=run_opts)
                                   #kw_string="--title '${model}_${experiment}'")

        try:
            process_output = this_process.execute(simulate=configuration.simulate_execution)
        except Exception as e:
            raise vistrails_module.ModuleError(self, repr(e))

        self.setResult('out_dataset', process_output)


text:
<?php
/*
 * This file is part of the BeSimpleSoapBundle.
 *
 * (c) Christian Kerl <christian-kerl@web.de>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace BeSimple\SoapBundle\ServiceDefinition\Dumper;

use BeSimple\SoapBundle\ServiceDefinition\ServiceDefinition;
use BeSimple\SoapBundle\ServiceDefinition\Loader\AnnotationComplexTypeLoader;
use BeSimple\SoapBundle\ServiceDefinition\Strategy\ComplexType;
use BeSimple\SoapBundle\Util\String;

use Zend\Soap\Exception;
use Zend\Soap\Wsdl as BaseWsdl;
use Zend\Soap\Wsdl\ComplexTypeStrategy\ComplexTypeStrategyInterface;
use Zend\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence;

class WsdlTypeStrategy implements ComplexTypeStrategyInterface
{
    /**
     * Context WSDL file
     *
     * @var \Zend\Soap\Wsdl|null
     */
    private $context;

    private $loader;
    private $definition;

    private $typeStrategy;
    private $arrayStrategy;

    public function __construct(AnnotationComplexTypeLoader $loader, ServiceDefinition $definition)
    {
        $this->loader     = $loader;
        $this->definition = $definition;
    }

    /**
     * Method accepts the current WSDL context file.
     *
     * @param \Zend\Soap\Wsdl $context
     */
    public function setContext(BaseWsdl $context)
    {
        $this->context = $context;

        return $this;
    }

    /**
     * Create a complex type based on a strategy
     *
     * @param  string $type
     *
     * @return string XSD type
     *
     * @throws \Zend\Soap\WsdlException
     */
    public function addComplexType($type)
    {
        if (!$this->context) {
            throw new \LogicException(sprintf('Cannot add complex type "%s", no context is set for this composite strategy.', $type));
        }

        $strategy = String::endsWith($type, '[]') ? $this->getArrayStrategy() : $this->getTypeStrategy();

        return $strategy->addComplexType($type);
    }

    private function getArrayStrategy()
    {
        if (!$this->arrayStrategy) {
            $this->arrayStrategy = new ArrayOfTypeSequence();
            $this->arrayStrategy->setContext($this->context);
        }

        return $this->arrayStrategy;
    }

    private function getTypeStrategy()
    {
        if (!$this->typeStrategy) {
            $this->typeStrategy = new ComplexType($this->loader, $this->definition);
            $this->typeStrategy->setContext($this->context);
        }

        return $this->typeStrategy;
    }
}


text:
package gov.va.isaac;

import gov.va.isaac.gui.App;
import gov.va.isaac.interfaces.RuntimeGlobalsI;
import gov.va.isaac.interfaces.utility.CommitListenerI;
import gov.va.isaac.interfaces.utility.ShutdownBroadcastListenerI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.naming.InvalidNameException;
import org.glassfish.hk2.api.IterableProvider;
import org.jvnet.hk2.annotations.Service;
import org.slf4j.LoggerFactory;

/**
 * {@link RuntimeGlobals}
 *
 * @author Dan Armbrust
 */
@Service
@Singleton
public class RuntimeGlobals implements RuntimeGlobalsI
{
	private ArrayList<ShutdownBroadcastListenerI> shutdownListeners_ = new ArrayList<>();
	@Inject private IterableProvider<CommitListenerI> commitListeners_;
	private AtomicInteger disableRequests = new AtomicInteger(0);

	private RuntimeGlobals()
	{
		//For HK2 to construct
	}

	/**
	 * Do not call this - only for internal use.
	 */
	public void shutdown()
	{
		for (ShutdownBroadcastListenerI s : shutdownListeners_)
		{
			if (s != null)
			{
				s.shutdown();
			}
		}
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#registerShutdownListener(gov.va.isaac.interfaces.utility.ShutdownBroadcastListenerI)
	 */
	@Override
	public void registerShutdownListener(ShutdownBroadcastListenerI listener)
	{
		//TODO this needs to use weak references - but would rather just get rid of the interface, and allow HK2 to manage.
		shutdownListeners_.add(listener);
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#getAllCommitListenerNames()
	 */
	@Override
	public List<String> getAllCommitListenerNames()
	{
		ArrayList<String> result = new ArrayList<>();
		for (CommitListenerI cl : commitListeners_)
		{
			result.add(cl.getListenerName());
		}
		return result;
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#disableCommitListener(java.lang.String)
	 */
	@Override
	public void disableCommitListener(String commitListenerName) throws InvalidNameException
	{
		CommitListenerI item = AppContext.getService(CommitListenerI.class, commitListenerName);
		if (item == null)
		{
			throw new InvalidNameException("Couldn't find a commit listener with the name '" + commitListenerName + "'");
		}
		else
		{
			item.disable();
		}
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#enableCommitListener(java.lang.String)
	 */
	@Override
	public void enableCommitListener(String commitListenerName) throws InvalidNameException
	{
		CommitListenerI item = AppContext.getService(CommitListenerI.class, commitListenerName);
		if (item == null)
		{
			throw new InvalidNameException("Couldn't find a commit listener with the name '" + commitListenerName + "'");
		}
		else
		{
			item.enable();
		}
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#enableAllCommitListeners()
	 */
	@Override
	public void enableAllCommitListeners()
	{
		if (disableRequests.get() < 1)
		{
			LoggerFactory.getLogger(this.getClass()).error("enableAll called when disable hasn't been called!  Ignoring.");
			return;
		}
		int disableRequestsActive = disableRequests.decrementAndGet();
		if (disableRequestsActive == 0)
		{
			for (CommitListenerI cl : commitListeners_)
			{
				cl.enable();
			}
		}
	}

	/**
	 * @see gov.va.isaac.interfaces.RuntimeGlobalsI#disableAllCommitListeners()
	 */
	@Override
	public void disableAllCommitListeners()
	{
		disableRequests.getAndIncrement();
		for (CommitListenerI cl : commitListeners_)
		{
			cl.disable();
		}
	}
}


text:
<?php

namespace SweetTooth\Bundle\BindingBundle\Command\Cron;

use SweetTooth\Bundle\BindingBundle\Entity\ContactBinding;

use Oro\Bundle\CronBundle\Command\CronCommandInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Oro\Bundle\ImapBundle\Sync\ImapEmailSynchronizer;
use Oro\Bundle\CronBundle\Command\Logger\OutputLogger;

class BindingSyncCommand extends ContainerAwareCommand implements CronCommandInterface
{
    /**
     * {@internaldoc}
     */
    public function getDefaultDefinition()
    {
        return '*/30 * * * *';
    }

    /**
     * {@internaldoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:cron:sweettooth:sync')
            ->setDescription('Sweet Tooth Contact and Order sync');
    }

    /**
     * {@internaldoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $synchronizer = $this->getContainer()->get('sweettooth_binding.binding_synchronizer');
        $synchronizer->sync();
    }
}


text:
#pragma once

#include <Core/RaCore.hpp>

#include <Core/Containers/VectorArray.hpp>

namespace Ra {
namespace Core {
namespace Animation {

struct SkinningRefData;
struct SkinningFrameData;

/**
 * \name Center-of-Rotation Skinning
 * Formula from: "Real-time Skeletal Skinning with Optimized Centers of Rotation"
 * 2016 - Le & Hodgins.
 */
/// \{

// clang-format off
/**
 * \brief Computes the per-vertex optimal center of rotations.
 *
 *
 * The optimal center of rotations are computed as:
 * \f$\mathbf{p}_i^* = \frac{\sum_{t}\varsigma(\mathbf{w}_i, \mathbf{w}_t)\mathcal{A}_t\mathbf{v}_t}
 *                          {\sum_{t}\varsigma(\mathbf{w}_i, \mathbf{w}_t)\mathcal{A}_t}\f$
 * , where \f$\mathbf{w}_i=\begin{bmatrix}\omega_{i0}&\omega_{i1}&\cdots&\omega_{in}\end{bmatrix}\f$
 * , \f$\mathbf{w}_t = \frac{1}{3}(\mathbf{w}_{t_0}+\mathbf{w}_{t_1}+\mathbf{w}_{t_2})\f$
 * and \f$\mathbf{v}_t = \frac{1}{3}(\mathbf{p}_{t_0}+\mathbf{p}_{t_1}+\mathbf{p}_{t_2})\f$
 * , \f$t_j\f$ being the \f$j\f$-th vertex of triangle \f$t\f$ and \f$\mathcal{A}_t\f$ its area.
 *
 * \note Parallelized loop inside (using openmp).
 */
// clang-format on
void RA_CORE_API computeCoR( SkinningRefData& dataInOut,
                             Scalar sigma         = 0.1_ra,
                             Scalar weightEpsilon = 0.1_ra );

// clang-format off
/**
 * \brief Applies Center-of-Rotation skinning to the current frame.
 *
 *
 * Center-of-Rotation skinning deforms the mesh geometry for frame \f$t\f$ as follows:
 * \f$\mathbf{p}_i^t = \sum_{s\in S} \omega_{is}\mathbf{M}_s\mathbf{p}_i^*
 *                   + \mathbf{R}(\mathbf{p}_i^0-\mathbf{p}_i^*)\f$
 * , where \f$\mathbf{R}\f$ is the rotation matrix given by the quaternion
 * \f$\mathbf{q} = \frac{\sum_{s\in S}^\oplus \omega_{is}\mathbf{q}_s}
 *                      {\|\sum_{s\in S}^\oplus \omega_{is}\mathbf{q}_s\|}\f$
 * and \f$\mathbf{p}_i^*\f$ is the Center-of-Rotation for vertex \f$\mathbf{p}_i\f$,
 * computed as:
 * \f$\mathbf{p}_i^* = \frac{\sum_{t}\varsigma(\mathbf{w}_i, \mathbf{w}_t)\mathcal{A}_t\mathbf{v}_t}
 *                          {\sum_{t}\varsigma(\mathbf{w}_i, \mathbf{w}_t)\mathcal{A}_t}\f$
 * , where \f$\mathbf{w}_i=\begin{bmatrix}\omega_{i0}&\omega_{i1}&\cdots&\omega_{in}\end{bmatrix}\f$
 * , \f$\mathbf{w}_t = \frac{1}{3}(\mathbf{w}_{t_0}+\mathbf{w}_{t_1}+\mathbf{w}_{t_2})\f$
 * and \f$\mathbf{v}_t = \frac{1}{3}(\mathbf{p}_{t_0}+\mathbf{p}_{t_1}+\mathbf{p}_{t_2})\f$
 * , \f$t_j\f$ being the \f$j\f$-th vertex of triangle \f$t\f$ and \f$\mathcal{A}_t\f$ its area.
 *
 * The skinning of the normal, tangent and bitangent vectors is approximated as:
 * \f$\mathbf{v}_i^t = \mathbf{R}\mathbf{v}_i^0\f$
 *
 *
 * \note Considers frameData is well sized.
 * \note Parallelized loop inside (using openmp).
 */
// clang-format on
void RA_CORE_API centerOfRotationSkinning( const SkinningRefData& refData,
                                           const Vector3Array& tangents,
                                           const Vector3Array& bitangents,
                                           SkinningFrameData& frameData );
/// \}

} // namespace Animation
} // namespace Core
} // namespace Ra


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interactivity;

namespace UB.Interactivity
{
    public class DragWindow :BehaviorBase
    {
        protected override void Attach()
        {
            AssociatedObject.PreviewMouseDown += AssociatedObject_PreviewMouseDown;
        }
        protected override void Cleanup()
        {
            AssociatedObject.PreviewMouseDown -= AssociatedObject_PreviewMouseDown;
        }
        void AssociatedObject_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Released)
                return;

            var window = AssociatedObject as Window;
            window.DragMove();

        }
    }
}