text:
package org.apache.nifi.controller.serialization;

import org.apache.nifi.connectable.Connectable;
import org.apache.nifi.connectable.Connection;
import org.apache.nifi.connectable.Port;
import org.apache.nifi.controller.AbstractComponentNode;
import org.apache.nifi.controller.ComponentNode;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.ParameterProviderNode;
import org.apache.nifi.controller.ProcessorNode;
import org.apache.nifi.controller.ReportingTaskNode;
import org.apache.nifi.controller.ScheduledState;
import org.apache.nifi.controller.UninheritableFlowException;
import org.apache.nifi.controller.flow.FlowManager;
import org.apache.nifi.controller.service.ControllerServiceNode;
import org.apache.nifi.controller.service.ControllerServiceProvider;
import org.apache.nifi.controller.service.ControllerServiceState;
import org.apache.nifi.flow.ComponentType;
import org.apache.nifi.flow.ConnectableComponent;
import org.apache.nifi.flow.ConnectableComponentType;
import org.apache.nifi.flow.VersionedComponent;
import org.apache.nifi.flow.VersionedConnection;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.groups.RemoteProcessGroup;
import org.apache.nifi.parameter.ParameterContext;
import org.apache.nifi.registry.flow.FlowRegistryClientNode;
import org.apache.nifi.registry.flow.diff.DifferenceType;
import org.apache.nifi.registry.flow.diff.FlowDifference;
import org.apache.nifi.remote.RemoteGroupPort;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * <p>
 *     An AffectedComponentSet is a collection of components that will need to be enabled/disabled/started/stopped in order to facilitate
 *     some set of changes to a dataflow.
 * </p>
 */
public class AffectedComponentSet {
    private static final Logger logger = LoggerFactory.getLogger(AffectedComponentSet.class);
    private static final Set<ControllerServiceState> ACTIVE_CONTROLLER_SERVICE_STATES = new HashSet<>(Arrays.asList(
        ControllerServiceState.ENABLED,
        ControllerServiceState.ENABLING,
        ControllerServiceState.DISABLING
    ));
    private final FlowController flowController;
    private final FlowManager flowManager;

    private final Set<Port> inputPorts = new HashSet<>();
    private final Set<Port> outputPorts = new HashSet<>();
    private final Set<RemoteGroupPort> remoteInputPorts = new HashSet<>();
    private final Set<RemoteGroupPort> remoteOutputPorts = new HashSet<>();
    private final Set<ProcessorNode> processors = new HashSet<>();
    private final Set<ControllerServiceNode> controllerServices = new HashSet<>();
    private final Set<ReportingTaskNode> reportingTasks = new HashSet<>();
    private final Set<ParameterProviderNode> parameterProviders = new HashSet<>();
    private final Set<FlowRegistryClientNode> flowRegistryClients = new HashSet<>();

    public AffectedComponentSet(final FlowController flowController) {
        this.flowController = flowController;
        this.flowManager = flowController.getFlowManager();
    }

    public void addInputPort(final Port port) {
        if (port == null) {
            return;
        }

        inputPorts.add(port);
    }

    public void addOutputPort(final Port port) {
        if (port == null) {
            return;
        }

        outputPorts.add(port);
    }

    public void addRemoteInputPort(final RemoteGroupPort port) {
        if (port == null) {
            return;
        }

        remoteInputPorts.add(port);
    }

    public void addRemoteOutputPort(final RemoteGroupPort port) {
        if (port == null) {
            return;
        }

        remoteOutputPorts.add(port);
    }

    public void addRemoteProcessGroup(final RemoteProcessGroup remoteProcessGroup) {
        if (remoteProcessGroup == null) {
            return;
        }

        remoteProcessGroup.getInputPorts().forEach(this::addRemoteInputPort);
        remoteProcessGroup.getOutputPorts().forEach(this::addRemoteOutputPort);
    }

    public void addProcessor(final ProcessorNode processor) {
        if (processor == null) {
            return;
        }

        processors.add(processor);
    }

    public void addControllerService(final ControllerServiceNode controllerService) {
        if (controllerService == null) {
            return;
        }

        controllerServices.add(controllerService);

        final List<ComponentNode> referencingComponents = controllerService.getReferences().findRecursiveReferences(ComponentNode.class);
        for (final ComponentNode reference : referencingComponents) {
            if (reference instanceof ControllerServiceNode) {
                addControllerService((ControllerServiceNode) reference);
            } else if (reference instanceof ProcessorNode) {
                addProcessor((ProcessorNode) reference);
            } else if (reference instanceof ReportingTaskNode) {
                addReportingTask((ReportingTaskNode) reference);
            } else if (reference instanceof ParameterProviderNode) {
                addParameterProvider((ParameterProviderNode) reference);
            } else if (reference instanceof FlowRegistryClientNode) {
                addFlowRegistryClient((FlowRegistryClientNode) reference);
            }
        }
    }

    public boolean isControllerServiceAffected(final String serviceId) {
        for (final ControllerServiceNode serviceNode : controllerServices) {
            if (serviceNode.getIdentifier().equals(serviceId)) {
                return true;
            }
        }

        return false;
    }

    private void addControllerServiceWithoutReferences(final ControllerServiceNode controllerService) {
        if (controllerService == null) {
            return;
        }

        controllerServices.add(controllerService);
    }

    public void addReportingTask(final ReportingTaskNode task) {
        if (task == null) {
            return;
        }

        reportingTasks.add(task);
    }

    public boolean isReportingTaskAffected(final String reportingTaskId) {
        for (final ReportingTaskNode taskNode : reportingTasks) {
            if (taskNode.getIdentifier().equals(reportingTaskId)) {
                return true;
            }
        }

        return false;
    }

    public void addParameterProvider(final ParameterProviderNode parameterProvider) {
        if (parameterProvider == null) {
            return;
        }

        parameterProviders.add(parameterProvider);
    }

    public boolean isParameterProviderAffected(final String parameterProviderId) {
        for (final ParameterProviderNode parameterProviderNode : parameterProviders) {
            if (parameterProviderNode.getIdentifier().equals(parameterProviderId)) {
                return true;
            }
        }

        return false;
    }

    public void addFlowRegistryClient(final FlowRegistryClientNode flowRegistryClient) {
        if (flowRegistryClient == null) {
            return;
        }

        flowRegistryClients.add(flowRegistryClient);
    }

    public boolean isFlowRegistryClientAffected(final String flowRegistryClientId) {
        for (final FlowRegistryClientNode flowRegistryClientNode : flowRegistryClients) {
            if (flowRegistryClientNode.getIdentifier().equals(flowRegistryClientId)) {
                return true;
            }
        }

        return false;
    }

    public void addConnection(final Connection connection) {
        if (connection == null) {
            return;
        }

        addConnectable(connection.getSource());
        addConnectable(connection.getDestination());
    }

    public void addConnectable(final Connectable connectable) {
        if (connectable == null) {
            return;
        }

        switch (connectable.getConnectableType()) {
            case INPUT_PORT:
                addInputPort((Port) connectable);
                break;
            case OUTPUT_PORT:
                addOutputPort((Port) connectable);
                break;
            case PROCESSOR:
                addProcessor((ProcessorNode) connectable);
                break;
            case REMOTE_INPUT_PORT:
                addRemoteInputPort((RemoteGroupPort) connectable);
                break;
            case REMOTE_OUTPUT_PORT:
                addRemoteOutputPort((RemoteGroupPort) connectable);
        }
    }

    /**
     * Adds any component that is affected by the given Flow Difference
     * @param difference the Flow Difference
     */
    public void addAffectedComponents(final FlowDifference difference) {
        final DifferenceType differenceType = difference.getDifferenceType();

        if (differenceType == DifferenceType.COMPONENT_ADDED) {
            // The component doesn't exist. But if it's a connection, the source or the destination might. And those need to be accounted for.
            if (difference.getComponentB().getComponentType() == ComponentType.CONNECTION) {
                addComponentsForNewConnection((VersionedConnection) difference.getComponentB());
            }

            return;
        }

        if (differenceType == DifferenceType.PARAMETER_VALUE_CHANGED || differenceType == DifferenceType.PARAMETER_DESCRIPTION_CHANGED || differenceType == DifferenceType.PARAMETER_REMOVED) {
            addComponentsForParameterUpdate(difference);
            return;
        }

        if (differenceType == DifferenceType.PARAMETER_CONTEXT_CHANGED) {
            addComponentsForParameterContextChange(difference);
            return;
        }

        if (differenceType == DifferenceType.INHERITED_CONTEXTS_CHANGED) {
            addComponentsForInheritedParameterContextChange(difference);
        }

        if (differenceType == DifferenceType.VARIABLE_CHANGED || differenceType == DifferenceType.VARIABLE_ADDED || differenceType == DifferenceType.VARIABLE_REMOVED) {
            addComponentsForVariableChange(difference.getComponentA().getInstanceIdentifier(), difference.getFieldName().orElse(null));
            return;
        }

        if (differenceType == DifferenceType.RPG_URL_CHANGED) {
            final String instanceId = difference.getComponentA().getInstanceIdentifier();
            final RemoteProcessGroup rpg = flowManager.getRootGroup().findRemoteProcessGroup(instanceId);
            if (rpg != null) {
                addRemoteProcessGroup(rpg);
            }
        }

        if (differenceType == DifferenceType.COMPONENT_REMOVED && difference.getComponentA().getComponentType() == ComponentType.PROCESS_GROUP) {
            // If a Process Group is removed, we need to consider any component within the Process Group as affected also
            addAllComponentsWithinGroup(difference.getComponentA().getInstanceIdentifier());
        }

        addAffectedComponents(difference.getComponentA());
    }

    private void addAllComponentsWithinGroup(final String groupId) {
        final ProcessGroup processGroup = flowManager.getGroup(groupId);
        if (processGroup == null) {
            return;
        }

        processGroup.getProcessors().forEach(this::addProcessor);
        processGroup.getControllerServices(false).forEach(this::addControllerServiceWithoutReferences);
        processGroup.getInputPorts().forEach(this::addInputPort);
        processGroup.getOutputPorts().forEach(this::addOutputPort);
        processGroup.getRemoteProcessGroups().forEach(this::addRemoteProcessGroup);
        processGroup.getProcessGroups().forEach(child -> addAllComponentsWithinGroup(child.getIdentifier()));
    }

