text:
package org.optaplanner.core.impl.solver;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.fail;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.assertj.core.api.SoftAssertions;
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.ExtendWith;
import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.ScoreManager;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.core.api.score.calculator.EasyScoreCalculator;
import org.optaplanner.core.api.score.director.ScoreDirector;
import org.optaplanner.core.api.solver.Solver;
import org.optaplanner.core.api.solver.SolverFactory;
import org.optaplanner.core.config.constructionheuristic.ConstructionHeuristicPhaseConfig;
import org.optaplanner.core.config.constructionheuristic.ConstructionHeuristicType;
import org.optaplanner.core.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import org.optaplanner.core.config.localsearch.LocalSearchPhaseConfig;
import org.optaplanner.core.config.localsearch.LocalSearchType;
import org.optaplanner.core.config.phase.custom.CustomPhaseConfig;
import org.optaplanner.core.config.score.director.ScoreDirectorFactoryConfig;
import org.optaplanner.core.config.solver.SolverConfig;
import org.optaplanner.core.config.solver.monitoring.MonitoringConfig;
import org.optaplanner.core.config.solver.monitoring.SolverMetric;
import org.optaplanner.core.config.solver.termination.TerminationConfig;
import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import org.optaplanner.core.impl.heuristic.selector.move.generic.ChangeMove;
import org.optaplanner.core.impl.phase.custom.CustomPhaseCommand;
import org.optaplanner.core.impl.phase.custom.NoChangeCustomPhaseCommand;
import org.optaplanner.core.impl.phase.event.PhaseLifecycleListenerAdapter;
import org.optaplanner.core.impl.phase.scope.AbstractStepScope;
import org.optaplanner.core.impl.score.DummySimpleScoreEasyScoreCalculator;
import org.optaplanner.core.impl.testdata.domain.TestdataEntity;
import org.optaplanner.core.impl.testdata.domain.TestdataSolution;
import org.optaplanner.core.impl.testdata.domain.TestdataValue;
import org.optaplanner.core.impl.testdata.domain.chained.TestdataChainedAnchor;
import org.optaplanner.core.impl.testdata.domain.chained.TestdataChainedEntity;
import org.optaplanner.core.impl.testdata.domain.chained.TestdataChainedSolution;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListEntity;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListSolution;
import org.optaplanner.core.impl.testdata.domain.list.TestdataListValue;
import org.optaplanner.core.impl.testdata.domain.multientity.TestdataHerdEntity;
import org.optaplanner.core.impl.testdata.domain.multientity.TestdataLeadEntity;
import org.optaplanner.core.impl.testdata.domain.multientity.TestdataMultiEntitySolution;
import org.optaplanner.core.impl.testdata.domain.pinned.TestdataPinnedEntity;
import org.optaplanner.core.impl.testdata.domain.pinned.TestdataPinnedSolution;
import org.optaplanner.core.impl.testdata.domain.score.TestdataHardSoftScoreSolution;
import org.optaplanner.core.impl.testdata.util.PlannerTestUtils;
import org.optaplanner.core.impl.testutil.TestMeterRegistry;

import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Metrics;
import io.micrometer.core.instrument.Tags;

@ExtendWith(SoftAssertionsExtension.class)
class DefaultSolverTest {

    @BeforeEach
    void resetGlobalRegistry() {
        Metrics.globalRegistry.clear();
        List<MeterRegistry> meterRegistryList = new ArrayList<>();
        meterRegistryList.addAll(Metrics.globalRegistry.getRegistries());
        meterRegistryList.forEach(Metrics.globalRegistry::remove);
    }

    @Test
    void solve() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void checkDefaultMeters() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);

        DefaultSolver<TestdataSolution> solver = (DefaultSolver<TestdataSolution>) solverFactory.buildSolver();
        meterRegistry.publish(solver);
        assertThat(meterRegistry.getMeters().stream().map(Meter::getId)).isEmpty();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        AtomicBoolean updatedTime = new AtomicBoolean();
        solver.addEventListener(event -> {
            if (!updatedTime.get()) {
                assertThat(meterRegistry.getMeters().stream().map(Meter::getId))
                        .containsExactlyInAnyOrder(
                                new Meter.Id(SolverMetric.SOLVE_DURATION.getMeterId(),
                                        Tags.empty(),
                                        null,
                                        null,
                                        Meter.Type.LONG_TASK_TIMER),
                                new Meter.Id(SolverMetric.ERROR_COUNT.getMeterId(),
                                        Tags.empty(),
                                        null,
                                        null,
                                        Meter.Type.COUNTER),
                                new Meter.Id(SolverMetric.SCORE_CALCULATION_COUNT.getMeterId(),
                                        Tags.empty(),
                                        null,
                                        null,
                                        Meter.Type.GAUGE));
                updatedTime.set(true);
            }
        });
        solver.solve(solution);

        // Score calculation count should be removed
        // since registering multiple gauges with the same id
        // make it return the average, and the solver holds
        // onto the solver scope, meaning it won't automatically
        // be deregistered.
        assertThat(meterRegistry.getMeters().stream().map(Meter::getId))
                .containsExactlyInAnyOrder(
                        new Meter.Id(SolverMetric.SOLVE_DURATION.getMeterId(),
                                Tags.empty(),
                                null,
                                null,
                                Meter.Type.LONG_TASK_TIMER),
                        new Meter.Id(SolverMetric.ERROR_COUNT.getMeterId(),
                                Tags.empty(),
                                null,
                                null,
                                Meter.Type.COUNTER));
    }

    @Test
    void checkDefaultMetersTags() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);

        DefaultSolver<TestdataSolution> solver = (DefaultSolver<TestdataSolution>) solverFactory.buildSolver();
        solver.setMonitorTagMap(Map.of("tag.key", "tag.value"));
        meterRegistry.publish(solver);
        assertThat(meterRegistry.getMeters().stream().map(Meter::getId)).isEmpty();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        AtomicBoolean updatedTime = new AtomicBoolean();
        solver.addEventListener(event -> {
            if (!updatedTime.get()) {
                assertThat(meterRegistry.getMeters().stream().map(Meter::getId))
                        .containsExactlyInAnyOrder(
                                new Meter.Id(SolverMetric.SOLVE_DURATION.getMeterId(),
                                        Tags.empty(),
                                        null,
                                        null,
                                        Meter.Type.LONG_TASK_TIMER),
                                new Meter.Id(SolverMetric.ERROR_COUNT.getMeterId(),
                                        Tags.empty(),
                                        null,
                                        null,
                                        Meter.Type.COUNTER),
                                new Meter.Id(SolverMetric.SCORE_CALCULATION_COUNT.getMeterId(),
                                        Tags.of("tag.key", "tag.value"),
                                        null,
                                        null,
                                        Meter.Type.GAUGE));
                updatedTime.set(true);
            }
        });
        solver.solve(solution);

        // Score calculation count should be removed
        // since registering multiple gauges with the same id
        // make it return the average, and the solver holds
        // onto the solver scope, meaning it won't automatically
        // be deregistered.
        assertThat(meterRegistry.getMeters().stream().map(Meter::getId))
                .containsExactlyInAnyOrder(
                        new Meter.Id(SolverMetric.SOLVE_DURATION.getMeterId(),
                                Tags.empty(),
                                null,
                                null,
                                Meter.Type.LONG_TASK_TIMER),
                        new Meter.Id(SolverMetric.ERROR_COUNT.getMeterId(),
                                Tags.empty(),
                                null,
                                null,
                                Meter.Type.COUNTER));
    }

    // TODO: Enable with Micrometer 1.7.8 or later.
    @Disabled("https://github.com/micrometer-metrics/micrometer/issues/2947")
    @Test
    void solveMetrics() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);

        Solver<TestdataSolution> solver = solverFactory.buildSolver();
        ((DefaultSolver<TestdataSolution>) solver).setMonitorTagMap(Map.of("solver.id", "solveMetrics"));
        meterRegistry.publish(solver);

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        AtomicBoolean updatedTime = new AtomicBoolean();
        solver.addEventListener(event -> {
            if (!updatedTime.get()) {
                meterRegistry.getClock().addSeconds(2);
                meterRegistry.publish(solver);
                assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "ACTIVE_TASKS")).isOne();
                assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "DURATION").longValue())
                        .isEqualTo(2L);
                updatedTime.set(true);
            }
        });
        solution = solver.solve(solution);

        meterRegistry.publish(solver);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();

        assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "DURATION")).isZero();
        assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "ACTIVE_TASKS")).isZero();
        assertThat(meterRegistry.getMeasurement(SolverMetric.ERROR_COUNT.getMeterId(), "COUNT")).isZero();
    }

    public static class BestScoreMetricEasyScoreCalculator
            implements EasyScoreCalculator<TestdataHardSoftScoreSolution, HardSoftScore> {

        @Override
        public HardSoftScore calculateScore(TestdataHardSoftScoreSolution testdataSolution) {
            long count = testdataSolution.getEntityList()
                    .stream()
                    .filter(e -> e.getValue() != null)
                    .filter(e -> e.getValue().getCode().startsWith("reward"))
                    .count();
            return HardSoftScore.ofSoft((int) count);
        }
    }

    public static class NoneValueSelectionFilter
            implements SelectionFilter<TestdataHardSoftScoreSolution, ChangeMove<TestdataHardSoftScoreSolution>> {
        @Override
        public boolean accept(ScoreDirector<TestdataHardSoftScoreSolution> scoreDirector,
                ChangeMove<TestdataHardSoftScoreSolution> selection) {
            return ((TestdataValue) (selection.getToPlanningValue())).getCode().equals("none");
        }
    }

    @Test
    void solveBestScoreMetrics() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataHardSoftScoreSolution.class, TestdataEntity.class);
        solverConfig.setScoreDirectorFactoryConfig(
                new ScoreDirectorFactoryConfig().withEasyScoreCalculatorClass(BestScoreMetricEasyScoreCalculator.class));
        solverConfig.setTerminationConfig(new TerminationConfig().withBestScoreLimit("0hard/2soft"));
        solverConfig.setMonitoringConfig(new MonitoringConfig()
                .withSolverMetricList(List.of(SolverMetric.BEST_SCORE)));
        solverConfig.setPhaseConfigList(List.of(
                // Force OptaPlanner to select "none" value which reward 0 soft
                new ConstructionHeuristicPhaseConfig()
                        .withConstructionHeuristicType(ConstructionHeuristicType.FIRST_FIT)
                        .withMoveSelectorConfigList(
                                List.of(new ChangeMoveSelectorConfig()
                                        .withFilterClass(NoneValueSelectionFilter.class))),
                // Then do a local search, which allow OptaPlanner to select "reward" value
                // which reward 1 soft per entity
                new LocalSearchPhaseConfig()
                        .withLocalSearchType(LocalSearchType.HILL_CLIMBING)));
        SolverFactory<TestdataHardSoftScoreSolution> solverFactory = SolverFactory.create(solverConfig);

        Solver<TestdataHardSoftScoreSolution> solver = solverFactory.buildSolver();
        ((DefaultSolver<TestdataHardSoftScoreSolution>) solver).setMonitorTagMap(Map.of("solver.id", "solveMetrics"));
        meterRegistry.publish(solver);
        TestdataHardSoftScoreSolution solution = new TestdataHardSoftScoreSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("none"), new TestdataValue("reward")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));
        AtomicInteger step = new AtomicInteger(-1);

        solver.addEventListener(event -> {
            meterRegistry.publish(solver);
            System.out.println(event.getNewBestScore());

            // This event listener is added before the best score event listener
            // so it is one step behind
            if (step.get() != -1) {
                assertThat(
                        meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".hard.score", "VALUE").intValue())
                                .isEqualTo(0);
            }
            if (step.get() == 0) {
                assertThat(
                        meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".soft.score", "VALUE").intValue())
                                .isEqualTo(0);
            } else if (step.get() == 1) {
                assertThat(
                        meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".soft.score", "VALUE").intValue())
                                .isEqualTo(1);
            } else if (step.get() == 2) {
                assertThat(
                        meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".soft.score", "VALUE").intValue())
                                .isEqualTo(2);
            }
            step.incrementAndGet();
        });
        solution = solver.solve(solution);

        assertThat(step.get()).isEqualTo(2);
        meterRegistry.publish(solver);
        assertThat(solution).isNotNull();
        assertThat(meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".hard.score", "VALUE").intValue())
                .isEqualTo(0);
        assertThat(meterRegistry.getMeasurement(SolverMetric.BEST_SCORE.getMeterId() + ".soft.score", "VALUE").intValue())
                .isEqualTo(2);
    }

    private static class SetTestdataEntityValueCustomPhaseCommand implements CustomPhaseCommand<TestdataHardSoftScoreSolution> {
        final TestdataEntity entity;
        final TestdataValue value;

        public SetTestdataEntityValueCustomPhaseCommand(TestdataEntity entity, TestdataValue value) {
            this.entity = entity;
            this.value = value;
        }

        @Override
        public void changeWorkingSolution(ScoreDirector<TestdataHardSoftScoreSolution> scoreDirector) {
            TestdataEntity workingEntity = scoreDirector.lookUpWorkingObject(entity);
            TestdataValue workingValue = scoreDirector.lookUpWorkingObject(value);

            scoreDirector.beforeVariableChanged(workingEntity, "value");
            workingEntity.setValue(workingValue);
            scoreDirector.afterVariableChanged(workingEntity, "value");
            scoreDirector.triggerVariableListeners();
        }
    }

    @Test
    void solveStepScoreMetrics() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataHardSoftScoreSolution.class, TestdataEntity.class);
        solverConfig.setScoreDirectorFactoryConfig(
                new ScoreDirectorFactoryConfig().withEasyScoreCalculatorClass(BestScoreMetricEasyScoreCalculator.class));
        solverConfig.setTerminationConfig(new TerminationConfig().withBestScoreLimit("0hard/3soft"));
        solverConfig.setMonitoringConfig(new MonitoringConfig()
                .withSolverMetricList(List.of(SolverMetric.STEP_SCORE)));

        TestdataHardSoftScoreSolution solution = new TestdataHardSoftScoreSolution("s1");
        TestdataEntity e1 = new TestdataEntity("e1");
        TestdataEntity e2 = new TestdataEntity("e2");
        TestdataEntity e3 = new TestdataEntity("e3");
        TestdataValue none = new TestdataValue("none");
        TestdataValue reward = new TestdataValue("reward");
        solution.setValueList(Arrays.asList(none, reward));
        solution.setEntityList(Arrays.asList(e1, e2, e3));

        solverConfig.setPhaseConfigList(List.of(
                // Force OptaPlanner to select "none" value which reward 0 soft
                new ConstructionHeuristicPhaseConfig()
                        .withConstructionHeuristicType(ConstructionHeuristicType.FIRST_FIT)
                        .withMoveSelectorConfigList(
                                List.of(new ChangeMoveSelectorConfig()
                                        .withFilterClass(NoneValueSelectionFilter.class))),
                // Then do a custom phase, to force certain steps to be taken
                new CustomPhaseConfig()
                        .withCustomPhaseCommands(
                                new SetTestdataEntityValueCustomPhaseCommand(e1, reward),
                                new SetTestdataEntityValueCustomPhaseCommand(e2, reward),
                                new SetTestdataEntityValueCustomPhaseCommand(e1, none),
                                new SetTestdataEntityValueCustomPhaseCommand(e1, reward),
                                new SetTestdataEntityValueCustomPhaseCommand(e3, reward))));
        SolverFactory<TestdataHardSoftScoreSolution> solverFactory = SolverFactory.create(solverConfig);

        Solver<TestdataHardSoftScoreSolution> solver = solverFactory.buildSolver();
        ((DefaultSolver<TestdataHardSoftScoreSolution>) solver).setMonitorTagMap(Map.of("solver.id", "solveMetrics"));
        AtomicInteger step = new AtomicInteger(-1);

        ((DefaultSolver<TestdataHardSoftScoreSolution>) solver)
                .addPhaseLifecycleListener(new PhaseLifecycleListenerAdapter<TestdataHardSoftScoreSolution>() {
                    @Override
                    public void stepEnded(AbstractStepScope<TestdataHardSoftScoreSolution> stepScope) {
                        super.stepEnded(stepScope);
                        meterRegistry.publish(solver);

                        // first 3 steps are construction heuristic steps and don't have a step score since it uninitialized
                        if (step.get() < 2) {
                            step.incrementAndGet();
                            return;
                        }

                        assertThat(
                                meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".hard.score", "VALUE")
                                        .intValue())
                                                .isEqualTo(0);

                        if (step.get() == 2) {
                            assertThat(
                                    meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE")
                                            .intValue())
                                                    .isEqualTo(0);
                        } else if (step.get() == 3) {
                            assertThat(
                                    meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE")
                                            .intValue())
                                                    .isEqualTo(1);
                        } else if (step.get() == 4) {
                            assertThat(
                                    meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE")
                                            .intValue())
                                                    .isEqualTo(2);
                        } else if (step.get() == 5) {
                            assertThat(
                                    meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE")
                                            .intValue())
                                                    .isEqualTo(1);
                        } else if (step.get() == 6) {
                            assertThat(
                                    meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE")
                                            .intValue())
                                                    .isEqualTo(2);
                        }
                        step.incrementAndGet();
                    }
                });
        solution = solver.solve(solution);

        assertThat(step.get()).isEqualTo(7);
        meterRegistry.publish(solver);
        assertThat(solution).isNotNull();
        assertThat(meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".hard.score", "VALUE").intValue())
                .isEqualTo(0);
        assertThat(meterRegistry.getMeasurement(SolverMetric.STEP_SCORE.getMeterId() + ".soft.score", "VALUE").intValue())
                .isEqualTo(3);
    }

    public static class ErrorThrowingEasyScoreCalculator implements EasyScoreCalculator<TestdataSolution, SimpleScore> {

        @Override
        public SimpleScore calculateScore(TestdataSolution testdataSolution) {
            throw new IllegalStateException("Thrown exception in constraint provider");
        }
    }

    @Test
    void solveMetricsError() {
        TestMeterRegistry meterRegistry = new TestMeterRegistry();
        Metrics.addRegistry(meterRegistry);

        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);

        solverConfig.setScoreDirectorFactoryConfig(
                new ScoreDirectorFactoryConfig().withEasyScoreCalculatorClass(ErrorThrowingEasyScoreCalculator.class));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);

        Solver<TestdataSolution> solver = solverFactory.buildSolver();
        ((DefaultSolver<TestdataSolution>) solver).setMonitorTagMap(Map.of("solver.id", "solveMetricsError"));
        meterRegistry.publish(solver);

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        meterRegistry.publish(solver);

        assertThatCode(() -> {
            solver.solve(solution);
        }).hasStackTraceContaining("Thrown exception in constraint provider");

        meterRegistry.getClock().addSeconds(1);
        meterRegistry.publish(solver);
        assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "ACTIVE_TASKS")).isZero();
        assertThat(meterRegistry.getMeasurement(SolverMetric.SOLVE_DURATION.getMeterId(), "DURATION")).isZero();
        assertThat(meterRegistry.getMeasurement(SolverMetric.ERROR_COUNT.getMeterId(), "COUNT")).isOne();
    }

    @Test
    void solveEmptyEntityList() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class)
                .withPhases(new CustomPhaseConfig().withCustomPhaseCommands(
                        scoreDirector -> fail("All phases should be skipped because there are no movable entities.")));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Collections.emptyList());

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void solveChainedEmptyEntityList() {
        SolverConfig solverConfig = PlannerTestUtils
                .buildSolverConfig(TestdataChainedSolution.class, TestdataChainedEntity.class)
                .withPhases(new CustomPhaseConfig().withCustomPhaseCommands(
                        scoreDirector -> fail("All phases should be skipped because there are no movable entities.")));
        SolverFactory<TestdataChainedSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataChainedSolution> solver = solverFactory.buildSolver();

        TestdataChainedSolution solution = new TestdataChainedSolution("s1");
        solution.setChainedAnchorList(Arrays.asList(new TestdataChainedAnchor("v1"), new TestdataChainedAnchor("v2")));
        solution.setChainedEntityList(Collections.emptyList());

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    // TODO https://issues.redhat.com/browse/PLANNER-1738
    @Test
    @Disabled("We currently don't support an empty value list yet if the entity list is not empty.")
    void solveEmptyValueList() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class);
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Collections.emptyList());
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isFalse();
    }

    @Test
    @Disabled("We currently don't support an empty value list yet if the entity list is not empty.")
    void solveChainedEmptyValueList() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataChainedSolution.class,
                TestdataChainedEntity.class);
        SolverFactory<TestdataChainedSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataChainedSolution> solver = solverFactory.buildSolver();

        TestdataChainedSolution solution = new TestdataChainedSolution("s1");
        solution.setChainedAnchorList(Collections.emptyList());
        solution.setChainedEntityList(Arrays.asList(new TestdataChainedEntity("e1"), new TestdataChainedEntity("e2")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isFalse();
    }

    @Test
    void solveEmptyEntityListAndEmptyValueList() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class)
                .withPhases(new CustomPhaseConfig().withCustomPhaseCommands(
                        scoreDirector -> fail("All phases should be skipped because there are no movable entities.")));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Collections.emptyList());
        solution.setEntityList(Collections.emptyList());

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void solvePinnedEntityList() {
        SolverConfig solverConfig = PlannerTestUtils
                .buildSolverConfig(TestdataPinnedSolution.class, TestdataPinnedEntity.class)
                .withPhases(new CustomPhaseConfig().withCustomPhaseCommands(
                        scoreDirector -> fail("All phases should be skipped because there are no movable entities.")));
        SolverFactory<TestdataPinnedSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataPinnedSolution> solver = solverFactory.buildSolver();

        TestdataPinnedSolution solution = new TestdataPinnedSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataPinnedEntity("e1", true, false),
                new TestdataPinnedEntity("e2", false, true)));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isFalse();
    }

    @Test
    void solveStopsWhenUninitialized() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        CustomPhaseConfig phaseConfig = new CustomPhaseConfig()
                .withCustomPhaseCommandClassList(Collections.singletonList(NoChangeCustomPhaseCommand.class));
        solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2"),
                new TestdataEntity("e3"), new TestdataEntity("e4"), new TestdataEntity("e5")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isFalse();
    }

    @Test
    void solveStopsWhenPartiallyInitialized() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataSolution.class, TestdataEntity.class);
        ConstructionHeuristicPhaseConfig phaseConfig = new ConstructionHeuristicPhaseConfig();
        // Run only 2 steps, although 5 are needed to initialize all entities
        phaseConfig.setTerminationConfig(new TerminationConfig().withStepCountLimit(2));
        solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1"), new TestdataEntity("e2"),
                new TestdataEntity("e3"), new TestdataEntity("e4"), new TestdataEntity("e5")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isFalse();
    }

    @Test
    @Timeout(60)
    void solveWithProblemChange() throws InterruptedException {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class);
        solverConfig.setDaemon(true); // Avoid terminating the solver too quickly.
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();
        final int valueCount = 4;
        TestdataSolution solution = TestdataSolution.generateSolution(valueCount, valueCount);

        AtomicReference<TestdataSolution> bestSolution = new AtomicReference<>();
        CountDownLatch solverStarted = new CountDownLatch(1);
        CountDownLatch solutionWithProblemChangeReceived = new CountDownLatch(1);
        solver.addEventListener(bestSolutionChangedEvent -> {
            solverStarted.countDown();
            if (bestSolutionChangedEvent.isEveryProblemChangeProcessed()) {
                TestdataSolution newBestSolution = bestSolutionChangedEvent.getNewBestSolution();
                if (newBestSolution.getValueList().size() == valueCount + 1) {
                    bestSolution.set(newBestSolution);
                    solutionWithProblemChangeReceived.countDown();
                }
            }
        });

        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.submit(() -> {
            solver.solve(solution);
        });

        solverStarted.await(); // Make sure we submit a ProblemChange only after the Solver started solving.
        solver.addProblemChange((workingSolution, problemChangeDirector) -> {
            problemChangeDirector.addProblemFact(new TestdataValue("added value"), solution.getValueList()::add);
        });

        solutionWithProblemChangeReceived.await();
        assertThat(bestSolution.get().getValueList()).hasSize(valueCount + 1);

        solver.terminateEarly();
        executorService.shutdown();
    }

    @Test
    void solveRepeatedlyBasicVariable(SoftAssertions softly) {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class);
        ConstructionHeuristicPhaseConfig phaseConfig = new ConstructionHeuristicPhaseConfig();
        // Run only 2 steps at a time, although 5 are needed to initialize all entities.
        int stepCountLimit = 2;
        phaseConfig.setTerminationConfig(new TerminationConfig().withStepCountLimit(stepCountLimit));
        solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        final int entityCount = 5;
        solution.setEntityList(IntStream.rangeClosed(1, entityCount)
                .mapToObj(id -> new TestdataEntity("e" + id))
                .collect(Collectors.toList()));

        Score<?> score = ScoreManager.create(solverFactory).updateScore(solution);
        assertThat(score.getInitScore()).isEqualTo(-entityCount);
        assertThat(score.isSolutionInitialized()).isFalse();

        // Keep restarting the solver until the solution is initialized.
        for (int initScore = -entityCount; initScore < 0; initScore += stepCountLimit) {
            softly.assertThat(solution.getScore().getInitScore()).isEqualTo(initScore);
            softly.assertThat(solution.getScore().isSolutionInitialized()).isFalse();
            solution = solver.solve(solution);
        }

        // Finally, the initScore is 0.
        softly.assertThat(solution.getScore().getInitScore()).isZero();
        softly.assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void solveRepeatedlyListVariable(SoftAssertions softly) {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(
                TestdataListSolution.class, TestdataListEntity.class, TestdataListValue.class);

        // Run only 7 steps at a time, although the total number of steps needed to complete CH is equal to valueCount.
        final int stepCountLimit = 7;
        ConstructionHeuristicPhaseConfig phaseConfig = new ConstructionHeuristicPhaseConfig();
        phaseConfig.setTerminationConfig(new TerminationConfig().withStepCountLimit(stepCountLimit));
        solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
        SolverFactory<TestdataListSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataListSolution> solver = solverFactory.buildSolver();

        final int valueCount = 24;
        TestdataListSolution solution = TestdataListSolution.generateUninitializedSolution(valueCount, 8);

        Score<?> score = ScoreManager.create(solverFactory).updateScore(solution);
        assertThat(score.getInitScore()).isEqualTo(-valueCount);
        assertThat(score.isSolutionInitialized()).isFalse();

        // Keep restarting the solver until the solution is initialized.
        for (int initScore = -valueCount; initScore < 0; initScore += stepCountLimit) {
            softly.assertThat(solution.getScore().getInitScore()).isEqualTo(initScore);
            softly.assertThat(solution.getScore().isSolutionInitialized()).isFalse();
            solution = solver.solve(solution);
        }

        // Finally, the initScore is 0.
        softly.assertThat(solution.getScore().getInitScore()).isZero();
        softly.assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void constructionHeuristicAllocateToValueFromQueue() {
        SolverConfig solverConfig = PlannerTestUtils.buildSolverConfig(TestdataSolution.class, TestdataEntity.class);
        ConstructionHeuristicPhaseConfig phaseConfig = new ConstructionHeuristicPhaseConfig()
                .withConstructionHeuristicType(ConstructionHeuristicType.ALLOCATE_TO_VALUE_FROM_QUEUE);
        solverConfig.setPhaseConfigList(Collections.singletonList(phaseConfig));
        SolverFactory<TestdataSolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataSolution> solver = solverFactory.buildSolver();

        TestdataSolution solution = new TestdataSolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setEntityList(Arrays.asList(new TestdataEntity("e1")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }

    @Test
    void defaultSolveWithMultipleGenuinePlanningEntities() {
        SolverConfig solverConfig = new SolverConfig()
                .withSolutionClass(TestdataMultiEntitySolution.class)
                .withEntityClasses(TestdataLeadEntity.class, TestdataHerdEntity.class)
                .withEasyScoreCalculatorClass(DummySimpleScoreEasyScoreCalculator.class)
                .withTerminationConfig(new TerminationConfig()
                        .withBestScoreLimit("0"));
        SolverFactory<TestdataMultiEntitySolution> solverFactory = SolverFactory.create(solverConfig);
        Solver<TestdataMultiEntitySolution> solver = solverFactory.buildSolver();

        TestdataMultiEntitySolution solution = new TestdataMultiEntitySolution("s1");
        solution.setValueList(Arrays.asList(new TestdataValue("v1"), new TestdataValue("v2")));
        solution.setLeadEntityList(Arrays.asList(new TestdataLeadEntity("lead1"), new TestdataLeadEntity("lead2")));
        solution.setHerdEntityList(Arrays.asList(new TestdataHerdEntity("herd1"), new TestdataHerdEntity("herd2")));

        solution = solver.solve(solution);
        assertThat(solution).isNotNull();
        assertThat(solution.getScore().isSolutionInitialized()).isTrue();
    }
}


text:
package com.vk.api.sdk.queries.groups;

import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.groups.responses.SearchResponse;

import java.util.Arrays;
import java.util.List;

/**
 * Query for Groups.search method
 */
public class GroupsSearchQuery extends AbstractQueryBuilder<GroupsSearchQuery, SearchResponse> {
    /**
     * Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
     *
     * @param client VK API client
     * @param actor  actor with access token
     * @param q      value of "q" parameter.
     */
    public GroupsSearchQuery(VkApiClient client, UserActor actor, String q) {
        super(client, "groups.search", SearchResponse.class);
        accessToken(actor.getAccessToken());
        q(q);
    }

    /**
     * Search query string.
     *
     * @param value value of "q" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    protected GroupsSearchQuery q(String value) {
        return unsafeParam("q", value);
    }

    /**
     * Community type. Possible values: "group, page, event."
     *
     * @param value value of "type" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery type(String value) {
        return unsafeParam("type", value);
    }

    /**
     * Country ID.
     *
     * @param value value of "country id" parameter. Minimum is 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery countryId(Integer value) {
        return unsafeParam("country_id", value);
    }

    /**
     * City ID. If this parameter is transmitted, country_id is ignored.
     *
     * @param value value of "city id" parameter. Minimum is 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery cityId(Integer value) {
        return unsafeParam("city_id", value);
    }

    /**
     * Only upcoming events will be returned.
     * Works with the "event" type only.
     *
     * @param value value of "future" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery future(Boolean value) {
        return unsafeParam("future", value);
    }

    /**
     * Set market
     *
     * @param value value of "market" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery market(Boolean value) {
        return unsafeParam("market", value);
    }

    /**
     * Sort order
     *
     * @param value value of "sort" parameter.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery sort(GroupsSearchSort value) {
        return unsafeParam("sort", value);
    }

    /**
     * Offset needed to return a specific subset of search results.
     *
     * @param value value of "offset" parameter. Minimum is 0.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery offset(Integer value) {
        return unsafeParam("offset", value);
    }

    /**
     * Number of communities to return.
     * Note that you can not receive more than first thousand of results, regardless of "count" and "offset" values.
     *
     * @param value value of "count" parameter. Maximum is 1000. Minimum is 0. By default 20.
     * @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
     */
    public GroupsSearchQuery count(Integer value) {
        return unsafeParam("count", value);
    }

    @Override
    protected GroupsSearchQuery getThis() {
        return this;
    }

    @Override
    protected List<String> essentialKeys() {
        return Arrays.asList("q", "access_token");
    }
}

redpajama_set_name: RedPajamaGithub


text:
interactive-transition
======================


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:padding="@dimen/standard_padding_small"
	android:layout_width="match_parent"
	android:layout_height="wrap_content">

	<android.support.design.widget.TextInputLayout
		android:layout_width="match_parent"
		android:layout_height="wrap_content">

		<EditText android:id="@+id/edit_query_name"
			android:hint="@string/name"
			style="@style/EditLine.Name" />

	</android.support.design.widget.TextInputLayout>

</FrameLayout>


text:
"use strict";
import { install, start, ChildProcess, FsPaths, InstallOpts, StartOpts } from "selenium-standalone";

// InstallOpts interface
let installOpts: InstallOpts = {
	baseURL: "baseURL",
	basePath: "basePath",
	version: "version",
	drivers: {
		chrome: {
			version: "chrome_version",
			arch: "ia32",
			baseURL: "baseURL a",
		},
		firefox: {
			version: "version",
			arch: "ia64",
			baseURL: "baseURL b",
		}
	},
	progressCb: (totalLength: number, progressLength: number, chunkLength: number) => {},
	logger: (message: string) => {},
	requestOpts: "requestOpts",
	cb: (error: Error) => {},
};

installOpts = {};

installOpts = {
	requestOpts: {
		agent: true,
		host: "host",
		family: 5
	},
};

// StartOpts interface
let startOpts: StartOpts = {
	basePath: "basePath",
	version: "version",
	drivers: {
		chrome: {
			version: "chrome_version",
			arch: "ia32",
			baseURL: "baseURL a",
		},
		firefox: {
			version: "version",
			arch: "ia64",
			baseURL: "baseURL b",
		}
	},
	seleniumArgs: ["bla", "foo"],
	javaArgs: ["bla", "foo"],
	spawnOptions: {},
	spawnCb: (selenium?: ChildProcess) => {},
	javaPath: "javaPath",
	requestOpts: "requestOpts",
	cb: (error: Error, child: ChildProcess) => {},
};
startOpts = {};

// FsPaths interface
let fsPaths: FsPaths = {
	bla: "foo",
	chrome: {
		installPath: "installPath",
		bla: "foo",
	},
	ie: {
		installPath: "installPath",
		bla: "foo",
	},
	edge: {
		installPath: "installPath",
		bla: "foo",
	},
	firefox: {
		installPath: "installPath",
		bla: "foo",
	},
	selenium: {
		installPath: "installPath",
		bla: "foo",
	},
};
fsPaths = {};

// start method
start(startOpts, (error: Error | null, selenium: ChildProcess) => {});
start((error: Error | null, selenium: ChildProcess) => {});

// install method
install(installOpts, (error: Error | undefined, fsPaths: FsPaths) => {});
install((error: Error | undefined, fsPaths: FsPaths) => {});


text:
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/ResetImageAttributeName.h>

namespace Aws
{
namespace EC2
{
namespace Model
{

  /*
  */
  class AWS_EC2_API ResetImageAttributeRequest : public EC2Request
  {
  public:
    ResetImageAttributeRequest();
    Aws::String SerializePayload() const override;

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline bool GetDryRun() const{ return m_dryRun; }

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }

    /*

Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    */
    inline ResetImageAttributeRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}

    /*

The ID of the AMI.

    */
    inline const Aws::String& GetImageId() const{ return m_imageId; }

    /*

The ID of the AMI.

    */
    inline void SetImageId(const Aws::String& value) { m_imageIdHasBeenSet = true; m_imageId = value; }

    /*

The ID of the AMI.

    */
    inline void SetImageId(Aws::String&& value) { m_imageIdHasBeenSet = true; m_imageId = value; }

    /*

The ID of the AMI.

    */
    inline void SetImageId(const char* value) { m_imageIdHasBeenSet = true; m_imageId.assign(value); }

    /*

The ID of the AMI.

    */
    inline ResetImageAttributeRequest& WithImageId(const Aws::String& value) { SetImageId(value); return *this;}

    /*

The ID of the AMI.

    */
    inline ResetImageAttributeRequest& WithImageId(Aws::String&& value) { SetImageId(value); return *this;}

    /*

The ID of the AMI.

    */
    inline ResetImageAttributeRequest& WithImageId(const char* value) { SetImageId(value); return *this;}

    /*

The attribute to reset (currently you can only reset the launch permission attribute).

    */
    inline const ResetImageAttributeName& GetAttribute() const{ return m_attribute; }

    /*

The attribute to reset (currently you can only reset the launch permission attribute).

    */
    inline void SetAttribute(const ResetImageAttributeName& value) { m_attributeHasBeenSet = true; m_attribute = value; }

    /*

The attribute to reset (currently you can only reset the launch permission attribute).

    */
    inline void SetAttribute(ResetImageAttributeName&& value) { m_attributeHasBeenSet = true; m_attribute = value; }

    /*

The attribute to reset (currently you can only reset the launch permission attribute).

    */
    inline ResetImageAttributeRequest& WithAttribute(const ResetImageAttributeName& value) { SetAttribute(value); return *this;}

    /*

The attribute to reset (currently you can only reset the launch permission attribute).

    */
    inline ResetImageAttributeRequest& WithAttribute(ResetImageAttributeName&& value) { SetAttribute(value); return *this;}

  private:
    bool m_dryRun;
    bool m_dryRunHasBeenSet;
    Aws::String m_imageId;
    bool m_imageIdHasBeenSet;
    ResetImageAttributeName m_attribute;
    bool m_attributeHasBeenSet;
  };

} // namespace Model
} // namespace EC2
} // namespace Aws