    private void addComponentsForVariableChange(final String groupId, final String variableName) {
        if (groupId == null || variableName == null) {
            return;
        }

        final ProcessGroup group = flowManager.getGroup(groupId);
        if (group == null) {
            return;
        }

        final Set<ComponentNode> affectedComponents = group.getComponentsAffectedByVariable(variableName);
        for (final ComponentNode component : affectedComponents) {
            if (component instanceof ProcessorNode) {
                addProcessor((ProcessorNode) component);
            } else if (component instanceof ControllerServiceNode) {
                addControllerService((ControllerServiceNode) component);
            }
        }
    }

    private void addComponentsForInheritedParameterContextChange(final FlowDifference difference) {
        // If the inherited parameter contexts have changed, any component referencing a parameter in that context is affected.
        final String parameterContextId = difference.getComponentA().getInstanceIdentifier();
        final ParameterContext context = flowManager.getParameterContextManager().getParameterContext(parameterContextId);
        if (context == null) {
            return;
        }

        final Set<ProcessGroup> boundGroups = context.getParameterReferenceManager().getProcessGroupsBound(context);
        for (final ProcessGroup group : boundGroups) {
            group.getProcessors().stream()
                .filter(AbstractComponentNode::isReferencingParameter)
                .forEach(this::addProcessor);

            group.getControllerServices(false).stream()
                .filter(ComponentNode::isReferencingParameter)
                .forEach(this::addControllerService);
        }
    }

    private void addComponentsForParameterContextChange(final FlowDifference difference) {
        // When the parameter context that a PG is bound to is updated, any component referencing a parameter is affected.
        final String groupId = difference.getComponentA().getInstanceIdentifier();
        final ProcessGroup group = flowManager.getGroup(groupId);
        if (group == null) {
            return;
        }

        group.getProcessors().stream()
            .filter(AbstractComponentNode::isReferencingParameter)
            .forEach(this::addProcessor);

        group.getControllerServices(false).stream()
            .filter(ComponentNode::isReferencingParameter)
            .forEach(this::addControllerService);
    }

    private void addComponentsForParameterUpdate(final FlowDifference difference) {
        final DifferenceType differenceType = difference.getDifferenceType();

        final Optional<String> optionalParameterName = difference.getFieldName();
        if (!optionalParameterName.isPresent()) {
            logger.warn("Encountered a Flow Difference {} with Difference Type of {} but no indication as to which parameter was updated.", difference, differenceType);
            return;
        }

        final String parameterName = optionalParameterName.get();
        final String contextId = difference.getComponentA().getInstanceIdentifier();
        final ParameterContext parameterContext = flowManager.getParameterContextManager().getParameterContext(contextId);
        if (parameterContext == null) {
            logger.warn("Encountered a Flow Difference {} with a Difference Type of {} but found no Parameter Context with Instance ID {}", difference, differenceType, contextId);
            return;
        }

        final Set<ControllerServiceNode> referencingServices = parameterContext.getParameterReferenceManager().getControllerServicesReferencing(parameterContext, parameterName);
        final Set<ProcessorNode> referencingProcessors = parameterContext.getParameterReferenceManager().getProcessorsReferencing(parameterContext, parameterName);

        referencingServices.forEach(this::addControllerService);
        referencingProcessors.forEach(this::addProcessor);
    }

    private void addComponentsForNewConnection(final VersionedConnection connection) {
        final ConnectableComponent sourceComponent = connection.getSource();
        final Connectable sourceConnectable = getConnectable(sourceComponent.getType(), sourceComponent.getInstanceIdentifier());
        if (sourceConnectable != null) {
            addConnectable(sourceConnectable);
        }

        final ConnectableComponent destinationComponent = connection.getDestination();
        final Connectable destinationConnectable = getConnectable(destinationComponent.getType(), destinationComponent.getInstanceIdentifier());
        if (destinationConnectable != null) {
            addConnectable(destinationConnectable);
        }
    }

    private Connectable getConnectable(final ConnectableComponentType type, final String identifier) {
        switch (type) {
            case FUNNEL:
                return flowManager.getFunnel(identifier);
            case INPUT_PORT:
                return flowManager.getInputPort(identifier);
            case OUTPUT_PORT:
                return flowManager.getOutputPort(identifier);
            case PROCESSOR:
                return flowManager.getProcessorNode(identifier);
            case REMOTE_INPUT_PORT:
            case REMOTE_OUTPUT_PORT:
                return flowManager.getRootGroup().findRemoteGroupPort(identifier);
            default:
                return null;
        }
    }

    private void addAffectedComponents(final VersionedComponent versionedComponent) {
        final String componentId = versionedComponent.getInstanceIdentifier();
        switch (versionedComponent.getComponentType()) {
            case CONNECTION:
                addConnection(flowManager.getConnection(componentId));
                break;
            case CONTROLLER_SERVICE:
                addControllerService(flowManager.getControllerServiceNode(componentId));
                break;
            case INPUT_PORT:
                addInputPort(flowManager.getInputPort(componentId));
                break;
            case OUTPUT_PORT:
                addOutputPort(flowManager.getOutputPort(componentId));
                break;
            case PROCESS_GROUP:
                break;
            case PROCESSOR:
                addProcessor(flowManager.getProcessorNode(componentId));
                break;
            case REMOTE_INPUT_PORT:
                final RemoteGroupPort remoteInputPort = flowManager.getRootGroup().findRemoteGroupPort(componentId);
                if (remoteInputPort != null) {
                    addRemoteInputPort(remoteInputPort);
                }
                break;
            case REMOTE_OUTPUT_PORT:
                final RemoteGroupPort remoteOutputPort = flowManager.getRootGroup().findRemoteGroupPort(componentId);
                if (remoteOutputPort != null) {
                    addRemoteOutputPort(remoteOutputPort);
                }
                break;
            case FLOW_REGISTRY_CLIENT:
                addFlowRegistryClient(flowManager.getFlowRegistryClient(componentId));
            case REMOTE_PROCESS_GROUP:
                addRemoteProcessGroup(flowManager.getRootGroup().findRemoteProcessGroup(componentId));
                break;
            case REPORTING_TASK:
                addReportingTask(flowManager.getReportingTaskNode(componentId));
                break;
        }
    }

    /**
     * Returns a new AffectedComponentSet that represents only those components that are currently active. A component is considered active if it is an Input/Output Port
     * and is running, is a Processor or reporting task that has at least one active thread or a scheduled state of RUNNING or STARTING, or is a Controller Service that is
     * ENABLED or ENABLING.
     *
     * @return an AffectedComponentSet that represents all components within this AffectedComponentSet that are currently active. The components contained by the returned AffectedComponentSet
     * will always be a subset or equal to the set of components contained by this.
     */
    public AffectedComponentSet toActiveSet() {
        final AffectedComponentSet active = new AffectedComponentSet(flowController);
        inputPorts.stream().filter(port -> port.getScheduledState() == ScheduledState.RUNNING).forEach(active::addInputPort);
        outputPorts.stream().filter(port -> port.getScheduledState() == ScheduledState.RUNNING).forEach(active::addOutputPort);
        remoteInputPorts.stream().filter(port -> port.getScheduledState() == ScheduledState.RUNNING).forEach(active::addRemoteInputPort);
        remoteOutputPorts.stream().filter(port -> port.getScheduledState() == ScheduledState.RUNNING).forEach(active::addRemoteOutputPort);

        processors.stream().filter(this::isActive).forEach(active::addProcessor);
        reportingTasks.stream().filter(task -> task.getScheduledState() == ScheduledState.STARTING || task.getScheduledState() == ScheduledState.RUNNING || task.isRunning())
            .forEach(active::addReportingTask);
        controllerServices.stream().filter(service -> ACTIVE_CONTROLLER_SERVICE_STATES.contains(service.getState()))
            .forEach(active::addControllerServiceWithoutReferences);

        return active;
    }

    private boolean isActive(final ProcessorNode processor) {
        // We consider component active if it's starting, running, or has active threads. The call to ProcessorNode.isRunning() will only return true if it has active threads or a scheduled
        // state of RUNNING but not if it has a scheduled state of STARTING. We also consider if the processor is to be started once the flow controller has been fully initialized, as
        // the state of the processor may not yet have been set
        final ScheduledState scheduledState = processor.getPhysicalScheduledState();
        return scheduledState == ScheduledState.STARTING || scheduledState == ScheduledState.RUNNING || processor.isRunning() || flowController.isStartAfterInitialization(processor);
    }

    private boolean isStopped(final ProcessorNode processor) {
        final ScheduledState state = processor.getPhysicalScheduledState();
        final boolean stateCorrect = state == ScheduledState.STOPPED || state == ScheduledState.DISABLED;
        return stateCorrect && !processor.isRunning();
    }

    public void start() {
        logger.info("Starting the following components: {}", this);
        flowController.getControllerServiceProvider().enableControllerServices(controllerServices);

        inputPorts.forEach(port -> port.getProcessGroup().startInputPort(port));
        outputPorts.forEach(port -> port.getProcessGroup().startOutputPort(port));
        remoteInputPorts.forEach(port -> port.getRemoteProcessGroup().startTransmitting(port));
        remoteOutputPorts.forEach(port -> port.getRemoteProcessGroup().startTransmitting(port));
        processors.forEach(processor -> processor.getProcessGroup().startProcessor(processor, false));
        reportingTasks.forEach(flowController::startReportingTask);
    }