text:
/**
 * generated by Xtext 2.9.2
 */
package org.wso2.vihanga.example.student.scoping;

import org.wso2.vihanga.example.student.scoping.AbstractStudentScopeProvider;

/**
 * This class contains custom scoping description.
 *
 * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping
 * on how and when to use it.
 */
@SuppressWarnings("all")
public class StudentScopeProvider extends AbstractStudentScopeProvider {
}


text:
/// <reference path="module.ts" />

module mz {
    export function undefine(mod: string) {
        if (mod in mz.modules) {
            mz.modules[mod] = null;
            delete mz.modules[mod];
        }
    }

    export function define(ObjetoDefinido: Object): Object;
    export function define(Callback: Function): void;
    export function define(RequiredModules: string[], Callback: IModuleCallback): void;
    export function define(Module: string, ObjetoDefinido: Object): Object;
    export function define(Module: string, Callback: Function): void;
    export function define(Module: string, RequiredModules: string[], Callback: IModuleCallback): void;
    export function define() {
        var name = mz.buscarArgumentoTipo('string', arguments) || (mz.define.currentModule ? mz.define.currentModule.id : null) || null;
        var fn = mz.buscarArgumentoTipo('function', arguments) || null;
        var reqs = mz.buscarArgumentoTipo(Array, arguments) || null;

        var obj = !fn && arguments.length && typeof arguments[arguments.length - 1] == "object" && arguments[arguments.length - 1] || null;

        if (!fn && obj) {
            fn = obj;
        }

        var module = null;

        if (mz.define.currentModule && mz.define.currentModule.id == name) {
            module = mz.define.currentModule;
            mz.define.currentModule = null;
        } else {
            module = new mz.Module(name);
            if (obj) module.exports = obj;
        }

        mz.define.lastModule = module;

        if (name !== null) {
            if (name in mz.modules && mz.modules[name] !== module) {
                if ((<any>mz)._debug) debugger;
                throw "Ya está definido " + name;
            }

            mz.modules[name] = module;

            if (reqs && reqs.length) {
                var args = [];

                if (module.async) {
                    module.require(reqs, function (args) {
                        for (var i in reqs) {
                            if (reqs[i] == "exports")
                                arguments[i] = module.exports;
                            else if (reqs[i] == "require")
                                arguments[i] = module.require;
                        }

                        module.ModuleExports.set(fn, arguments);
                    });
                } else {
                    for (var i in reqs) {
                        if (reqs[i] == "exports") {
                            module.dependencias[reqs[i]] = args[i] = module.exports;
                        } else if (reqs[i] == "require")
                            module.dependencias[reqs[i]] = args[i] = module.require;
                        else
                            module.dependencias[reqs[i]] = args[i] = module.require(reqs[i]);
                    }

                    module.ModuleExports.set(fn, args);
                }
            } else {
                module.ModuleExports.set(fn, []);
            }
        } else {
            module.ModuleExports.set(fn, []);
        }

        return module.exports;

    }
    define.amd = {};
}

module mz.define {
    export var amd: any;
    export var lastModule: Module;
    export var currentModule: Module;
}

mz.globalContext.define = mz.define;


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

#include "ConfigView.h"
#include "SVGTranslator.h"
#include "SVGLoader.h"

#define kSVGMimeType "image/svg+xml"
#define kSVGName "SVG Image"

static const translation_format sInputFormats[] = {
	{
		SVG_IMAGE_FORMAT,
		B_TRANSLATOR_BITMAP,
		SVG_IN_QUALITY,
		SVG_IN_CAPABILITY,
		kSVGMimeType,
		kSVGName
	},
};

static const translation_format sOutputFormats[] = {
	{
		B_TRANSLATOR_BITMAP,
		B_TRANSLATOR_BITMAP,
		BITS_OUT_QUALITY,
		BITS_OUT_CAPABILITY,
		"image/x-be-bitmap",
		"Be Bitmap Format (NanoSVGTranslator)"
	},
};

static const TranSetting sDefaultSettings[] = {
	{B_TRANSLATOR_EXT_HEADER_ONLY, TRAN_SETTING_BOOL, false},
	{B_TRANSLATOR_EXT_DATA_ONLY, TRAN_SETTING_BOOL, false},
	{SVG_SETTING_SCALE, TRAN_SETTING_INT32, 10}
};