    public void removeComponents(final ComponentSetFilter filter) {
        inputPorts.removeIf(filter::testInputPort);
        outputPorts.removeIf(filter::testOutputPort);
        remoteInputPorts.removeIf(filter::testRemoteInputPort);
        remoteOutputPorts.removeIf(filter::testRemoteOutputPort);
        processors.removeIf(filter::testProcessor);
        controllerServices.removeIf(filter::testControllerService);
        reportingTasks.removeIf(filter::testReportingTask);
        flowRegistryClients.removeIf(filter::testFlowRegistryClient);
    }

    /**
     * Returns a new AffectedComponentSet that represents only those components that currently exist within the NiFi instance. When a set of dataflow updates have occurred, it is very possible
     * that one or more components referred to by the AffectedComponentSet no longer exist (for example, there was a dataflow update that removed a Processor, so that Processor no longer exists).
     *
     * @return an AffectedComponentSet that represents all components within this AffectedComponentSet that currently exist within the NiFi instance. The components contained by the returned
     * AffectedComponentSetwill always be a subset or equal to the set of components contained by this.
     */
    public AffectedComponentSet toExistingSet() {
        final ControllerServiceProvider serviceProvider = flowController.getControllerServiceProvider();

        final AffectedComponentSet existing = new AffectedComponentSet(flowController);
        inputPorts.stream().filter(port -> port.getProcessGroup().getInputPort(port.getIdentifier()) != null).forEach(existing::addInputPort);
        outputPorts.stream().filter(port -> port.getProcessGroup().getOutputPort(port.getIdentifier()) != null).forEach(existing::addOutputPort);
        remoteInputPorts.stream().filter(port -> port.getProcessGroup().findRemoteGroupPort(port.getIdentifier()) != null).forEach(existing::addRemoteInputPort);
        remoteOutputPorts.stream().filter(port -> port.getProcessGroup().findRemoteGroupPort(port.getIdentifier()) != null).forEach(existing::addRemoteOutputPort);
        processors.stream().filter(processor -> processor.getProcessGroup().getProcessor(processor.getIdentifier()) != null).forEach(existing::addProcessor);
        reportingTasks.stream().filter(task -> flowController.getReportingTaskNode(task.getIdentifier()) != null).forEach(existing::addReportingTask);
        controllerServices.stream().filter(service -> serviceProvider.getControllerServiceNode(service.getIdentifier()) != null).forEach(existing::addControllerServiceWithoutReferences);
        flowRegistryClients.stream().filter(client -> flowManager.getFlowRegistryClient(client.getIdentifier()) != null).forEach(existing::addFlowRegistryClient);

        return existing;
    }

    /**
     * Returns a new AffectedComponentSet that represents only those components that currently can be started. When a set of dataflow updates have occurred, it is very possible
     * that one or more components referred to by the AffectedComponentSet can no longer be started (for example, there was a dataflow update that disabled a Processor that previously was running).
     *
     * @return an AffectedComponentSet that represents all components within this AffectedComponentSet that currently exist within the NiFi instance. The components contained by the returned
     * AffectedComponentSet will always be a subset or equal to the set of components contained by this.
     */
    public AffectedComponentSet toStartableSet() {
        final AffectedComponentSet startable = new AffectedComponentSet(flowController);
        inputPorts.stream().filter(this::isStartable).forEach(startable::addInputPort);
        outputPorts.stream().filter(this::isStartable).forEach(startable::addOutputPort);
        remoteInputPorts.stream().filter(this::isStartable).forEach(startable::addRemoteInputPort);
        remoteOutputPorts.stream().filter(this::isStartable).forEach(startable::addRemoteOutputPort);
        processors.stream().filter(this::isStartable).forEach(startable::addProcessor);
        reportingTasks.stream().filter(this::isStartable).forEach(startable::addReportingTask);
        controllerServices.stream().filter(this::isStartable).forEach(startable::addControllerServiceWithoutReferences);

        return startable;
    }

    private boolean isStartable(final ComponentNode componentNode) {
        if (componentNode == null) {
            return false;
        }

        if (componentNode instanceof ProcessorNode) {
            return ((ProcessorNode) componentNode).getScheduledState() != ScheduledState.DISABLED;
        }
        if (componentNode instanceof ReportingTaskNode) {
            return ((ReportingTaskNode) componentNode).getScheduledState() != ScheduledState.DISABLED;
        }

        return true;
    }

    private boolean isStartable(final Port port) {
        if (port == null) {
            return false;
        }

        return port.getScheduledState() != ScheduledState.DISABLED;
    }

    public void stop() {
        logger.info("Stopping the following components: {}", this);
        final long start = System.currentTimeMillis();

        inputPorts.forEach(port -> port.getProcessGroup().stopInputPort(port));
        outputPorts.forEach(port -> port.getProcessGroup().stopOutputPort(port));
        remoteInputPorts.forEach(port -> port.getRemoteProcessGroup().stopTransmitting(port));
        remoteOutputPorts.forEach(port -> port.getRemoteProcessGroup().stopTransmitting(port));
        processors.forEach(processor -> processor.getProcessGroup().stopProcessor(processor));
        reportingTasks.forEach(flowController::stopReportingTask);

        waitForConnectablesStopped();

        if (!controllerServices.isEmpty()) {
            final Future<Void> disableFuture = flowController.getControllerServiceProvider().disableControllerServicesAsync(controllerServices);
            waitForControllerServicesStopped(disableFuture);
        }

        final long millis = System.currentTimeMillis() - start;
        logger.info("Successfully stopped all components in {} milliseconds", millis);
    }

    private void waitForControllerServicesStopped(final Future<Void> future) {
        try {
            while (true) {
                logger.info("Waiting for all Controller Services to become disabled...");
                if (logger.isDebugEnabled()) {
                    final Set<ControllerServiceNode> activeServices = controllerServices.stream().filter(ControllerServiceNode::isActive).collect(Collectors.toSet());
                    logger.debug("There are currently {} active Controller Services: {}", activeServices.size(), activeServices);
                }

                try {
                    future.get(10, TimeUnit.SECONDS);
                    return;
                } catch (final TimeoutException ignored) {
                }
            }
        } catch (final Exception e) {
            throw new UninheritableFlowException("Could not disable all affected Controller Services", e);
        }
    }

    private void waitForConnectablesStopped() {
        long count = 0L;
        try {
            while (!componentsStopped()) {
                if (count++ % 1000 == 0) {
                    // The 0th time and every 1000th time (10 seconds), log an update
                    logger.info("Waiting for all required Processors and Reporting Tasks to stop...");
                    if (reportingTasks.isEmpty() && processors.isEmpty()) {
                        return;
                    }

                    if (logger.isDebugEnabled()) {
                        final Set<ReportingTaskNode> activeReportingTasks = reportingTasks.stream().filter(ReportingTaskNode::isRunning).collect(Collectors.toSet());
                        logger.debug("There are currently {} active Reporting Tasks: {}", activeReportingTasks.size(), activeReportingTasks);

                        final Set<ProcessorNode> activeProcessors = processors.stream()
                            .filter(processor -> !isStopped(processor))
                            .collect(Collectors.toSet());
                        logger.debug("There are currently {} active Processors: {}", activeProcessors.size(), activeProcessors);
                    }
                }

                Thread.sleep(10L);
            }
        } catch (final Exception e) {
            throw new UninheritableFlowException("Could not stop all affected components", e);
        }
    }

    private boolean componentsStopped() {
        if (processors.stream().anyMatch(processor -> !isStopped(processor))) {
            return false;
        }
        if (reportingTasks.stream().anyMatch(ReportingTaskNode::isRunning)) {
            return false;
        }

        return true;
    }

    @Override
    public String toString() {
        return "AffectedComponentSet[" +
            "inputPorts=" + inputPorts +
            ", outputPorts=" + outputPorts +
            ", remoteInputPorts=" + remoteInputPorts +
            ", remoteOutputPorts=" + remoteOutputPorts +
            ", processors=" + processors +
            ", parameterProviders=" + parameterProviders +
            ", flowRegistryCliens=" + flowRegistryClients +
            ", controllerServices=" + controllerServices +
            ", reportingTasks=" + reportingTasks +
            "]";
    }
}


text:
@interface LookUpReservationController () <UITableViewDelegate, UITableViewDataSource>

@property(strong, nonatomic) UITableView *tableView;
@property(strong, nonatomic) NSFetchedResultsController *reservedRooms;

@end

@implementation LookUpReservationController