const uint32 kNumInputFormats = sizeof(sInputFormats)
	/ sizeof(translation_format);
const uint32 kNumOutputFormats = sizeof(sOutputFormats)
	/ sizeof(translation_format);
const uint32 kNumDefaultSettings = sizeof(sDefaultSettings)
	/ sizeof(TranSetting);

SVGTranslator::SVGTranslator()
	: BaseTranslator("SVG Images",
		"SVG image translator",
		SVG_TRANSLATOR_VERSION,
		sInputFormats, kNumInputFormats,
		sOutputFormats, kNumOutputFormats,
		"NanoSVGTranslator",
		sDefaultSettings, kNumDefaultSettings,
		B_TRANSLATOR_BITMAP, SVG_IMAGE_FORMAT)
{
}

SVGTranslator::~SVGTranslator()
{
}

status_t
SVGTranslator::DerivedIdentify(BPositionIO *stream,
	const translation_format *format, BMessage *ioExtension,
	translator_info *info, uint32 outType)
{
	if (outType != B_TRANSLATOR_BITMAP)
		return B_NO_TRANSLATOR;

	char svgData[256];
	ssize_t readedBytes = 255;
	readedBytes = stream->Read(svgData, 255);
	svgData[readedBytes] = 0;

	if(strncasecmp(svgData, "<?xml", 5) != 0
		&& strncasecmp(svgData, "<svg", 4) != 0) {
		return B_NO_TRANSLATOR;
	}

	if(strcasestr(svgData, "<svg") == NULL
		&& strcasestr(svgData, "<!DOCTYPE SVG") == NULL) {
		return B_NO_TRANSLATOR;
	}

	info->type = SVG_IMAGE_FORMAT;
	info->group = B_TRANSLATOR_BITMAP;
	info->quality = SVG_IN_QUALITY;
	info->capability = SVG_IN_CAPABILITY;
	strcpy(info->name, kSVGName);
	strcpy(info->MIME, kSVGMimeType);

	return B_OK;
}