- (void)loadView {
    [super loadView];
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:self.tableView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

//-(NSFetchedResultsController *)reservedRooms {
//
//    if (!_reservedRooms) {
//    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
//    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Reservation"];
//
//    }
//}

@end

redpajama_set_name: RedPajamaGithub


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

<title>Uses of Class org.springframework.core.AttributeAccessorSupport (Spring Framework 5.1.18.RELEASE API)</title>
<meta name="date" content="2020-09-15">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.springframework.core.AttributeAccessorSupport

Packages that use AttributeAccessorSupport

Package
Description

org.springframework.beans

This package contains interfaces and classes for manipulating Java beans.

org.springframework.beans.factory.annotation

Support package for annotation-driven bean configuration.

org.springframework.beans.factory.support

Classes supporting the org.springframework.beans.factory package.

org.springframework.context.annotation

Annotation support for the Application Context, including JSR-250 "common"
 annotations, component-scanning, and Java-based metadata for creating
 Spring-managed objects.

Uses of AttributeAccessorSupport in org.springframework.beans

Subclasses of AttributeAccessorSupport in org.springframework.beans

Modifier and Type
Class and Description

class
BeanMetadataAttributeAccessor

Extension of AttributeAccessorSupport,
 holding attributes as BeanMetadataAttribute objects in order
 to keep track of the definition source.

class
PropertyValue

Object to hold information and value for an individual bean property.

Uses of AttributeAccessorSupport in org.springframework.beans.factory.annotation

Subclasses of AttributeAccessorSupport in org.springframework.beans.factory.annotation

Modifier and Type
Class and Description

class
AnnotatedGenericBeanDefinition

Extension of the GenericBeanDefinition
 class, adding support for annotation metadata exposed through the
 AnnotatedBeanDefinition interface.

Uses of AttributeAccessorSupport in org.springframework.beans.factory.support

Subclasses of AttributeAccessorSupport in org.springframework.beans.factory.support

Modifier and Type
Class and Description

class
AbstractBeanDefinition

Base class for concrete, full-fledged BeanDefinition classes,
 factoring out common properties of GenericBeanDefinition,
 RootBeanDefinition, and ChildBeanDefinition.

class
AutowireCandidateQualifier

Qualifier for resolving autowire candidates.

class
ChildBeanDefinition

Bean definition for beans which inherit settings from their parent.

class
GenericBeanDefinition

GenericBeanDefinition is a one-stop shop for standard bean definition purposes.

class
RootBeanDefinition

A root bean definition represents the merged bean definition that backs
 a specific bean in a Spring BeanFactory at runtime.

Uses of AttributeAccessorSupport in org.springframework.context.annotation

Subclasses of AttributeAccessorSupport in org.springframework.context.annotation

Modifier and Type
Class and Description

class
ScannedGenericBeanDefinition

Extension of the GenericBeanDefinition
 class, based on an ASM ClassReader, with support for annotation metadata exposed
 through the AnnotatedBeanDefinition interface.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Spring Framework

Prev

Next

Frames

No Frames

All Classes


text:
title: 'Utenti e gruppi di utenti'
date: '01-08-2015 00:00'
taxonomy:
    tag:
        - arch
        - linux
        - lenovo
        - ideapad
        - g50-70
        - user
        - utente
        - groups
        - gruppo
        - getent
        - limitato
        - root
        - permessi
summary: 'Installare Arch Linux su Lenovo IdeaPad G50-70 con UEFI e Secure Boot (parte 15 - Utenti e gruppi di utenti)'
product: articles
depth: 2
---

Tutte le operazioni fino ad ora svolte sono state eseguite utilizzando l'utente principale **root** con tutti i permessi sull'intero sistema.

Tuttavia, per l'utilizzo quotidiano del sistema, è sempre raccomandato l'uso di un altro utente, di permessi limitati che possa agire esclusivamente nella propria directory *home*, ovvero nella directory che contiene tutti i dati personali dell'utente.

Ciascun utente avrà un identificativo di utente (UID = User ID) e un identificativo di gruppo (GID = Group ID). I gruppi di utenti consentono di raggruppare permessi a più utenti.

## Gruppi di utenti

Per conoscere l'elenco dei gruppi ai quali aggiungere gli utenti è possibile utilizzare il comando **getent group**.

    [root@arch-lenovo ~]# getent group
    root:x:0:root
    bin:x:1:root,bin,daemon
    ...

La maggior parte dei gruppi di utenti sono ad uso del sistema mentre alcuni gruppi aggiuntivi sono specifici per l'aggiunta di permessi agli utenti extra, come i seguenti:

  * **root** consente ai membri accesso totale a tutte le parti del sistema
  * **adm** fornisce l'accesso a molti strumenti amministrativi
  * **tty** fornisce l'accesso ai dispositivi console come /dev/tty\*
  * **disk** fornisce l'accesso alle periferiche disco, come dischi e partizioni
  * **lp** fornisce l'accesso alle periferiche di stampa
  * **wheel** consente agli utenti di diventare utente root col comando sudo
  * **uucp** fornisce l'accesso alle periferiche seriali come /dev/ttyS\*
  * **locate** permette l'uso del comando updatedb (dal pacchetto mlocate)
  * **rfkill** permette di comandare l'accensione e lo spegnimento di periferiche WiFi o Bluetooth
  * **proc** consente di leggere le informazioni contenute nel file system /proc
  * **network** consente di controllare le connessioni di rete
  * **video** fornisce l'accesso alle periferiche video
  * **audio** fornisce l'accesso alle periferiche audio
  * **optical** fornisce l'accesso alle periferiche ottiche
  * **floppy** fornisce l'accesso alle periferiche floppy
  * **storage** fornisce l'accesso alle periferiche disco rimovibili
  * **scanner** fornisce l'accesso alle periferiche scanner
  * **input** fornisce l'accesso alle periferiche di input
  * **power** permette il controllo dell'alimentazione o della sospensione
  * **users** include i permessi standard per gli utenti limitati
  * **systemd-journal** consente l'accesso ai log di systemd

## Aggiungere un nuovo utente al sistema

Per aggiungere un nuovo utente è possibile utilizzare il comando **useradd** in questa maniera:

    [root@arch-lenovo ~]# useradd -m -g users muflone

L'ultimo argomento **muflone** rappresenta il nome del nuovo utente da creare, mentre l'argomento **-m** indica di creare una nuova directory home col nome /home/muflone, infine l'argomento **-g users** indica il gruppo predefinito cui l'utente appartiene, in questo caso **users**.

E' possibile specificare gruppi di utenti aggiuntivi con l'argomento **-G**, ad esempio con:

    [root@arch-lenovo ~]# useradd -m -g users -G rfkill,systemd-journal muflone

L'utente muflone sarà automaticamente membro del gruppo **users** e dei gruppi aggiuntivi **rfkill** (per l'uso del comando rfkill) e **systemd-journal** (per la lettura del log di sistema col comando journalctl).

## Aggiungere un utente ad un gruppo di utenti

E' anche possibile aggiungere in un secondo momento un utente ad un gruppo utilizzando il comando **gpasswd --add UTENTE GRUPPO**.

    [root@arch-lenovo ~]# gpasswd --add muflone rfkill
    Aggiunta dell'utente muflone al gruppo rfkill

    [root@arch-lenovo ~]# gpasswd --add muflone systemd-journal
    Aggiunta dell'utente muflone al gruppo systemd-journal

Un utente per il sistema viene sempre identificato attraverso il suo UID, sebbene molti programmi (come gpasswd ad esempio) richiedono l'uso del suo nome. Alcuni strumenti (come i gestori grafici di login) visualizzano il nome completo dell'utente, una sorta di descrizione associata a ciascun utente.

Per cambiare il nome completo dell'utente è possibile utilizzare il comando **chfn --full-name "NOME COMPLETO" UTENTE** come ad esempio.

    [root@arch-lenovo ~]# chfn --full-name "Muflone Ovinis" muflone
    Modifica delle informazioni finger per muflone in corso.

    Le informazioni finger sono state modificate.

## Verifica di un utente

Per verificare l'operazione appena eseguita è possibile utilizzare il comando **id UTENTE**.

    [root@arch-lenovo ~]# id muflone
    uid=1000(muflone) gid=100(users) gruppi=100(users),24(rfkill),190(systemd-journal)

L'utente muflone avrà un identificativo personale (uid) 1000, un identificativo di gruppo (gid) 100 e sarà presente nei gruppi 100 (users), 24 (rfkill) e 190 (systemd-journal).

Per verificare i gruppi cui un utente appartiene è possibile utilizzare il comando **groups UTENTE**.

    [root@arch-lenovo ~]# groups muflone
    rfkill systemd-journal users

## Cambiare la password di accesso di un utente

Senza una password di accesso, normalmente non è permesso l'accesso al sistema.

Per assegnare una password di accesso al nuovo utente appena creato si potrà utilizzare il comando **passwd UTENTE**.

    [root@arch-lenovo ~]# passwd muflone
    Immettere nuova password UNIX:
    Reimmettere la nuova password UNIX:
    passwd: password aggiornata correttamente

Quando richiesto, digitare la nuova password da assegnare all'utente. **Non saranno mostrati asterischi** o altri simboli durante la digitazione per non lasciare traccia della lunghezza della password. Limitarsi a digitare la password, confermarla con invio e ridigitarla quando richiesto.

## Eliminazione di un utente

Per completezza di informazione è possibile eliminare un utente preesistente utilizzando il comando **userdel**.

    [root@arch-lenovo ~]# userdel -r muflone
    userdel: muflone mail spool (/var/spool/mail/muflone) not found

L'argomento **-r** indica l'eliminazione di tutti i dati personali nella directory home dell'utente da eliminare. Senza l'argomento -r la directory personale non verrà eliminata.


text:
package javasmmr.zoowsome.models.animals;

import static javasmmr.zoowsome.repositories.EntityRepository.createNode;

import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLStreamException;

import javasmmr.zoowsome.services.factories.animal.Constants;

/**
 *
 * @author Marius Bologa
 *
 */

public class Butterfly extends Insect {
	/**
	 *
	 */
	private int legs = 6;
	/**
	 *
	 */
	private String nameB = "Monarch";

	/**
	 *
	 * @param maintenanceCost
	 *            How many hours per week each animal require.
	 *
	 * @param dangerPerc
	 *            How dangerous an animal is.
	 *
	 *
	 */
	public Butterfly(final double maintenanceCost, final double dangerPerc) {
		super(maintenanceCost, dangerPerc);
		setCanFly(true);
		setNrOfLegs(legs);
		setName(nameB);
		setDangerous(false);
	}

	/**
	 *
	 * @param name
	 *            The name of the butterfly.
	 * @param maintenanceCost
	 *            How many hours per week each animal require.
	 *
	 * @param dangerPerc
	 *            How dangerous an animal is.
	 */
	public Butterfly(final String name, final double maintenanceCost, final double dangerPerc) {
		super(maintenanceCost, dangerPerc);
		setCanFly(true);
		setNrOfLegs(legs);
		setName(name);
		setDangerous(false);
	}

	/**
	 * @param eventWriter
	 *            To encode to XML.
	 * @throws XMLStreamException
	 *             .
	 */
	public void encodeToXml(final XMLEventWriter eventWriter) throws XMLStreamException {
		super.encodeToXml(eventWriter);
		createNode(eventWriter, Constants.XML_TAGS.DISCRIMINANT, Constants.Animals.Insects.Butterfly);
	}
}


text:
{% set addon_type = amo.ADDON_PERSONA %}
{% extends "impala/base_side_categories.html" %}

{% from "includes/forms.html" import pretty_field, tip %}
{% from "devhub/includes/macros.html" import some_html_tip %}

{% set title = _('Create a New Theme') %}

{% block title %}{{ page_title(title) }}{% endblock %}