status_t
SVGTranslator::DerivedTranslate(BPositionIO *source,
	const translator_info *info, BMessage *ioExtension,
	uint32 outType, BPositionIO *target, int32 baseType)
{
	if (outType != B_TRANSLATOR_BITMAP)
		return B_NO_TRANSLATOR;

	switch (baseType) {
		case 0:
		{
			if (outType != B_TRANSLATOR_BITMAP)
				return B_NO_TRANSLATOR;

			SVGLoader SVGFile(source);
			if (!SVGFile.IsParsed())
				return B_NO_TRANSLATOR;
			float scale = fSettings->SetGetInt32(SVG_SETTING_SCALE) / 10.0;
			return SVGFile.RenderImage(target, scale);
		}

		default:
			return B_NO_TRANSLATOR;
	}
}

status_t
SVGTranslator::DerivedCanHandleImageSize(float width, float height) const
{
	return B_OK;
}

BView *
SVGTranslator::NewConfigView(TranslatorSettings *settings)
{
	return new ConfigView(settings);
}

BTranslator *
make_nth_translator(int32 n, image_id you, uint32 flags, ...)
{
	if (n != 0)
		return NULL;

	return new SVGTranslator();
}


text:
# synstructure

[![Latest Version](https://img.shields.io/crates/v/synstructure.svg)](https://crates.io/crates/synstructure)
[![Documentation](https://docs.rs/synstructure/badge.svg)](https://docs.rs/synstructure)
[![Build Status](https://travis-ci.org/mystor/synstructure.svg?branch=master)](https://travis-ci.org/mystor/synstructure)
[![Rustc Version 1.31+](https://img.shields.io/badge/rustc-1.31+-lightgray.svg)](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018.html)

> NOTE: What follows is an exerpt from the module level documentation. For full
> details read the docs on [docs.rs](https://docs.rs/synstructure/)

This crate provides helper types for matching against enum variants, and
extracting bindings to each of the fields in the deriving Struct or Enum in
a generic way.

If you are writing a `#[derive]` which needs to perform some operation on
every field, then you have come to the right place!

# Example: `WalkFields`
### Trait Implementation
```rust
pub trait WalkFields: std::any::Any {
    fn walk_fields(&self, walk: &mut FnMut(&WalkFields));
}
impl WalkFields for i32 {
    fn walk_fields(&self, _walk: &mut FnMut(&WalkFields)) {}
}
```

### Custom Derive
```rust
#[macro_use]
extern crate synstructure;
#[macro_use]
extern crate quote;
extern crate proc_macro2;

fn walkfields_derive(s: synstructure::Structure) -> proc_macro2::TokenStream {
    let body = s.each(|bi| quote!{
        walk(#bi)
    });

    s.bound_impl(quote!(example_traits::WalkFields), quote!{
        fn walk_fields(&self, walk: &mut FnMut(&example_traits::WalkFields)) {
            match *self { #body }
        }
    })
}
decl_derive!([WalkFields] => walkfields_derive);

/*
 * Test Case
 */
fn main() {
    test_derive! {
        walkfields_derive {
            enum A<T> {
                B(i32, T),
                C(i32),
            }
        }
        expands to {
            #[allow(non_upper_case_globals)]
            const _DERIVE_example_traits_WalkFields_FOR_A: () = {
                extern crate example_traits;
                impl<T> example_traits::WalkFields for A<T>
                    where T: example_traits::WalkFields
                {
                    fn walk_fields(&self, walk: &mut FnMut(&example_traits::WalkFields)) {
                        match *self {
                            A::B(ref __binding_0, ref __binding_1,) => {
                                { walk(__binding_0) }
                                { walk(__binding_1) }
                            }
                            A::C(ref __binding_0,) => {
                                { walk(__binding_0) }
                            }
                        }
                    }
                }
            };
        }
    }
}
```

# Example: `Interest`
### Trait Implementation
```rust
pub trait Interest {
    fn interesting(&self) -> bool;
}
impl Interest for i32 {
    fn interesting(&self) -> bool { *self > 0 }
}
```

### Custom Derive
```rust
#[macro_use]
extern crate synstructure;
#[macro_use]
extern crate quote;
extern crate proc_macro2;

fn interest_derive(mut s: synstructure::Structure) -> proc_macro2::TokenStream {
    let body = s.fold(false, |acc, bi| quote!{
        #acc || example_traits::Interest::interesting(#bi)
    });

    s.bound_impl(quote!(example_traits::Interest), quote!{
        fn interesting(&self) -> bool {
            match *self {
                #body
            }
        }
    })
}
decl_derive!([Interest] => interest_derive);

/*
 * Test Case
 */
fn main() {
    test_derive!{
        interest_derive {
            enum A<T> {
                B(i32, T),
                C(i32),
            }
        }
        expands to {
            #[allow(non_upper_case_globals)]
            const _DERIVE_example_traits_Interest_FOR_A: () = {
                extern crate example_traits;
                impl<T> example_traits::Interest for A<T>
                    where T: example_traits::Interest
                {
                    fn interesting(&self) -> bool {
                        match *self {
                            A::B(ref __binding_0, ref __binding_1,) => {
                                false ||
                                    example_traits::Interest::interesting(__binding_0) ||
                                    example_traits::Interest::interesting(__binding_1)
                            }
                            A::C(ref __binding_0,) => {
                                false ||
                                    example_traits::Interest::interesting(__binding_0)
                            }
                        }
                    }
                }
            };
        }
    }
}
```

For more example usage, consider investigating the `abomonation_derive` crate,
which makes use of this crate, and is fairly simple.


text:
|          |                                         |
| -------- | --------------------------------------- |
| title    | Amazon Route 53                         |
| status   | 90                                      |
| section  | IaaS Management from HPC to hypervisors |
| keywords | IaaS Management from HPC to hypervisors |

Amazon Route 53 is a DNS (Domain Name System) service that gives
developers and businesses a reliable way to route end users to
Internet applications. The number 53 refers to TCP or UDP port 53,
where DNS server requests are addressed [@www-ar53].

When using Route 53 as your DNS provider, in case of a recursion, the
query of fetching an IP address (of a website or application) always
goes to the closest server location to reduce query latency. The Route
53 server returns the IP address enabling the browser to load the
website or application. Route 53 can also be used for registering
domain names and arranging DNS health checks to monitor the
server [@www-amar53].


text:
package ch.liquidmind.inflection.bidir;

import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class BidirectionalMap< K extends Object, V extends Object > extends BidirectionalDelegate implements Map< K, V >
{
	public BidirectionalMap( Object owner, String opposingPropertyName, Object target )
	{
		super( owner, opposingPropertyName, target );
	}

	@SuppressWarnings( "unchecked" )
	@Override
	public Map< K, V > getTarget()
	{
		return (Map< K, V >)super.getTarget();
	}

	@Override
	public int size()
	{
		return getTarget().size();
	}

	@Override
	public boolean isEmpty()
	{
		return getTarget().isEmpty();
	}

	@Override
	public boolean containsKey( Object key )
	{
		return getTarget().containsKey( key );
	}

	@Override
	public boolean containsValue( Object value )
	{
		return getTarget().containsValue( value );
	}

	@Override
	public V get( Object key )
	{
		return getTarget().get( key );
	}

	@Override
	public V put( K key, V value )
	{
		setOpposing( getTarget().get( key ), getOwner(), null );
		setOpposing( value, null, getOwner() );

		return getTarget().put( key, value );
	}

	@Override
	public V remove( Object key )
	{
		setOpposing( getTarget().get( key ), getOwner(), null );

		return getTarget().remove( key );
	}

	@Override
	public void putAll( Map< ? extends K, ? extends V > m )
	{
		for ( Map.Entry< ?, ? > entry : m.entrySet() )
		{
			setOpposing( getTarget().get( entry.getKey() ), getOwner(), null );
			setOpposing( entry.getValue(), null, getOwner() );
		}

		getTarget().putAll( m );
	}

	@Override
	public void clear()
	{
		for ( Object value : getTarget().values() )
			setOpposing( value, getOwner(), null );

		getTarget().clear();
	}

	@Override
	public Set< K > keySet()
	{
		return getTarget().keySet();
	}

	@Override
	public Collection< V > values()
	{
		return getTarget().values();
	}

	@Override
	public Set< java.util.Map.Entry< K, V > > entrySet()
	{
		return getTarget().entrySet();
	}
}


text:
package:
	python scripts/package.py
	pip install -e .

pypi: package
	python setup.py sdist bdist_wheel upload

publish: package pypi


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clipToPadding="false"
        android:paddingBottom="@dimen/listview_bottom_padding"
        android:paddingLeft="20dp"
        android:paddingRight="20dp" />

    <TextView
        android:id="@android:id/empty"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:paddingTop="30dip"
        android:text="@string/nohistory"
        android:textSize="20sp" />

</LinearLayout>


text:
function create_alert(level, message) {
    $('#alert_area').append('
<button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>' + message + '
');
}

function set_and_change(selector, value) {
    $(selector).prop('checked', value).trigger('change');
}

function flicker(selector, count) {
    $(selector).addClass('flicker')
        .delay(100)
        .queue(function() {
            $(this).removeClass('flicker');
            $(this).dequeue();
        })
        .delay(100)
        .queue(function() {
            if(count > 1) {
                flicker(selector, count - 1);
            } else {
                flick_out(selector);
            }
            $(this).dequeue();
        });
}

function flick_out(selector) {
    $(selector).addClass('flicker')
        .delay(100)
        .queue(function() {
            $(this).addClass('flicker-out');
            $(this).dequeue();
        }).delay(1000)
        .queue(function() {
            $(this).removeClass('flicker').removeClass('flicker-out');
            $(this).dequeue();
        })
}

function replace_via_ajax(selector, path) {
    $.getJSON( path, function( data ) {
        $(selector).replaceWith(data.html);
        flicker(selector, 3);
    });
}

function process_results(data) {
    if(typeof data.results === 'undefined' || data.results.length == 0) {
        create_alert('warning', data.message);
    } else {
        create_alert('info', data.message);
        for(var key in data.results) {
            var item = data.results[key];
            replace_via_ajax('#' + item.css_id, item.path);
        }
    }
}

function add_tag_magic(selector) {
    $(selector).tokenfield({
        typeahead: [
            {
                hint: true,
                highlight: true
            },
            {
                source: suggestions.ttAdapter()
            }
        ],
        showAutocompleteOnFocus: true
    });
}

$(document).ready(function(){

    $('.message_train_conversation input[type="checkbox"]').change(function(event) {
        if (event.target.checked) {
            //Checkbox has been checked
            $(this).parents('.message_train_conversation').addClass('selected');
        } else {
            //Checkbox has been unchecked
            $(this).parents('.message_train_conversation').removeClass('selected');
        }
    });

    $('#check_all').change(function(event) {
        if (event.target.checked) {
            set_and_change( '.message_train_conversation input[type="checkbox"]', true);
        } else {
            set_and_change( '.message_train_conversation input[type="checkbox"]', false);
        }
    });

    $('#box-actions .check').click(function(event) {
        event.preventDefault();
        selector = $(this).data('selector');
        set_and_change( '.message_train_conversation input[type="checkbox"]', false);
        if(selector == '.message_train_conversation') {
            $('#check_all').prop('checked', true);
        } else {
            $('#check_all').prop('checked', false);
        }
        if(selector != '') {
            set_and_change( selector + ' input[type="checkbox"]', true);
        }
    });

    $('#box-actions .mark-all-link').click(function(event) {
        event.preventDefault();
        $('#spinner').removeClass('hide');
        mark_to_set = $(this).data('mark');
        if(mark_to_set == 'ignore' || mark_to_set == 'unignore') {
            $('input[name="_method"]').val('delete');
        } else {
            $('input[name="_method"]').val('put');
        }
        $('input[name="mark_to_set"]').val(mark_to_set);
        $('#box').submit();
    });

    $('#box').on('ajax:success', function (e, data, status, xhr) {
        $('#spinner').addClass('hide');
        process_results(data);
    }).on('ajax:error', function (e, data, status, xhr) {
        create_alert('danger', data.responseJSON.message);
    });

    $('#box #message_train_messages .read').each(function(e){
        $(this).find('.collapse').collapse('hide');
    });

    $('.recipient-input').each(function() {
        add_tag_magic('#' + $(this).attr('id'));
    });

    $('#attachment_preview').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget); // Button that triggered the modal
        var src = button.data('src'); // Extract info from data-* attributes
        var original = button.data('original');
        var text = button.data('text');
        var modal = $(this);
        modal.find('#image_placeholder').html('')
    });
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Determine Whether a Component Handles Container Attributes (Qi and Karma)</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Spirit 2.5.7">
<link rel="up" href="../customize.html" title="Customization of Spirit's Attribute Handling">
<link rel="prev" href="is_string.html" title="Determine if a Type Should be Treated as a String (Qi and Karma)">
<link rel="next" href="transform.html" title="Transform an Attribute to a Different Type (Qi and Karma)">

Home
Libraries
People
FAQ
More

Determine
        Whether a Component Handles Container Attributes (Qi and Karma)

          handles_container

          The template handles_container
          is a template meta-function used as an attribute customization point. It
          is invoked by the Qi Sequence
          (>>) and Karma
          Sequence (<<) operators in order to determine
          whether a sequence element (component) handles container attributes directly.
          This customization point is invoked for container attributes only, and
          only if the sequence is compatible with the supplied container attribute.

          If a component, which is part of a sequence is able to handle a container
          attribute directly, the sequence passes the attribute to the component
          without any additional action. In Spirit.Qi the component
          uses the attribute to directly store all matched attributes. In Spirit.Karma
          the generator component extracts the attributes needed for output generation
          directly from this attribute.

          If a component, which is part of a sequence is not able to handle container
          attributes, in Spirit.Qi the sequence passes a new
          instance of the container attributes' value_type
          to the parser component, inserting the result into the attribute on behalf
          of the parser component. In Spirit.Karma the sequence
          extracts the next container element on behalf of the generator component
          and passing it the extracted value.

          Header

#include <boost/spirit/home/support/handles_container.hpp>

          Also, see Include Structure.

Note

            This header file does not need to be included directly by any user program
            as it is normally included by other Spirit header files relying on its
            content.

          Namespace

<colgroup><col></colgroup>

                    Name

                    boost::spirit::traits

          Synopsis

template <
    typename Component, typename Attribute, typename Context,
    typename Iterator, typename Enable>
struct handles_container
{
    <unspecified>;
};

          Template
          parameters

<colgroup>
<col>
<col>
<col>
</colgroup>

                    Parameter

                    Description

                    Default

                    Component

                    The component type Component
                    which needs to be tested whether it handles container attributes
                    directly.

                    none

                    Attribute

                    The attribute type Attribute
                    as passed to the sequence operator.

                    none

                    Context

                    This is the type of the current component execution context.

                    unused_type

                    Iterator

                    The type, Iterator
                    is the type of the iterators used to invoke the component.

                    unused_type

                    Enable

                    Helper template parameter usable to selectively enable or disable
                    certain specializations of is_container
                    utilizing SFINAE (i.e. boost::enable_if
                    or boost::disable_if).

                    void

Notation

Component

                A component type to be tested whether it directly handles container
                attributes in the context of sequences.

Attribute

                A container attribute type as passed to the sequence.

T1, T2, ...

                Arbitrary types

          Expression
          Semantics

<colgroup>
<col>
<col>
</colgroup>

                    Expression

                    Semantics

                    handles_container<Component, Attribute>::type

                    Result of the metafunction that evaluates to mpl::true_
                    if a given component type Component,
                    handles container attributes directly, mpl::false_
                    otherwise. Generally, any implementation of handles_container
                    needs to behave as if if was a MPL
                    Boolean Constant.

          Predefined
          Specializations

          Spirit predefines specializations
          of this customization point for several types. The following table lists
          those types together with the conditions for which the corresponding specializations
          will evaluate to mpl::true_ (see MPL
          Boolean Constant):

<colgroup>
<col>
<col>
</colgroup>

                    Template Parameters

                    Semantics

                    Component, Attribute

                    Always returns mpl::false_
                    (the default).

                    rule<Iterator,
                    T1,
                    T2,
                    T3,
                    T4>,
                    Attribute

                    Returns is_container<A>, where A
                    is the attribute exposed by the rule (Spirit.Qi
                    and Spirit.Karma).

                    grammar<Iterator,
                    T1,
                    T2,
                    T3,
                    T4>,
                    Attribute

                    Returns is_container<A>, where A
                    is the attribute exposed by the grammar (Spirit.Qi
                    and Spirit.Karma).

          When
          to implement

          The customization point handles_container
          needs to be implemented for a specific type whenever this type directly
          handles container attributes. It is applicable for parsers (Spirit.Qi)
          and generators (Spirit.Karma). It will have to be
          implemented under rare circumstances only.

Copyright © 2001-2011 Joel de Guzman, Hartmut Kaiser

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
<?php

namespace Fountain\Connection;

/**
 * @author Nikita Gusakov <dev@nkt.me>
 */
interface Statement
{
    /**
     * @param mixed $parameter Parameter identifier.
     * @param mixed $value     The value to bind to the parameter.
     * @param mixed $type      The type for binding value.
     */
    public function bindValue($parameter, $value, $type = null);

    /**
     * Executes a prepared statement
     *
     * @param array|null $parameters
     *
     * @return Statement
     */
    public function execute($parameters = null);

    /**
     * @return mixed
     */
    public function fetchAll();
}


text:
'''
Created on 3 mars 2017

@author: Jacky
'''

import logging
from time import sleep

from django.apps import AppConfig

from ArkDiscordBot.discord.bot_base import DiscordBot
from ark_supervisor.rcon.connection import Rcon

logger = logging.getLogger('BOT.{}'.format(__name__))

ark_connection = Rcon()
bot = DiscordBot(pm_help=True)

# Add all commands
from ArkDiscordBot.bot_commands import *

# Add all tasks
from ArkDiscordBot.tasks import *

class MyAppConfig(AppConfig):
    name = 'ArkDiscordBot'
    verbose_name = "ArkDiscordBot"

    def ready(self):
        while True:
                try:
                    bot.run()
                except Exception as e:
                    logger.exception('Discord bot error !')
                    bot.logout()
                    bot.http.recreate()
                    sleep(3)


text:
"use strict"

const ruleMessages = require("../../utils/ruleMessages")
const validateOptions = require("../../utils/validateOptions")
const whitespaceChecker = require("../../utils/whitespaceChecker")
const functionCommaSpaceChecker = require("../functionCommaSpaceChecker")

const ruleName = "function-comma-space-before"

const messages = ruleMessages(ruleName, {
  expectedBefore: () => "Expected single space before \",\"",
  rejectedBefore: () => "Unexpected whitespace before \",\"",
  expectedBeforeSingleLine: () => "Expected single space before \",\" in a single-line function",
  rejectedBeforeSingleLine: () => "Unexpected whitespace before \",\" in a single-line function",
})

const rule = function (expectation) {
  const checker = whitespaceChecker("space", expectation, messages)
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: expectation,
      possible: [
        "always",
        "never",
        "always-single-line",
        "never-single-line",
      ],
    })
    if (!validOptions) {
      return
    }

    functionCommaSpaceChecker({
      root,
      result,
      locationChecker: checker.before,
      checkedRuleName: ruleName,
    })
  }
}

rule.ruleName = ruleName
rule.messages = messages
module.exports = rule


text:
CREATE TABLE deployment_hook(
    id uuid PRIMARY KEY,
    created_at timestamp without time zone NOT NULL,
    deployment_version text NOT NULL,
    hooks jsonb NOT NULL,
    app_id uuid NOT NULL REFERENCES app(id),
    is_last_deployment boolean NOT NULL DEFAULT false
);


text:
<?php

namespace SONUser\Controller;

use Zend\Mvc\Controller\AbstractActionController,
    Zend\View\Model\ViewModel;
use Zend\Authentication\AuthenticationService,
    Zend\Authentication\Storage\Session as SessionStorage;
use SONUser\Form\Login as LoginForm;

/**
 * Description of AuthController
 *
 * @author velho
 */
class AuthController extends AbstractActionController {

    public function indexAction() {
        $form = new LoginForm;
        $error = false;
        $request = $this->getRequest();

        if ($request->isPost()) {

            $form->setData($request->getPost());
            if ($form->isValid()) {

                $data = $request->getPost()->toArray();

                //criando storage para gravar sessao da autenticação
                $sessionStorage = new SessionStorage("SONUser");

                $auth = new AuthenticationService;
                $auth->setStorage($sessionStorage); //definindo o sessionstprage para auth

                $authAdapter = $this->getServiceLocator()->get('SONUser\Auth\Adapter');
                $authAdapter->setUsername($data['email']);
                $authAdapter->setPassword($data['password']);

                $result = $auth->authenticate($authAdapter);

                if ($result->isValid()) {
                /*
                      $user = $auth->getIdentity();
                      $user = $user['user'];
                      $sessionStorage->write($user, NULL);
                  */

                  $sessionStorage->write($auth->getIdentity()['user'], null);

                    return $this->redirect()->toRoute('sonuser-admin/default', array('controller' => 'users'));
                } else
                    $error = true;
            }
        }
        return  new ViewModel(array('form' => $form, 'error'=>$error));
    }

    public function logoutAction(){
        $auth = new AuthenticationService;
        $auth->setStorage(new SessionStorage("SONUser"));
        $auth->clearIdentity();

        return $this->redirect()->toRoute("sonuser-auth");
    }

}


text:
package org.lightadmin.jhipster.config;

import org.lightadmin.jhipster.aop.logging.LoggingAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Profile;

@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {

    @Bean
    @Profile(Constants.SPRING_PROFILE_DEVELOPMENT)
    public LoggingAspect loggingAspect() {
        return new LoggingAspect();
    }
}


text:
package com.dslplatform.client.json.Point;

import com.dslplatform.client.JsonSerialization;
import com.dslplatform.patterns.Bytes;
import java.io.IOException;

public class OneSetOfOnePointsDefaultValueTurtle {
	private static JsonSerialization jsonSerialization;

	@org.junit.BeforeClass
	public static void initializeJsonSerialization() throws IOException {
		jsonSerialization = com.dslplatform.client.StaticJson.getSerialization();
	}

	@org.junit.Test
	public void testDefaultValueEquality() throws IOException {
		final java.util.Set<java.awt.Point> defaultValue = new java.util.HashSet<java.awt.Point>(0);
		final Bytes defaultValueJsonSerialized = jsonSerialization.serialize(defaultValue);
		final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, defaultValueJsonSerialized.content, defaultValueJsonSerialized.length);
		final java.util.Set<java.awt.Point> defaultValueJsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
		com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(defaultValue, defaultValueJsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue1Equality() throws IOException {
		final java.util.Set<java.awt.Point> borderValue1 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point()));
		final Bytes borderValue1JsonSerialized = jsonSerialization.serialize(borderValue1);
		final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue1JsonSerialized.content, borderValue1JsonSerialized.length);
		final java.util.Set<java.awt.Point> borderValue1JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
		com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue1, borderValue1JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue2Equality() throws IOException {
		final java.util.Set<java.awt.Point> borderValue2 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point(0, 1000000000)));
		final Bytes borderValue2JsonSerialized = jsonSerialization.serialize(borderValue2);
		final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue2JsonSerialized.content, borderValue2JsonSerialized.length);
		final java.util.Set<java.awt.Point> borderValue2JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
		com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue2, borderValue2JsonDeserialized);
	}

	@org.junit.Test
	public void testBorderValue3Equality() throws IOException {
		final java.util.Set<java.awt.Point> borderValue3 = new java.util.HashSet<java.awt.Point>(java.util.Arrays.asList(new java.awt.Point(), new java.awt.Point(Integer.MIN_VALUE, Integer.MIN_VALUE), new java.awt.Point(Integer.MAX_VALUE, Integer.MAX_VALUE), new java.awt.Point(0, -1000000000), new java.awt.Point(0, 1000000000)));
		final Bytes borderValue3JsonSerialized = jsonSerialization.serialize(borderValue3);
		final java.util.List<java.awt.Point> deserializedTmpList = jsonSerialization.deserializeList(java.awt.Point.class, borderValue3JsonSerialized.content, borderValue3JsonSerialized.length);
		final java.util.Set<java.awt.Point> borderValue3JsonDeserialized = deserializedTmpList == null ? null : new java.util.HashSet<java.awt.Point>(deserializedTmpList);
		com.dslplatform.ocd.javaasserts.PointAsserts.assertOneSetOfOneEquals(borderValue3, borderValue3JsonDeserialized);
	}
}