{% block primary %}

  <masthead class="hero submit-theme">

{{ title }}

      {% trans submit_url=url('devhub.docs', 'themes') %}
        Background themes let you easily personalize the look of your Firefox.
        Submit your own design below, or learn how
        to create one!
      {% endtrans %}

  </masthead>

    <form method="post">
      {% csrf_token %}
      {{ form.unsaved_data }}
      <fieldset>
        <legend>{{ _('Theme Details') }}</legend>

          {{ pretty_field(form.name, label=_('Give your Theme a name.'), validate=True) }}

            {% set before_slug = ('%s/addon/' % settings.SITE_URL)|safe %}
            {{ pretty_field(form.slug, label=_('Supply a pretty URL for your detail page.'), tag=None, before=before_slug, validate=True) }}

              {{ _('Please use only letters, numbers, underscores, and dashes in your URL.') }}

          {{ pretty_field(form.category, label=_('Select the category that best describes your Theme.'),
                          class='row radios addon-cats', validate=True) }}

            {{ pretty_field(form.tags, label=_('Add some tags to describe your Theme.'), tag=None, opt=True, validate=True) }}

              {{ ngettext('Comma-separated, minimum of {0} character.',
                          'Comma-separated, minimum of {0} characters.',
                          amo.MIN_TAG_LENGTH)|format_html(amo.MIN_TAG_LENGTH) }}
              {{ _('Example: dark, cinema, noir. Limit 20.') }}

            {{ pretty_field(form.description, label=_('Describe your Theme.'),
                            tooltip=_("A short explanation of your theme's "
                                      "basic functionality that is displayed in "
                                      "search and browse listings, as well as at "
                                      "the top of your theme's details page."),
                            tag=None, opt=True, validate=True) }}

              {{ some_html_tip() }}

      </fieldset>
      <fieldset>
        <legend>{{ _('Theme License') }}</legend>
        {{ form.license }}
        {{ form.license.errors }}
        {% include 'devhub/addons/includes/cc_license_chooser.html' %}

{{ _('Select a license for your Theme.') }}

            {% for license in amo.PERSONA_LICENSES %}

<input type="radio" name="license" value="{{ license.id }}">
                {{ license.name }}

            {% endfor %}

      </fieldset>
      <fieldset id="persona-design">
        <legend>{{ _('Theme Design') }}</legend>
        {% with required = True %}
          {% include "devhub/personas/includes/theme_design.html" %}
        {% endwith %}

{{ _('Select colors for your Theme.') }}

          {{ pretty_field(form.textcolor, label=_('Foreground Text'),
                          tooltip=_('This is the color of the tab text.'),
                          validate=True) }}
          {{ pretty_field(form.accentcolor, label=_('Background'),
                          tooltip=_('This is the color of the tabs.'),
                          validate=True) }}

      </fieldset>
      <fieldset id="persona-preview">
        <legend>{{ _('Preview') }}</legend>

                {{ _("Your Theme's Name") }}

                {% trans user=user.username,
                         profile_url=user.get_url_path() %}
                  by {{ user }}
                {% endtrans %}

      </fieldset>

          {{ form.agreed.as_widget(attrs={'required': ''}) }}
          {% trans agreement_link_open=''|safe,
                   privacy_notice_link_open=''|safe, link_close=''|safe %}
            I agree to the {{ agreement_link_open }}Firefox Add-on Distribution Agreement{{ link_close }} and to my information being handled as described in the {{ privacy_notice_link_open }}Websites, Communications and Cookies Privacy Notice{{ link_close }}.
          {% endtrans %}

        {{ form.agreed.errors }}

<button class="button prominent" disabled type="submit">{{ _('Submit Theme') }}</button>

    </form>

{% endblock %}


text:
title: GSIM - Generic Statistical Information Model
slug: gsim-generic-statistical-information-model
description:
A reference framework that provides a common terminology acroos and
  between statistical organisations; aligns with DDI and SDMX.

website: http://www1.unece.org/stat/platform/display/metis/Generic+Statistical+Information+Model
subjects:
- general
disciplines:
- statistics
standards:
- ddi-data-documentation-initiative
layout: extension
type: extension
---


text:
title: 'Progetto esecutivo'
date: '28-11-2016 15:20'
body_classes: article-background-image
---

Il 28 Novembre 2016 il progetto esecutivo del Braccetto ed il relativo bando di appalto è stato trasmesso alla Centrale Unica di San Miniato per la pubblicazione.

![](braccetto-1TAVOLA-2.jpg)


text:
using System;
using System.Web.Mvc;
using System.Web.Routing;

namespace Subtext.Web.Infrastructure
{
    public class SubtextControllerActivator : IControllerActivator
    {
        IDependencyResolver _resolver;

        public SubtextControllerActivator(IDependencyResolver resolver)
        {
            _resolver = resolver;
        }

        public IController Create(RequestContext requestContext, Type controllerType)
        {
            IController controller = (_resolver.GetService(controllerType) ?? Activator.CreateInstance(controllerType)) as IController;
            var fullController = controller as Controller;
            if (fullController != null)
            {
                fullController.TempDataProvider = new EmptyTempDataProvider();
            }

            return controller;

        }
    }
}


text:
package org.musiel.args.reflect;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@ Target( ElementType.METHOD)
@ Retention( RetentionPolicy.RUNTIME)
@ Inherited
public @ interface EnvironmentVariable {

	public String value();
}


text:
"""
Declaration of a class corresponding to the data stored in the token for a prayer

by John McGuinness, 2017
"""

from __future__ import print_function
import struct
import os
from abc import ABCMeta, abstractmethod

AUDIO_HOST=os.environ['AUDIO_HOST']

AUDIO_MAPPING={
    'SignOfTheCross': AUDIO_HOST + 'prayers/SignOfTheCross.m4a',
    'Creed': AUDIO_HOST + 'prayers/Creed.m4a',
    'Our Father': AUDIO_HOST + 'prayers/Our+Father.m4a',
    'Hail Mary': AUDIO_HOST + 'prayers/Hail+Mary.m4a',
    'Glory Be': AUDIO_HOST + 'prayers/Glory+Be.m4a',
    'Fatima Prayer': AUDIO_HOST + 'prayers/Fatima+Prayer.m4a',
    'Hail Holy Queen': AUDIO_HOST + 'prayers/Hail+Holy+Queen.m4a',
    'ClosingPrayer': AUDIO_HOST + 'prayers/ClosingPrayer.m4a',
    'Holy God': AUDIO_HOST + 'prayers/Holy+God.m4a',
    'For the sake': AUDIO_HOST + 'prayers/For+the+sake.m4a',
    'Eternal Father': AUDIO_HOST + 'prayers/Eternal+Father.m4a'
    }

FORMAT='15p15p20pll'

class TokenData(object):
    prayer_type='Rosary'
    mysteries='joyful'
    prayer='Creed'
    decade=0
    counter=0

    __metaclass__ = ABCMeta

    def do_print(self):
        return (self.prayer_type + ":" + self.mysteries + ":" + str(self.decade) + ":" + self.prayer + ":" + str(self.counter))

    def __init__(self,prayer_type,mysteries,prayer,decade,counter):
        self.prayer_type = prayer_type
        self.mysteries = mysteries
        self.prayer = prayer
        self.decade = decade
        self.counter = counter

    @classmethod
    def from_token(self, token):
        parts = struct.unpack(FORMAT,token)
        type  = parts[0];
        if (type == 'Rosary'):
            return RosaryTokenData(parts[1],parts[2],parts[3],parts[4])
        elif (type == 'Divine Mercy'):
            return DivineMercyTokenData(parts[2],parts[3],parts[4])
        else:
            raise NotImplementedError('Bad prayer type:' + type)

    def get_audio(self):
        if self.prayer=='Mystery':
            return AUDIO_HOST + 'mysteries/' + self.mysteries + '/' + str(self.decade) + '.m4a'
        else:
            return AUDIO_MAPPING[self.prayer]

    def get_token(self):
        return struct.pack(FORMAT, self.prayer_type,
                           self.mysteries,
                           self.prayer,
                           self.decade,
                           self.counter)

    @abstractmethod
    def get_next(self):
        pass

    def __eq__(self, other):
        if isinstance(other, TokenData):
            return (self.prayer_type == other.prayer_type
                    and self.mysteries == other.mysteries
                    and self.prayer == other.prayer
                    and self.decade == other.decade
                    and self.counter == other.counter
            )
        else:
            return NotImplemented

class RosaryTokenData(TokenData):
    def __init__(self,mysteries,prayer,decade,counter):
        super(RosaryTokenData, self).__init__('Rosary',mysteries,prayer,decade,counter)

    def get_next(self):
        mysteries=self.mysteries
        prayer=self.prayer
        counter=self.counter+1
        decade=self.decade

        if self.prayer=='SignOfTheCross':
            if (self.decade == 0):
                prayer='Creed'
            else:
                return {}

        if self.prayer=='Hail Holy Queen':
            prayer='ClosingPrayer'

        if self.prayer=='ClosingPrayer':
            prayer='SignOfTheCross'

        if self.prayer=='Creed':
            prayer='Our Father';

        elif self.prayer=='Mystery':
            prayer='Our Father'

        elif self.prayer=='Our Father':
            prayer='Hail Mary'

        elif self.prayer=='Hail Mary':
            if (self.decade == 0 and counter >= 3) or counter >= 10:
                prayer='Glory Be'

        elif self.prayer=='Glory Be':
            prayer='Fatima Prayer'

        elif self.prayer=='Fatima Prayer':
            if self.decade >= 5:
                prayer='Hail Holy Queen'
            else:
                prayer='Mystery'
                decade += 1

        if prayer != self.prayer:
            counter=0

        return RosaryTokenData(mysteries, prayer, decade, counter)

class DivineMercyTokenData(TokenData):
    def __init__(self,prayer,decade,counter):
        super(DivineMercyTokenData, self).__init__('Divine Mercy','',prayer,decade,counter)

    def get_next(self):
        prayer=self.prayer
        counter=self.counter+1
        decade=self.decade

        if self.prayer == 'SignOfTheCross':
            if (self.decade == 0):
                prayer='Our Father'
            else:
                return {}

        elif self.prayer == 'Our Father':
            prayer='Hail Mary'

        elif self.prayer == 'Hail Mary':
            prayer='Creed'

        elif self.prayer == 'Creed':
            decade += 1
            prayer ='Eternal Father'

        elif self.prayer == 'Eternal Father':
            prayer = 'For the sake'

        elif self.prayer == 'For the sake':
            if (counter >= 10):
                if (decade >= 5):
                    prayer='Holy God'
                    counter = 0
                else:
                    decade += 1
                    prayer='Eternal Father'

        elif self.prayer == 'Holy God':
            if (counter < 3):
                prayer = 'Holy God'
            else:
                prayer='SignOfTheCross'

        if prayer != self.prayer:
            counter=0

        return DivineMercyTokenData(prayer, decade, counter)


text:
<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\RefPeringkatProgram;

/**
 * RefPeringkatProgramSearch represents the model behind the search form about `app\models\RefPeringkatProgram`.
 */
class RefPeringkatProgramSearch extends RefPeringkatProgram
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'aktif', 'created_by', 'updated_by'], 'integer'],
            [['desc', 'created', 'updated'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = RefPeringkatProgram::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'aktif' => $this->aktif,
            'created_by' => $this->created_by,
            'updated_by' => $this->updated_by,
            'created' => $this->created,
            'updated' => $this->updated,
        ]);

        $query->andFilterWhere(['like', 'desc', $this->desc]);

        return $dataProvider;
    }
}


text:
package model

import (
	"testing"

	. "github.com/smartystreets/goconvey/convey"
)

func TestChangeLogs(t *testing.T) {
	Convey("GetReviewUrl", t, func() {
		cl := &ChangeLog{
			Message: "",
		}
		_, err := cl.GetReviewUrl()
		So(err, ShouldNotBeNil)
		cl = &ChangeLog{
			Message: "Use TestActivationManager for all page activations\n\nblah blah\n\nChange-Id: blah\nBug: blah\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3472129\nReviewed-by: blah blah\n",
		}
		reviewUrl, err := cl.GetReviewUrl()
		So(err, ShouldBeNil)
		So(reviewUrl, ShouldEqual, "https://chromium-review.googlesource.com/c/chromium/src/+/3472129")
	})

	Convey("GetReviewTitle", t, func() {
		cl := &ChangeLog{
			Message: "",
		}
		reviewTitle, err := cl.GetReviewTitle()
		So(err, ShouldNotBeNil)
		So(reviewTitle, ShouldEqual, "")

		cl = &ChangeLog{
			Message: "Use TestActivationManager for all page activations\n\nblah blah\n\nChange-Id: blah\nBug: blah\nReviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3472129\nReviewed-by: blah blah\n",
		}
		reviewTitle, err = cl.GetReviewTitle()
		So(err, ShouldBeNil)
		So(reviewTitle, ShouldEqual, "Use TestActivationManager for all page activations")
	})
}


text:
![CI](https://github.com/joliss/node-fixturify/workflows/CI/badge.svg)

Convert JSON objects into directory structures on the file system, and back
again. This package is primarily useful for writing tests.

## Installation

```bash
yarn add fixturify
```

## Usage

```js
const fixturify = require('fixturify')

const obj = {
  'foo.txt': 'foo.txt contents',
  'subdir': {
    'bar.txt': 'bar.txt contents'
  }
}

fixturify.writeSync('testdir', obj) // write it to disk

fixturify.readSync('testdir') // => deep-equals obj

fixturify.readSync('testdir', { globs: ['foo*'] }) // glob support
// => { foo.txt: 'foo.text contents' }

fixturify.readSync('testdir', { ignore: ['foo*'] }) // glob support
// => { subdir: { bar.txt: 'bar.text contents' } }

fixturify.writeSync('testDir', {
  'subdir': { 'bar.txt': null }
}) // remove subdir/bar.txt

fixturify.readSync('testdir') // => { foo.txt: 'foo.text contents' }

fixturify.writeSync('testDir', {
  'subdir': null
}) // remove subdir/

```

```js
const fixturify = require('fixturify')

const obj = {
  'subdir': {
    'foo.txt': 'foo.txt contents'
  },
  'emptydir': {}
}

fixturify.writeSync('testdir', obj) // write it to disk

fixturify.readSync('testdir', { ignoreEmptyDirs: true })
// => { subdir: { foo.txt': 'foo.txt contents' } }

```

File contents are decoded and encoded with UTF-8.

`fixture.readSync` follows symlinks. It throws an error if it encounters a
broken symlink.

## Limitations

To keep the API simple, node-fixturify has the following limitations:

* Reading or setting file stats (last-modified time, permissions, etc.) is
  not supported.

* Creating symlinks is not supported. Symlinks are traversed when reading. Broken symlinks throw.

* Special files like FIFOs, sockets, or devices are not supported.

* File contents are automatically encoded/decoded into strings. Binary files
  are not supported.


text:
'''
Created on 2014年12月23日

@author: jin
'''
from django.conf.urls import patterns, url
import os
from house.settings import MEDIA_ROOT
urlpatterns=patterns('apps.agent.views',
     url(r'^profile/$', 'profile'),
     url(r'^client_list/$', 'client_list'),
     url(r'^add_client/(recommend)/$', 'add_client'),
     url(r'^add_client/$', 'add_client'),
     url(r'^bind_account/$', 'bind_account'),
     url(r'^recommend/(\d*)/$', 'recommend'),
     url(r'^introduction/$', 'introduction'),
     url(r'^public_weixin_authorization_url/$', 'public_weixin_authorization_url'),
     url(r'^public_weixin_authorization/$', 'public_weixin_authorization'),
     url(r'^download/([0-9\-]*\.xlsx)/$', 'download_xlsx',),

)


text:
var React = require('react')
  , ImmutablePropTypes = require('react-immutable-proptypes');

var TEST_TEMPLATE_CLASS = 'findme';
var TEST_TEMPLATE_SELECTED_CLASS = 'selected';
var TEST_TEMPLATE_DELETE_BUTTON_CLASS = 'deleteMe';

function createTestTemplate(id) {
  id = id || '';
  var template = React.createClass({
    displayName: 'TestTemplate' + id,
    propTypes: {
      data: ImmutablePropTypes.contains({
        text: React.PropTypes.string
      }),
      selected: React.PropTypes.bool,
      onRemove: React.PropTypes.func
    },
    render: function() {
      return (
        <div
          className={TEST_TEMPLATE_CLASS + id + (this.props.selected ? ' ' + TEST_TEMPLATE_SELECTED_CLASS : '')}
          style={{display: 'inline-block'}}
        >
          {this.props.data.get('text')}
          <span className={TEST_TEMPLATE_DELETE_BUTTON_CLASS} onClick={this.props.onRemove} />
        </div>
      );
    }
  });

  template.templateClass = TEST_TEMPLATE_CLASS + id;
  template.selectedClass = TEST_TEMPLATE_SELECTED_CLASS;
  template.deleteButtonClass = TEST_TEMPLATE_DELETE_BUTTON_CLASS;

  return template;
}

module.exports = {
  default: createTestTemplate(''),
  alternate: createTestTemplate('_2')
};


text:
<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web/frontend/assets';
    public $css = [
        'css/site.css',
    ];
    public $js = [
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}


text:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public class NewInfectionManager : MonoBehaviour {
    public static NewInfectionManager Instance;

    public Transform WabbitPrefab, StandardPrefab, TankPrefab, BombPrefab;
    public bool AllowWabbit, AllowStandard, AllowTank, AllowBomb;
    public List<Transform> InvasionForce { get; set; }

    //idea: 'threat level' that can be tied to UI

    private List<MachineStrategyAnchor> invasionCandidates = new List<MachineStrategyAnchor>();
    private int MachinesToInfect = 1;
    private float InvasionRadius = 175f;
    private Guid InvasionID;
    private MachineStrategyAnchor MachineInvasionTarget;
    private Coroutine WaitingInvasion { get; set; }
    private float CurrentWaitDuration { get; set; }
    private bool IsPlottingOrInvading = false;

    private static float InvasionSuccessCountdownInSeconds = 60;
    private float CurrentCoundown = 0f;

    void Awake()
    {
#if UNITY_EDITOR
        NetworkMap.CurrentLocation = NetworkMap.GetLocationByCurrentScene();
#endif
        Instance = this;
    }

    // Use this for initialization
    void Start() {
        for (int i = 0; i < CyberspaceBattlefield.Current.CurrentNetwork.Machines.Count; i++)
        {
            MachineStrategyAnchor msa = GameObject.Find(CyberspaceBattlefield.Current.CurrentNetwork.Machines[i].Name).GetComponent<MachineStrategyAnchor>();
            invasionCandidates.Add(msa);
            msa.myMachine.OnMachineClean += OnMachineClean;
        }

        InvasionForce = new List<Transform>();
    }

    private void OnMachineClean()
    {
        MachinesToInfect++;

        StartRandomCountdown();
    }

    /// <summary>
    /// starts an invasion countdown if not currently planning or executing a reinfection
    /// and if there are more than one machine
    /// and if the player hasn't won
    /// </summary>
    private void StartRandomCountdown()
    {
        if (!IsPlottingOrInvading && (MachinesToInfect > 1) && NetworkMap.CurrentLocation.IsInfected)
        {
            WaitingInvasion = StartCoroutine(WaitUntilInvasion());
        }
    }

    private IEnumerator WaitUntilInvasion()
    {
        IsPlottingOrInvading = true;
        InvasionForce = GetRandomInvasionForce();
        yield return new WaitForSecondsInterruptTime(GetRandomInvasionTime());
        MachineInvasionTarget = FindRandomMachine();
        StartInvasion();
    }

    private List<Transform> invasionForceCandidates = new List<Transform>();
    private Coroutine WaitToWin;

    private List<Transform> GetRandomInvasionForce()
    {
        InvasionForce.Clear();
        invasionForceCandidates.Clear();

        if (AllowWabbit)
            invasionForceCandidates.Add(WabbitPrefab);
        if (AllowStandard)
            invasionForceCandidates.Add(StandardPrefab);
        if (AllowTank)
            invasionForceCandidates.Add(TankPrefab);
        if (AllowBomb)
            invasionForceCandidates.Add(BombPrefab);

        int NumOfInvaders = UnityEngine.Random.Range(3, 6);

        int randomIndex = -1;
        for (int i = 0; i < NumOfInvaders; i++)
        {
            randomIndex = UnityEngine.Random.Range(0, invasionForceCandidates.Count);
            Transform toAdd = invasionForceCandidates[randomIndex];
            InvasionForce.Add(toAdd);

            //wabbits create partners, so they count for twice
            if (toAdd == WabbitPrefab)
                i++;
        }

        return InvasionForce;
    }

    private MachineStrategyAnchor FindRandomMachine()
    {
        int randomIndex = UnityEngine.Random.Range(0, MachinesToInfect);

        return invasionCandidates.FindAll(c => !c.myMachine.IsInfected)[randomIndex];
    }

    /// <summary>
    /// begins an invasion if there is a target and the battlefield is infected
    /// </summary>
    private void StartInvasion()
    {
        if ((MachineInvasionTarget != null) && NetworkMap.CurrentLocation.IsInfected)
        {
            MachineInvasionTarget.myMachine.StartReinfection();
            InvasionID = Guid.NewGuid();

            foreach(Transform t in InvasionForce)
            {
                Transform newT = GameObject.Instantiate<Transform>(t);
                VirusAI.AfterInstantiateVirus(newT, MachineInvasionTarget.transform);
                newT.localPosition = Vector3.back * InvasionRadius;
                newT.RotateAround(MachineInvasionTarget.transform.position, Vector3.up, UnityEngine.Random.Range(0f, 360f));
            }

            ToastLog.ToastSticky(String.Format("{0} Reinfection: 1%", MachineInvasionTarget.myMachine.SubnetAddress), 1, InvasionID);
            WaitToWin = StartCoroutine(WaitUntilWin());
        }
    }

    private IEnumerator WaitUntilWin()
    {
        while((CurrentCoundown < InvasionSuccessCountdownInSeconds) && MachineInvasionTarget.myMachine.IsBeingReinfected)
        {
            yield return null;
            CurrentCoundown += InterruptTime.deltaTime;

            int percentage = (int)(CurrentCoundown / InvasionSuccessCountdownInSeconds * 100f);
            ToastLog.ToastSticky(String.Format("{0} Reinfection: {1}%", MachineInvasionTarget.myMachine.SubnetAddress, percentage), percentage, InvasionID);
        }

        if (MachineInvasionTarget.myMachine.IsBeingReinfected)
        {
            OnInvasionSuccess();
        }
        else
        {
            OnInvasionFailure();
        }
    }

    public void OnInvasionSuccess()
    {
        MachinesToInfect--;
        MachineInvasionTarget.myMachine.DoOnMachineReinfectionComplete();
        ToastLog.ToastSticky(String.Format("{0} Reinfection Complete!", MachineInvasionTarget.myMachine.SubnetAddress), -1, InvasionID);
        StartRandomCountdown();
    }

    public void OnInvasionFailure()
    {
        ToastLog.ToastSticky(String.Format("{0} Reinfection Aborted!", MachineInvasionTarget.myMachine.SubnetAddress), -1, InvasionID);
        StartRandomCountdown();
    }

    private float GetRandomInvasionTime()
    {
#if UNITY_EDITOR
        this.CurrentWaitDuration = UnityEngine.Random.Range(30f, 60f);
#else
        this.CurrentWaitDuration = UnityEngine.Random.Range(30f, 120f);
#endif
        return this.CurrentWaitDuration;
    }

    void OnDestroy()
    {
        foreach(MachineStrategyAnchor msa in invasionCandidates)
        {
            msa.myMachine.OnMachineClean -= OnMachineClean;
        }
    }
}


text:
package org.hope6537.netty.protocol.http.xml.codec;

import io.netty.handler.codec.http.FullHttpRequest;

/**
 * @author wuyang
 * @version 1.0
 * @date 2014年3月1日
 */
public class HttpXmlRequest {

    private FullHttpRequest request;
    private Object body;

    public HttpXmlRequest(FullHttpRequest request, Object body) {
        this.request = request;
        this.body = body;
    }

    /**
     * @return the request
     */
    public final FullHttpRequest getRequest() {
        return request;
    }

    /**
     * @param request the request to set
     */
    public final void setRequest(FullHttpRequest request) {
        this.request = request;
    }

    /**
     * @return the object
     */
    public final Object getBody() {
        return body;
    }

    /**
     * @param object the object to set
     */
    public final void setBody(Object body) {
        this.body = body;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "HttpXmlRequest [request=" + request + ", body =" + body + "]";
    }
}


text:
// Copyright 2008 Google Inc. All Rights Reserved.

package com.google.opengse.testlet.Error;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSession;

/**
 * Throws an exception out of the the app code stack.
 *
 * This is not yet used - as our TCs are all client-driven.
 *
 * The spec says: "crash" the web app - 500 code only.
 *
 * @author Wenbo Zhu
 */
public class SessionTimeoutListener implements HttpSessionListener {

  public void sessionCreated ( HttpSessionEvent se ) {
  }

  public void sessionDestroyed ( HttpSessionEvent se ) {
    HttpSession session = se.getSession();
    if (session == null) {
      throw new NullPointerException("null session!");
    }
    String id = (String) session.getAttribute("id");
    if (id != null && id.equals("timedoutSession")) {
      // timed-out
      throw new IllegalArgumentException("what the hell");
    }
  }
}


text:
export class NamesList {
  names: Array<string>;
  constructor() {
    this.names = ['Dijkstra', 'Knuth', 'Turing', 'Hopper'];
  }
  get() {
    return this.names;
  }
  add(value) {
    this.names.push(value);
  }
}


text:
package org.apache.hadoop.zebra.pig;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.zebra.BaseTestCase;
import org.apache.hadoop.zebra.io.BasicTable;
import org.apache.hadoop.zebra.io.TableInserter;
import org.apache.hadoop.zebra.schema.Schema;
import org.apache.hadoop.zebra.types.TypesUtils;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.Iterator;

public class TestLoaderWithCollection extends BaseTestCase
{
    private static Path pathTable;

    @BeforeClass
    public static void setUp() throws Exception {
      init();
      pathTable = getTableFullPath("TestMapTableLoader");
      removeDir(pathTable);

        BasicTable.Writer writer = new BasicTable.Writer(pathTable,
                "c:collection(record(a:double))", "[c]", conf);
        Schema schema = writer.getSchema();
        Tuple tuple = TypesUtils.createTuple(schema);

        final int numsBatch = 10;
        final int numsInserters = 2;
        TableInserter[] inserters = new TableInserter[numsInserters];
        for (int i = 0; i < numsInserters; i++) {
            inserters[i] = writer.getInserter("ins" + i, false);
        }

        for (int b = 0; b < numsBatch; b++) {
            for (int i = 0; i < numsInserters; i++) {
                TypesUtils.resetTuple(tuple);

                DataBag bagColl = TypesUtils.createBag();
                Schema schColl = schema.getColumn(0).getSchema().getColumn(0).getSchema();
                Tuple tupColl1 = TypesUtils.createTuple(schColl);
                Tuple tupColl2 = TypesUtils.createTuple(schColl);
                tupColl1.set(0, 3.1415926);
                bagColl.add(tupColl1);
                tupColl2.set(0, 123.456789);
                bagColl.add(tupColl2);
                tuple.set(0, bagColl);

                inserters[i].insert(new BytesWritable(("key" + i).getBytes()), tuple);
            }
        }
        for (int i = 0; i < numsInserters; i++) {
            inserters[i].close();
        }
        writer.close();
    }

    @AfterClass
    public static void tearDown() throws Exception {
        pigServer.shutdown();
    }

    @Test
    public void test() throws ExecException, IOException {
        String query = "records = LOAD '" + pathTable.toString()
        + "' USING org.apache.hadoop.zebra.pig.TableLoader('c');";
        System.out.println(query);
        pigServer.registerQuery(query);
        Iterator<Tuple> it = pigServer.openIterator("records");
        while (it.hasNext()) {
            Tuple cur = it.next();
            System.out.println(cur);
        }
    }
}


text:
<?php
/**
 * Deprecated. No longer needed.
 *
 * @package WordPress
 */
_deprecated_file( basename( __FILE__ ), '2.1.0', null, __( 'This file no longer needs to be included.' ) );


text:
package com.hs.mail.imap.message.response;

import com.hs.mail.imap.mailbox.Mailbox;

/**
 *
 * @author Won Chul Doh
 * @since Mar 9, 2010
 *
 */
public class ListResponse extends AbstractImapResponse {

	private Mailbox mailbox;

	public ListResponse(Mailbox mailbox) {
		super();
		this.mailbox = mailbox;
	}

	public Mailbox getMailbox() {
		return mailbox;
	}

}


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace Projeny.Internal
{
    public static class PathUtil
    {
        public static bool IsSubPath(string parent, string child)
        {
            // call Path.GetFullPath to Make sure we're using Path.DirectorySeparatorChar
            parent = Path.GetFullPath(parent);
            child = Path.GetFullPath(child);

            return child.StartsWith(parent);
        }

        public static void AssertPathIsValid(string path)
        {
            try
            {
                Path.GetDirectoryName(path);
            }
            catch (Exception e)
            {
                throw new ArgumentException(
                    "Invalid path '{0}'".Fmt(path, e));
            }
        }

        public static string Combine(params string[] paths)
        {
            Assert.That(!paths.IsEmpty());

            string result = paths[0];

            for (int i = 1; i < paths.Length; i++)
            {
                result = Path.Combine(result, paths[i]);
            }

            return result;
        }

        public static string GetRelativePath(string fromDirectory, string toPath)
        {
            Assert.IsNotNull(toPath);
            Assert.IsNotNull(fromDirectory);

            // call Path.GetFullPath to Make sure we're using Path.DirectorySeparatorChar
            fromDirectory = Path.GetFullPath(fromDirectory);
            toPath = Path.GetFullPath(toPath);

            bool isRooted = (Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath));

            if (isRooted)
            {
                bool isDifferentRoot = (string.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0);

                if (isDifferentRoot)
                {
                    return toPath;
                }
            }

            List<string> relativePath = new List<string>();
            string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);

            string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);

            int length = Math.Min(fromDirectories.Length, toDirectories.Length);

            int lastCommonRoot = -1;

            // find common root
            for (int x = 0; x < length; x++)
            {
                if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
                {
                    break;
                }

                lastCommonRoot = x;
            }

            if (lastCommonRoot == -1)
                return toPath;

            // add relative folders in from path
            for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
            {
                if (fromDirectories[x].Length > 0)
                {
                    relativePath.Add("..");
                }
            }

            // add to folders to path
            for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
            {
                relativePath.Add(toDirectories[x]);
            }

            // create relative path
            string[] relativeParts = new string[relativePath.Count];
            relativePath.CopyTo(relativeParts, 0);

            return string.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);
        }

        public static IEnumerable<string> GetAllFilesUnderDirectory(string path)
        {
            Assert.That(Directory.Exists(path));

            Queue<string> queue = new Queue<string>();
            queue.Enqueue(path);

            while (queue.Count > 0)
            {
                path = queue.Dequeue();
                try
                {
                    foreach (string subDir in Directory.GetDirectories(path))
                    {
                        queue.Enqueue(subDir);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(ex);
                }

                string[] files = null;
                try
                {
                    files = Directory.GetFiles(path);
                }
                catch (Exception ex)
                {
                    Log.ErrorException(ex);
                }

                if (files != null)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        yield return files[i];
                    }
                }
            }
        }

        public static IEnumerable<DirectoryInfo> GetAllParentDirectories(string path)
        {
            //Assert.That(Directory.Exists(path));
            return GetAllParentDirectories(new DirectoryInfo(path));
        }

        public static IEnumerable<DirectoryInfo> GetAllParentDirectories(DirectoryInfo dirInfo)
        {
            if (dirInfo == null || dirInfo.Name == dirInfo.Root.Name)
            {
                yield break;
            }

            yield return dirInfo;

            foreach (var parent in GetAllParentDirectories(dirInfo.Parent))
            {
                yield return parent;
            }
        }

        public static string FindExePathFromEnvPath(string exe)
        {
            exe = Environment.ExpandEnvironmentVariables(exe);

            if (!File.Exists(exe))
            {
                if (Path.GetDirectoryName(exe) == String.Empty)
                {
                    foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'))
                    {
                        string path = test.Trim();

                        if (!String.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe)))
                        {
                            return Path.GetFullPath(path);
                        }
                    }
                }

                throw new FileNotFoundException(
                    new FileNotFoundException().Message, exe);
            }

            return Path.GetFullPath(exe);
        }

        // Returns null if can't find anything that's valid
        public static string FindClosestValidPath(string absolutePath)
        {
            if (!Path.IsPathRooted(absolutePath))
            {
                return null;
            }

            while (!Directory.Exists(absolutePath))
            {
                var parentInfo = Directory.GetParent(absolutePath);

                if (parentInfo == null)
                {
                    return null;
                }

                absolutePath = parentInfo.FullName;
            }

            return absolutePath;
        }
    }
}


text:
var errorBuilder = require('error-builder');

var HttpError = exports.HttpError = errorBuilder.create('HttpError', 500, 'Http error');

var HttpAppError = exports.HttpAppError = errorBuilder.create('HttpAppError', 400, 'Http application error', HttpError);
exports.BadRequest = errorBuilder.create('BadRequestError', 400, 'Bad request', HttpAppError);
exports.Unauthorized = errorBuilder.create('UnauthorizedError', 401, 'Not authorized to make this request', HttpAppError);
exports.PaymentRequired = errorBuilder.create('PaymentRequiredError', 402, 'Payment required', HttpAppError);
exports.Forbidden = errorBuilder.create('ForbiddenError', 403, 'Forbidden', HttpAppError);
exports.NotFound = errorBuilder.create('NotFoundError', 404, 'Resource not found', HttpAppError);

var HttpSysError = exports.HttpSysError = errorBuilder.create('HttpSysError', 500, 'Http system error', HttpError);
exports.InternalError = errorBuilder.create('InternalError', 500, 'Internal error', HttpSysError);
exports.NotImplemented = errorBuilder.create('NotImplementedError', 501, 'Not implemented', HttpSysError);
exports.Overloaded = errorBuilder.create('OverloadedError', 502, 'Temporarily overloaded', HttpSysError);
exports.GatewayTimeout = errorBuilder.create('GatewayTimeoutError', 503, 'Gateway timeout', HttpSysError);


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monograph of Cercospora 597 (1954)

#### Original name
Cercospora weberi Chupp

### Remarks
null


text:
% load data/generate new testing data and show how matlab implementation of
% FEMH1 regularisation works
%
% Lukas Pospisil, USI, Lugano 2016
%

clear all
close all

fem_type = 0;
%fem_type = 1;

addpath('common') % add common stuff
addpath('compute_femh1') % add functions for femh1 computation

fem_reduce = 0.5;

% load data or create new
C_true=[2*ones(1,60) ones(1,50) 2*ones(1,30) ones(1,133) 2*ones(1,20)];

C_true = [C_true C_true C_true C_true]';
sigma=1;
C_orig=C_true+sigma*randn(size(C_true)); % gaussian

% reduce original problem
T2 = ceil(length(C_orig)*fem_reduce);
if fem_type == 0
    C = reduce0( C_orig, T2 );
end
if fem_type == 1
    C = reduce1( C_orig, T2 );
end

Theta = [1.0, 2.0]; % given Theta, K = length(Theta)
epssqrs = 10.^(0:0.2:7); % used penalties
T = length(C_true);

C_err = Inf*ones(size(epssqrs)); % here store errors (to plot final error curve)
L_value = Inf*ones(size(epssqrs)); % here store values of L (to final plot)
qp_lin = zeros(size(epssqrs)); % here store values of linear term of L (to plot final L-curve)
qp_quad = zeros(size(epssqrs)); % here store values of linear term of L (to plot final L-curve)

best_epssqr = Inf;
best_epssqr_id = 1;

gamma = get_random_gamma0( length(C), length(Theta) ); % random initial gamma for first epssqr
[H1 B] = get_H1(length(C), length(Theta)); % I want to reuse matrices, it is not neccessary to assemble them for each epssqr
for i = 1:length(epssqrs)
	% get penalty
	epssqr = epssqrs(i);

    % show some info to prove that Matlab is not sleeping
    disp([' - epssqr = ' num2str(epssqr)])

	% run the algorithm (reuse previous gamma as initial approximation)
    [C_filtered, gamma, qp_lin(i), qp_quad(i), L ] = compute_femh1( C, H1, B, gamma, Theta, epssqr );

	% compute error
%    C_err(i) = mean(abs(C_filtered-C_true));
    if fem_type == 0
        C_filtered_orig = prolongate0(C_filtered,length(C_orig));
    end
    if fem_type == 1
        C_filtered_orig = prolongate1(C_filtered,length(C_orig));
    end
    C_err(i) = norm(C_filtered_orig-C_true,2);
    L_values(i) = L;

	% if this choice of penalty is the best (subject to error), then store the solution
    if C_err(i) < best_epssqr
		best_epssqr_id = i;
        best_C_filtered = C_filtered_orig;
        best_epssqr = C_err(best_epssqr_id);
	end
end

% plot the error curve (epssqr vs. err)
figure
subplot(1,3,1);
hold on
title('Error curve');
xlabel('epssqr');
ylabel('Filtering Error E_t[||x_{true}(t)-x_{filtered}(t)||]')
% plot curve
plot(epssqrs,C_err,'b.-','LineWidth',1.0);
% plot the best choice
plot(epssqrs(best_epssqr_id),C_err(best_epssqr_id),'mo', 'MarkerSize', 15)
set(gca,'xscale','log','yscale','log')
hold off

% plot the L curve (linear_part vs. quadratic_part)
subplot(1,3,2);
hold on
title('L-curve');
xlabel('linear term (model error)');
ylabel('quadratic term (penalty)')
%set(gca,'xscale','log','yscale','log')
% plot curve
plot(qp_lin,qp_quad,'r.-','LineWidth',1.0);
% plot the best choice
plot(qp_lin(best_epssqr_id),qp_quad(best_epssqr_id),'mo', 'MarkerSize', 15)
% plot text
for i=1:length(epssqrs)
   text(qp_lin(i),qp_quad(i),['eps = ' num2str(epssqrs(i))])
end
set(gca,'xscale','log','yscale','log')
hold off

% plot values of L
subplot(1,3,3);
hold on
title('values of L');
xlabel('epssqr');
ylabel('L')
% plot curve
plot(epssqrs,L_values,'b.-','LineWidth',1.0);
% plot the best choice
plot(epssqrs(best_epssqr_id),L_values(best_epssqr_id),'mo', 'MarkerSize', 15)
set(gca,'xscale','log')
hold off

% plot solution
figure
hold on
title(['solution, epssqr = ' num2str(epssqrs(best_epssqr_id))]);
xlabel('t');
ylabel('x(t)')
% plot signals
plot(1:length(C_orig),C_orig,'b-','LineWidth',1.0);
plot(1:length(C_true),C_true,'r--','LineWidth',2.0);
plot(1:length(C_true),best_C_filtered,'-','LineWidth',2.0,'Color',[0.0,0.4,0.0]);
legend('with noise','original', 'reconstructed');
%legend('with noise', 'original', 'reconstructed');
% the noise is large, I am interested more in signal, not in noise
axis([1 length(C_true) 0 3])
hold off