text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.config.materials.dependency.DependencyMaterial;
import com.thoughtworks.go.config.materials.git.GitMaterial;
import com.thoughtworks.go.config.materials.mercurial.HgMaterial;
import com.thoughtworks.go.config.materials.perforce.P4Material;
import com.thoughtworks.go.config.materials.svn.SvnMaterial;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.feed.Author;
import com.thoughtworks.go.domain.feed.FeedEntries;
import com.thoughtworks.go.domain.feed.stage.StageFeedEntry;
import com.thoughtworks.go.domain.materials.Material;
import com.thoughtworks.go.domain.materials.Modification;
import com.thoughtworks.go.dto.DurationBean;
import com.thoughtworks.go.fixture.PipelineWithMultipleStages;
import com.thoughtworks.go.helper.*;
import com.thoughtworks.go.presentation.pipelinehistory.StageHistoryEntry;
import com.thoughtworks.go.presentation.pipelinehistory.StageHistoryPage;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.dao.DatabaseAccessHelper;
import com.thoughtworks.go.server.dao.JobInstanceDao;
import com.thoughtworks.go.server.dao.PipelineSqlMapDao;
import com.thoughtworks.go.server.dao.StageDao;
import com.thoughtworks.go.server.domain.StageIdentity;
import com.thoughtworks.go.server.domain.StageStatusListener;
import com.thoughtworks.go.server.domain.Username;
import com.thoughtworks.go.server.materials.DependencyMaterialUpdateNotifier;
import com.thoughtworks.go.server.messaging.GoMessageListener;
import com.thoughtworks.go.server.messaging.JobResultMessage;
import com.thoughtworks.go.server.messaging.JobResultTopic;
import com.thoughtworks.go.server.persistence.MaterialRepository;
import com.thoughtworks.go.server.scheduling.ScheduleHelper;
import com.thoughtworks.go.server.service.result.HttpOperationResult;
import com.thoughtworks.go.server.transaction.TransactionSynchronizationManager;
import com.thoughtworks.go.server.transaction.TransactionTemplate;
import com.thoughtworks.go.server.ui.StageSummaryModels;
import com.thoughtworks.go.server.util.Pagination;
import com.thoughtworks.go.util.GoConfigFileHelper;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.ReflectionUtil;
import com.thoughtworks.go.util.TimeProvider;
import com.thoughtworks.go.utils.Assertions;
import com.thoughtworks.go.utils.Timeout;
import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.BooleanSupplier;

import static com.thoughtworks.go.domain.JobResult.Passed;
import static com.thoughtworks.go.helper.BuildPlanMother.withBuildPlans;
import static com.thoughtworks.go.helper.JobInstanceMother.building;
import static com.thoughtworks.go.helper.JobInstanceMother.completed;
import static com.thoughtworks.go.helper.ModificationsMother.checkinWithComment;
import static com.thoughtworks.go.helper.ModificationsMother.modifyOneFile;
import static com.thoughtworks.go.util.DataStructureUtils.a;
import static com.thoughtworks.go.util.SystemUtil.currentWorkingDirectory;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:/applicationContext-global.xml",
        "classpath:/applicationContext-dataLocalAccess.xml",
        "classpath:/testPropertyConfigurer.xml",
        "classpath:/spring-all-servlet.xml",
})
public class StageServiceIntegrationTest {
    @Autowired private JobInstanceDao jobInstanceDao;
    @Autowired private StageService stageService;
    @Autowired private AgentService agentService;
    @Autowired private StageDao stageDao;
    @Autowired private PipelineSqlMapDao pipelineDao;
	@Autowired private DatabaseAccessHelper dbHelper;
	@Autowired private ScheduleHelper scheduleHelper;
    @Autowired private ScheduleService scheduleService;
    @Autowired private GoConfigDao goConfigDao;
    @Autowired private JobResultTopic jobResultTopic;
    @Autowired private TransactionTemplate transactionTemplate;
    @Autowired private TransactionSynchronizationManager transactionSynchronizationManager;
    @Autowired private MaterialRepository materialRepository;
    @Autowired private ConfigDbStateRepository configDbStateRepository;
    @Autowired private GoConfigService goConfigService;
    @Autowired private ChangesetService changesetService;
    @Autowired private GoCache goCache;
    @Autowired private InstanceFactory instanceFactory;
    @Autowired private DependencyMaterialUpdateNotifier notifier;
    @Rule
    public final TemporaryFolder temporaryFolder = new TemporaryFolder();

    private static final String PIPELINE_NAME = "mingle";
    private static final String STAGE_NAME = "dev";
    private JobInstance job;
    private static final String UUID = "uuid";
    private Pipeline savedPipeline;
    private PipelineConfig pipelineConfig;
    private Stage stage;
    private GoConfigFileHelper configFileHelper = new GoConfigFileHelper();
    private PipelineWithMultipleStages fixture;
    private String md5 = "md5-test";
    private JobState receivedState;
    private JobResult receivedResult;
    private StageResult receivedStageResult;

    @Before
    public void setUp() throws Exception {
        dbHelper.onSetUp();
        pipelineConfig = PipelineMother.withSingleStageWithMaterials(PIPELINE_NAME, STAGE_NAME, withBuildPlans("unit", "dev", "blah"));
        pipelineConfig.getFirstStageConfig().setFetchMaterials(false);
        pipelineConfig.getFirstStageConfig().setCleanWorkingDir(true);
        configFileHelper.usingCruiseConfigDao(goConfigDao);
        configFileHelper.onSetUp();
        configFileHelper.addPipeline(PIPELINE_NAME, STAGE_NAME);
        savedPipeline = scheduleHelper.schedule(pipelineConfig, BuildCause.createWithModifications(modifyOneFile(pipelineConfig), ""), GoConstants.DEFAULT_APPROVED_BY);
        stage = savedPipeline.getStages().first();
        job = stage.getJobInstances().first();
        job.setAgentUuid(UUID);
        jobInstanceDao.updateAssignedInfo(job);
        AgentIdentifier agentIdentifier = new AgentIdentifier("localhost", "127.0.0.1", UUID);
        agentService.updateRuntimeInfo(new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie"));
        receivedState = null;
        receivedResult = null;
        receivedStageResult = null;
        notifier.disableUpdates();
    }

    @After
    public void teardown() throws Exception {
        if (fixture != null) {
            fixture.onTearDown();
        }
        dbHelper.onTearDown();
        configFileHelper.onTearDown();
        notifier.enableUpdates();
    }

    @Test
    public void shouldPostAllMessagesAfterTheDatabaseIsUpdatedWhenCancellingAStage() {
        jobResultTopic.addListener(new GoMessageListener<JobResultMessage>() {
            @Override
            public void onMessage(JobResultMessage message) {
                JobIdentifier jobIdentifier = message.getJobIdentifier();
                JobInstance instance = jobInstanceDao.mostRecentJobWithTransitions(jobIdentifier);
                receivedState = instance.getState();
                receivedResult = instance.getResult();
            }
        });
        stageService.addStageStatusListener(new StageStatusListener() {
            @Override
            public void stageStatusChanged(Stage stage) {
                Stage retrievedStage = stageDao.stageById(stage.getId());
                receivedStageResult = retrievedStage.getResult();
            }
        });
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stage, null);
            }
        });

        Assertions.waitUntil(Timeout.TEN_SECONDS, new BooleanSupplier() {
            @Override
            public boolean getAsBoolean() {
                return receivedResult != null && receivedState != null && receivedStageResult!=null;
            }
        });
        assertThat(receivedState, is(JobState.Completed));
        assertThat(receivedResult, is(JobResult.Cancelled));
        assertThat(receivedStageResult, is(StageResult.Cancelled));

    }

    @Test
    public void shouldReturnFalseWhenAllStagesAreCompletedInAGivenPipeline() throws Exception {
        fixture = new PipelineWithMultipleStages(4, materialRepository, transactionTemplate, temporaryFolder);
        fixture.usingConfigHelper(configFileHelper).usingDbHelper(dbHelper).onSetUp();
        Pipeline pipeline = fixture.createdPipelineWithAllStagesPassed();
        assertThat(stageService.isAnyStageActiveForPipeline(pipeline.getIdentifier()), is(false));
    }

    @Test
    public void shouldReturnTrueIfAnyStageIsBuildingInAGivenPipeline() throws Exception {
        fixture = new PipelineWithMultipleStages(4, materialRepository, transactionTemplate, temporaryFolder);
        fixture.usingConfigHelper(configFileHelper).usingDbHelper(dbHelper).onSetUp();

        Pipeline pipeline = fixture.createPipelineWithFirstStageAssigned();
        assertThat(stageService.isAnyStageActiveForPipeline(pipeline.getIdentifier()), is(true));
    }

    @Test
    public void testShouldReturnTrueIfAStageOfAPipelineHasBeenScheduked() throws Exception {
        fixture = new PipelineWithMultipleStages(3, materialRepository, transactionTemplate, temporaryFolder);
        fixture.usingConfigHelper(configFileHelper).usingDbHelper(dbHelper).onSetUp();
        Pipeline pipeline = fixture.createPipelineWithFirstStageScheduled();
        assertThat(stageService.isAnyStageActiveForPipeline(pipeline.getIdentifier()), is(true));
    }

    @Test
    public void shouldReturnStageWithSpecificCounter() {
        Stage firstStage = savedPipeline.getStages().first();
        Stage newInstance = instanceFactory.createStageInstance(pipelineConfig.first(), new DefaultSchedulingContext(
                "anonymous"), md5, new TimeProvider());
        Stage newSavedStage = stageService.save(savedPipeline, newInstance);

        Stage latestStage = stageService.findStageWithIdentifier(
                new StageIdentifier(CaseInsensitiveString.str(pipelineConfig.name()), null, savedPipeline.getLabel(), firstStage.getName(), String.valueOf(newSavedStage.getCounter())));
        assertThat(latestStage, is(newSavedStage));

    }

    @Test
    public void shouldReturnStageWithSpecificCounter_findStageWithIdentifier() {
        Stage newInstance = instanceFactory.createStageInstance(pipelineConfig.first(), new DefaultSchedulingContext("anonymous"), md5, new TimeProvider());
        Stage newSavedStage = stageService.save(savedPipeline, newInstance);

        StageIdentifier identifier = newSavedStage.getIdentifier();
        Stage latestStage = stageService.findStageWithIdentifier(identifier.getPipelineName(), identifier.getPipelineCounter(), identifier.getStageName(), identifier.getStageCounter(), "admin", new HttpOperationResult());

        assertThat(latestStage, is(newSavedStage));
    }

    @Test
    public void shouldReturnTrueIfStageIsActive() {
        savedPipeline.getStages().first();
        Stage newInstance = instanceFactory.createStageInstance(pipelineConfig.first(), new DefaultSchedulingContext("anonymous"), md5, new TimeProvider());
        stageService.save(savedPipeline, newInstance);

        boolean stageActive = stageService.isStageActive(CaseInsensitiveString.str(pipelineConfig.name()), CaseInsensitiveString.str(pipelineConfig.first().name()));
        assertThat(stageActive, is(true));
    }

    @Test
    public void shouldSaveStageWithFetchMaterialsFlag() {
        Stage firstStage = savedPipeline.getStages().first();
        Stage savedStage = stageService.stageById(firstStage.getId());
        assertThat(savedStage.shouldFetchMaterials(), is(false));
    }

    @Test
    public void shouldSaveStageWithCleanWorkingDirFlag() {
        Stage firstStage = savedPipeline.getStages().first();
        Stage savedStage = stageService.stageById(firstStage.getId());
        assertThat(savedStage.shouldCleanWorkingDir(), is(true));
    }

    @Test
    public void shouldGetStageHistoryForCurrentPage() {

        StageHistoryEntry[] stages = createFiveStages();

        StageHistoryPage history = stageService.findStageHistoryPage(stageService.stageById(stages[2].getId()), 3);
        assertThat("Found " + history, history.getPagination(), is(Pagination.pageStartingAt(0, 5, 3)));
        assertThat("Found " + history, history.getStages().size(), is(3));
        assertThat("Found " + history, history.getStages().get(0), is(stages[4]));
        assertThat("Found " + history, history.getStages().get(1), is(stages[3]));
        assertThat("Found " + history, history.getStages().get(2), is(stages[2]));

    }

    @Test
    public void shouldGetStageHistoryForLastPage() {

        StageHistoryEntry[] stages = createFiveStages();

        StageHistoryPage history = stageService.findStageHistoryPage(stageService.stageById(stages[0].getId()), 3);
        assertThat("Found " + history, history.getStages().get(0), is(stages[1]));
        assertThat("Found " + history, history.getStages().get(1), is(stages[0]));
        assertThat("Found " + history, history.getPagination(), is(Pagination.pageStartingAt(3, 5, 3)));
        assertThat("Found " + history, history.getPagination().getCurrentPage(), is(2));
    }

    private StageHistoryEntry[] createFiveStages() {
        Stage[] stages = new Stage[5];
        stages[0] = savedPipeline.getFirstStage();
        for (int i = 1; i < stages.length; i++) {
            DefaultSchedulingContext ctx = new DefaultSchedulingContext("anonumous");
            StageConfig stageCfg = pipelineConfig.first();
            stages[i] = i%2 == 0 ? instanceFactory.createStageInstance(stageCfg, ctx, md5, new TimeProvider()) : instanceFactory.createStageForRerunOfJobs(stages[i - 1], a("unit", "blah"), ctx,
                    stageCfg, new TimeProvider(), "md5");
            stageService.save(savedPipeline, stages[i]);
        }
        StageHistoryEntry[] entries = new StageHistoryEntry[5];
        for (int i = 0; i < stages.length; i++) {
            entries[i] = new StageHistoryEntry(stages[i], pipelineDao.loadHistory(savedPipeline.getId()).getNaturalOrder(), stages[i].getRerunOfCounter());
        }
        return entries;
    }

    @Test
    public void shouldGetStageHistoryByPageNumber() throws Exception {
        StageHistoryEntry[] stages = createFiveStages();

        StageHistoryPage history = stageService.findStageHistoryPageByNumber(PIPELINE_NAME, STAGE_NAME, 2, 3);
        assertThat("Found " + history, history.getPagination(), is(Pagination.pageStartingAt(3, 5, 3)));
        assertThat("Found " + history, history.getStages().size(), is(2));
        assertThat("Found " + history, history.getStages().get(0), is(stages[1]));
        assertThat("Found " + history, history.getStages().get(1), is(stages[0]));
    }

    @Test
    public void shouldSaveStageWithStateBuilding() throws Exception {
        Stage stage = instanceFactory.createStageInstance(pipelineConfig.first(), new DefaultSchedulingContext("anonumous"), md5, new TimeProvider());
        stageService.save(savedPipeline, stage);
        Stage latestStage = stageService.findLatestStage(CaseInsensitiveString.str(pipelineConfig.name()), CaseInsensitiveString.str(pipelineConfig.first().name()));
        assertThat(latestStage.getState(), is(StageState.Building));
    }

    @Test
    public void shouldIgnoreErrorsWhenNotifyingListenersDuringSave() throws Exception {
        List<StageStatusListener> original = new ArrayList<>(stageService.getStageStatusListeners());

        try {
            stageService.getStageStatusListeners().clear();
            StageStatusListener failingListener = mock(StageStatusListener.class);
            doThrow(new RuntimeException("Should not be rethrown by save")).when(failingListener).stageStatusChanged(any(Stage.class));
            StageStatusListener passingListener = mock(StageStatusListener.class);
            stageService.getStageStatusListeners().add(failingListener);
            stageService.getStageStatusListeners().add(passingListener);
            Stage newInstance = instanceFactory.createStageInstance(pipelineConfig.first(), new DefaultSchedulingContext("anonumous"), md5, new TimeProvider());
            Stage savedStage = stageService.save(savedPipeline, newInstance);
            assertThat("Got: " + savedStage.getId(), savedStage.getId() > 0L, is(true));
            verify(passingListener).stageStatusChanged(any(Stage.class));
        } finally {
            stageService.getStageStatusListeners().clear();
            stageService.getStageStatusListeners().addAll(original);
        }
    }

    @Test
    public void shouldNotifyListenersWhenStageScheduled() throws Exception {
        StageStatusListener listener = mock(StageStatusListener.class);
        stageService.addStageStatusListener(listener);

        Stage newInstance = instanceFactory.createStageInstance(pipelineConfig.first(),
                new DefaultSchedulingContext("anonymous"), md5, new TimeProvider());
        Stage savedStage = stageService.save(savedPipeline, newInstance);

        verify(listener).stageStatusChanged(savedStage);
    }

    @Test
    public void shouldNotifyListenersAfterStageIsCancelled() {
        StageStatusListener listener = mock(StageStatusListener.class);
        stageService.addStageStatusListener(listener);

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stage, null);
            }
        });
        stage = stageService.stageById(stage.getId());

        verify(listener).stageStatusChanged(stage);
    }

    @Test public void shouldLookupModifiedStageById_afterCancel() {
        Stage stageLoadedBeforeCancellation = stageService.stageById(stage.getId());
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stage, null);
            }
        });

        assertThat(stageService.stageById(stage.getId()), is(not(stageLoadedBeforeCancellation)));
    }

    @Test public void shouldSetCancelledByWhileCancellingAStage() {
        Stage stageLoadedBeforeCancellation = stageService.stageById(stage.getId());
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stage, "foo");
            }
        });

        Stage afterCancel = stageService.stageById(stage.getId());
        assertThat(afterCancel.getCancelledBy(), is("foo"));
        assertNull(stageLoadedBeforeCancellation.getCancelledBy());
    }

    @Test public void shouldLookupModifiedStageById_afterJobUpdate() {
        Stage stageLoadedBeforeUpdate = stageService.stageById(stage.getId());
        dbHelper.completeAllJobs(stage, JobResult.Passed);
        assertThat(stageService.stageById(stage.getId()), is(stageLoadedBeforeUpdate));
        stageService.updateResult(stage);

        assertThat(stageService.stageById(stage.getId()), is(not(stageLoadedBeforeUpdate)));
    }

    @Test public void shouldNotCancelAlreadyCompletedBuild() {
        jobResultTopic.addListener(new GoMessageListener<JobResultMessage>() {
            @Override
            public void onMessage(JobResultMessage message) {
                JobIdentifier jobIdentifier = message.getJobIdentifier();
                JobInstance instance = jobInstanceDao.mostRecentJobWithTransitions(jobIdentifier);
                receivedState = instance.getState();
                receivedResult = instance.getResult();
            }
        });
        JobInstanceMother.completed(job, Passed, new Date());
        jobInstanceDao.updateStateAndResult(job);
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                stageService.cancelStage(stage, null);
            }
        });

        JobInstance instanceFromDB = jobInstanceDao.buildByIdWithTransitions(job.getId());
        assertThat(instanceFromDB.getState(), is(JobState.Completed));
        assertThat(instanceFromDB.getResult(), is(Passed));
        assertThat(agentService.findAgentAndRefreshStatus(UUID).isCancelled(), is(false));
        assertThat(receivedState, is(nullValue()));
        assertThat(receivedResult, is(nullValue()));
    }

    @Test
    // #2328
    public void shouldGetDurationBasedOnPipelineNameStageNameJobNameAndAgentUUID() throws Exception {
        String pipelineName = "Cruise";
        configFileHelper.addPipeline(pipelineName, STAGE_NAME);
        Stage saveStage = dbHelper.saveTestPipeline(pipelineName, STAGE_NAME).getStages().first();
        JobInstance job1 = completed("unit", Passed, new Date(), new DateTime().minusMinutes(1).toDate());
        job1.setAgentUuid(UUID);

        jobInstanceDao.save(saveStage.getId(), job1);

        String pipeline2Name = "Cruise-1.1";
        configFileHelper.addPipeline(pipeline2Name, STAGE_NAME);
        Stage stage11 = dbHelper.saveTestPipeline(pipeline2Name, STAGE_NAME).getStages().first();

        final JobInstance job2 = building("unit", new Date());
        job2.setAgentUuid(UUID);
        JobInstance buildingJob = jobInstanceDao.save(stage11.getId(), job2);

        final DurationBean duration = stageService.getBuildDuration("Cruise-1.1", STAGE_NAME, buildingJob);
        assertThat("we should not load duration according to stage name + job name + agent uuid only, "
                + "we should also use pipeline name as a paramater", duration.getDuration(), is(0L));
    }

    @Test
    public void shouldNotifyListenerOnStageStatusChange() {
        StageStatusListener listener = mock(StageStatusListener.class);

        stageService.addStageStatusListener(listener);
        stageService.updateResult(stage);

        verify(listener).stageStatusChanged(stage);
    }

    @Test
    public void ensurePipelineSqlMapDaoIsAStageStatusListener() {
        assertThat(stageService.getStageStatusListeners(), hasItem((StageStatusListener) pipelineDao));
    }

    @Test
    public void shouldNotNotifyListenersWhenJobCancellationTransactionRollsback() {
        StageStatusListener listener = mock(StageStatusListener.class);
        JobInstanceService jobInstanceService = mock(JobInstanceService.class);
        JobInstance job = JobInstanceMother.building("foo");
        doThrow(new RuntimeException("test exception")).when(jobInstanceService).cancelJob(job);
        JobIdentifier jobId = new JobIdentifier("pipeline", 10, "label-10", "stage", "1", "foo");
        job.setIdentifier(jobId);
        StageDao stageDao = mock(StageDao.class);
        Stage stage = StageMother.custom("stage");
        when(stageDao.findStageWithIdentifier(jobId.getStageIdentifier())).thenReturn(stage);
        StageService service = new StageService(stageDao, jobInstanceService, null, null, null, null, changesetService, goConfigService, transactionTemplate, transactionSynchronizationManager,
                goCache, listener);
        try {
            service.cancelJob(job);
            fail("should have thrown up when underlying service bombed");
        } catch (Exception e) {
            assertThat(e.getMessage(), is("test exception"));
        }
        verify(listener, never()).stageStatusChanged(any(Stage.class));
    }

    @Test
    public void shouldNotifyListenersWhenJobCancelledSuccessfully() {
        StageStatusListener listener = mock(StageStatusListener.class);
        JobInstanceService jobInstanceService = mock(JobInstanceService.class);
        JobInstance job = JobInstanceMother.building("foo");
        JobIdentifier jobId = new JobIdentifier("pipeline", 10, "label-10", "stage", "1", "foo");
        job.setIdentifier(jobId);
        StageDao stageDao = mock(StageDao.class);
        Stage stage = StageMother.custom("stage");
        when(stageDao.findStageWithIdentifier(jobId.getStageIdentifier())).thenReturn(stage);
        StageService service = new StageService(stageDao, jobInstanceService, null, null, null, null, changesetService, goConfigService, transactionTemplate, transactionSynchronizationManager,
                goCache, listener);
        service.cancelJob(job);
        verify(listener).stageStatusChanged(stage);
    }

    @Test
    public void shouldLoadStagesHavingArtifactsWhenStageIsNotCleanupProtected() {
        PipelineConfig pipelineConfig = configFileHelper.addPipeline("pipeline-1", "stage-1", "job-1");

        Pipeline completed = dbHelper.schedulePipelineWithAllStages(pipelineConfig, ModificationsMother.modifySomeFiles(pipelineConfig));
        dbHelper.pass(completed);
        List<Stage> stages = stageService.oldestStagesWithDeletableArtifacts();
        assertThat(stages.size(), is(1));

        CruiseConfig cruiseConfig = configFileHelper.currentConfig();
        pipelineConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString("pipeline-1"));
        ReflectionUtil.setField(pipelineConfig.get(0), "artifactCleanupProhibited", true);
        configFileHelper.writeConfigFile(cruiseConfig);

        configDbStateRepository.flushConfigState();

        stages = stageService.oldestStagesWithDeletableArtifacts();
        assertThat(stages.size(), is(0));
    }

    @Test
    public void shouldLoadPageOfOldestStagesHavingArtifacts() {
        CruiseConfig cruiseConfig = configFileHelper.currentConfig();
        PipelineConfig mingleConfig = cruiseConfig.pipelineConfigByName(new CaseInsensitiveString(PIPELINE_NAME));
        ReflectionUtil.setField(mingleConfig.get(0), "artifactCleanupProhibited", true);
        configFileHelper.writeConfigFile(cruiseConfig);

        configDbStateRepository.flushConfigState();

        Pipeline[] pipelines = new Pipeline[101];
        for (int i = 0; i < 101; i++) {
            PipelineConfig pipelineCfg = configFileHelper.addPipeline("pipeline-" + i, "stage", "job");
            Pipeline pipeline = dbHelper.schedulePipeline(pipelineCfg, new TimeProvider());
            dbHelper.pass(pipeline);
            pipelines[i] = pipeline;
        }

        List<Stage> stages = stageService.oldestStagesWithDeletableArtifacts();
        for (int i = 0; i < 100; i++) {
            Stage stage = stages.get(i);
            assertThat(stage.getIdentifier(), is(pipelines[i].getFirstStage().getIdentifier()));
            stageService.markArtifactsDeletedFor(stage);
        }
        assertThat(stages.size(), is(100));

        stages = stageService.oldestStagesWithDeletableArtifacts();
        assertThat(stages.size(), is(1));
        Stage stage = stages.get(0);
        assertThat(stage.getIdentifier(), is(pipelines[100].getFirstStage().getIdentifier()));
        stageService.markArtifactsDeletedFor(stage);

        assertThat(stageService.oldestStagesWithDeletableArtifacts().size(), is(0));
    }

     @Test
     public void findStageHistoryForChart_shouldFindLatestStageInstancesForChart() throws Exception {
         PipelineConfig pipelineConfig = configFileHelper.addPipeline("pipeline-1", "stage-1");
         configFileHelper.turnOffSecurity();
         List<Pipeline> completedPipelines = new ArrayList<>();
         Pipeline pipeline;
         for (int i = 0; i < 16; i++) {
             pipeline = dbHelper.schedulePipelineWithAllStages(pipelineConfig, ModificationsMother.modifySomeFiles(pipelineConfig));
             dbHelper.pass(pipeline);
             completedPipelines.add(pipeline);
         }
         StageSummaryModels stages = stageService.findStageHistoryForChart(pipelineConfig.name().toString(), pipelineConfig.first().name().toString(), 1, 4, new Username(new CaseInsensitiveString("loser")));
         assertThat(stages.size(), is(4));
         assertThat(stages.get(0).getIdentifier().getPipelineCounter(), is(16));
         stages = stageService.findStageHistoryForChart(pipelineConfig.name().toString(), pipelineConfig.first().name().toString(), 3, 4, new Username(new CaseInsensitiveString("loser")));
         assertThat(stages.size(), is(4));
         assertThat(stages.get(0).getIdentifier().getPipelineCounter(), is(8));
         assertThat(stages.getPagination().getTotalPages(), is(4));
     }

    @Test
    public void findStageHistoryForChart_shouldNotRetrieveCancelledStagesAndStagesWithRerunJobs() throws Exception {
        PipelineConfig pipelineConfig = configFileHelper.addPipeline("pipeline-1", "stage-1");
        configFileHelper.turnOffSecurity();
        Pipeline pipeline = dbHelper.schedulePipelineWithAllStages(pipelineConfig, ModificationsMother.modifySomeFiles(pipelineConfig));
        dbHelper.pass(pipeline);
        StageSummaryModels stages = stageService.findStageHistoryForChart(pipelineConfig.name().toString(), pipelineConfig.first().name().toString(), 1, 10, new Username(new CaseInsensitiveString("loser")));
        assertThat(stages.size(), is(1));

        scheduleService.rerunJobs(pipeline.getFirstStage(), Arrays.asList(CaseInsensitiveString.str(pipelineConfig.first().getJobs().first().name())), new HttpOperationResult());
        stages = stageService.findStageHistoryForChart(pipelineConfig.name().toString(), pipelineConfig.first().name().toString(), 1, 10, new Username(new CaseInsensitiveString("loser")));

        assertThat(stages.size(), is(1)); //should not retrieve stages with rerun jobs

        pipeline = dbHelper.schedulePipelineWithAllStages(pipelineConfig, ModificationsMother.modifySomeFiles(pipelineConfig));
        dbHelper.cancelStage(pipeline.getFirstStage());
        stages = stageService.findStageHistoryForChart(pipelineConfig.name().toString(), pipelineConfig.first().name().toString(), 1, 10, new Username(new CaseInsensitiveString("loser")));

        assertThat(stages.size(), is(1)); //should not retrieve cancelled stages
    }

    @Test
    public void shouldSaveTheStageStatusProperlyUponJobCancelAfterInvalidatingTheCache() throws Exception {
        fixture = (PipelineWithMultipleStages) new PipelineWithMultipleStages(2, materialRepository, transactionTemplate, temporaryFolder).usingTwoJobs();
        fixture.usingConfigHelper(configFileHelper).usingDbHelper(dbHelper).onSetUp();

        Pipeline pipeline = fixture.createPipelineWithFirstStageAssigned();
        Stage currentStage = pipeline.getFirstStage();
        JobInstances jobs = currentStage.getJobInstances();

        JobInstance firstJob = jobs.first();
        firstJob.completing(JobResult.Passed);
        firstJob.completed(new Date());
        jobInstanceDao.updateStateAndResult(firstJob);

        // prime the cache
        stageService.findStageWithIdentifier(new StageIdentifier(pipeline, currentStage));

        stageService.cancelJob(jobs.last());

        Stage savedStage = stageService.stageById(currentStage.getId());
        assertThat(savedStage.getState(), is(StageState.Cancelled));
        assertThat(savedStage.getResult(), is(StageResult.Cancelled));
    }

    @Test
    public void shouldNotLoadStageAuthors_fromUpstreamInvisibleToUser() throws Exception {
        PipelineConfig downstream = setup2DependentInstances();

        configFileHelper.enableSecurity();
        configFileHelper.addAdmins("super-hero");

        configFileHelper.addAuthorizedUserForPipelineGroup("loser", "upstream-without-mingle");
        configFileHelper.addAuthorizedUserForPipelineGroup("loser", "downstream");
        configFileHelper.addAuthorizedUserForPipelineGroup("boozer", "upstream-with-mingle");

        FeedEntries feed = stageService.feed(downstream.name().toString(), new Username(new CaseInsensitiveString("loser")));

        assertAuthorsOnEntry((StageFeedEntry) feed.get(0),
                Arrays.asList(new Author("svn 3 guy", "svn.3@gmail.com"),
                        new Author("p4 2 guy", "p4.2@gmail.com")));

        assertAuthorsOnEntry((StageFeedEntry) feed.get(1),
                Arrays.asList(new Author("svn 1 guy", "svn.1@gmail.com"),
                        new Author("svn 2 guy", "svn.2@gmail.com"),
                        new Author("p4 1 guy", "p4.1@gmail.com")));
    }

    @Test
    public void shouldLoadStageAuthors_forFirstPageOfFeed() throws Exception {
        PipelineConfig downstream = setup2DependentInstances();

        FeedEntries feed = stageService.feed(downstream.name().toString(), new Username(new CaseInsensitiveString("loser")));

        assertStageEntryAuthor(feed);
    }

    @Test
    public void shouldLoadStageAuthors_forSubsequentPages() throws Exception {
        PipelineConfig downstream = setup2DependentInstances();

        FeedEntries feed = stageService.feedBefore(Integer.MAX_VALUE, downstream.name().toString(), new Username(new CaseInsensitiveString("loser")));

        assertStageEntryAuthor(feed);
    }

    @Test
    public void shouldFetchLatestStageInstanceForEachStage() {
        setup2DependentInstances();
        List<StageIdentity> latestStageInstances = stageService.findLatestStageInstances();
        assertThat(latestStageInstances.size(), is(4));
        assertThat(latestStageInstances.contains(new StageIdentity("mingle", "dev",8L)),is(true));
        assertThat(latestStageInstances.contains(new StageIdentity("upstream-without-mingle", "stage",13L)),is(true));
        assertThat(latestStageInstances.contains(new StageIdentity("downstream", "down-stage",14L)),is(true));
        assertThat(latestStageInstances.contains(new StageIdentity("upstream-with-mingle", "stage",10L)),is(true));
    }

    @Test
    public void testShouldReturnTrueIfAStageIsActive_CaseInsensitive() throws Exception {
        fixture = new PipelineWithMultipleStages(4, materialRepository, transactionTemplate, temporaryFolder);
        fixture.usingConfigHelper(configFileHelper).usingDbHelper(dbHelper).onSetUp();
        Pipeline pipeline = fixture.createPipelineWithFirstStagePassedAndSecondStageRunning();
        assertThat(stageService.isStageActive(pipeline.getName().toUpperCase(), "FT"), is(true));
    }

    private void assertStageEntryAuthor(FeedEntries feed) {

        assertAuthorsOnEntry((StageFeedEntry) feed.get(0),
                Arrays.asList(new Author("hg 3 guy", "hg.3@gmail.com"),
                        new Author("git 2&3 guy", "git.2.and.3@gmail.com"),
                        new Author("svn 3 guy", "svn.3@gmail.com"),
                        new Author("p4 2 guy", "p4.2@gmail.com")));

        assertAuthorsOnEntry((StageFeedEntry) feed.get(1),
                Arrays.asList(new Author("hg 1 guy", "hg.1@gmail.com"),
                        new Author("hg 2 guy", null),
                        new Author("git 1 guy", "git.1@gmail.com"),
                        new Author("svn 1 guy", "svn.1@gmail.com"),
                        new Author("svn 2 guy", "svn.2@gmail.com"),
                        new Author("p4 1 guy", "p4.1@gmail.com")));
    }

    private void assertAuthorsOnEntry(StageFeedEntry stage2, List<Author> authors) {
        List<Author> stage2Authors = stage2.getAuthors();

        assertThat(stage2Authors, hasItems(authors.toArray(new Author[0])));

        assertThat(stage2Authors.size(), is(authors.size()));

    }

    private PipelineConfig setup2DependentInstances() {
        Username loser = new Username(new CaseInsensitiveString("loser"));
        ManualBuild build = new ManualBuild(loser);
        Date checkinTime = new Date();

        GitMaterial git = MaterialsMother.gitMaterial("http://google.com", null, "master");
        git.setFolder("git");
        HgMaterial hg = MaterialsMother.hgMaterial();
        hg.setFolder("hg");
        PipelineConfig upstreamWithMingle = PipelineConfigMother.createPipelineConfig("upstream-with-mingle", "stage", "build");
        upstreamWithMingle.setMaterialConfigs(new MaterialConfigs(git.config(), hg.config()));
        configFileHelper.addPipelineToGroup(upstreamWithMingle, "upstream-with-mingle");

        P4Material p4 = MaterialsMother.p4Material("loser:007", "loser", "boozer", "through-the-window", true);
        PipelineConfig upstreamWithoutMingle = PipelineConfigMother.createPipelineConfig("upstream-without-mingle", "stage", "build");
        upstreamWithoutMingle.setMaterialConfigs(new MaterialConfigs(p4.config()));
        configFileHelper.addPipelineToGroup(upstreamWithoutMingle, "upstream-without-mingle");

        DependencyMaterial dependencyMaterial = MaterialsMother.dependencyMaterial(upstreamWithMingle.name().toString(), upstreamWithMingle.get(0).name().toString());
        SvnMaterial svn = MaterialsMother.svnMaterial("http://svn.com");
        DependencyMaterial dependencyMaterialViaP4 = MaterialsMother.dependencyMaterial(upstreamWithoutMingle.name().toString(), upstreamWithoutMingle.get(0).name().toString());
        PipelineConfig downstream = PipelineConfigMother.createPipelineConfig("downstream", "down-stage", "job");
        downstream.setMaterialConfigs(new MaterialConfigs(dependencyMaterial.config(), svn.config(), dependencyMaterialViaP4.config()));

        configFileHelper.addPipelineToGroup(downstream, "downstream");

        //mingle card nos.
        //svn: 1xx
        //p4: 2xx
        //hg: 3xx
        //git: 4xx

        Modification svnCommit1 = checkin(svn, "888", "svn commit #101 1", "svn 1 guy", "svn.1@gmail.com", checkinTime);

        Modification hgCommit1 = checkin(hg, "abcd", "hg commit 1 #301", "hg 1 guy", "hg.1@gmail.com", checkinTime);

        Modification gitCommit1 = checkin(git, "1234", "#401 - git commit 1", "git 1 guy", "git.1@gmail.com", checkinTime);

        Modification gitCommit2 = checkin(git, "2355", "git #402 commit 2", "git 2&3 guy", "git.2.and.3@gmail.com", checkinTime);//used in a later instance

        Modification hgCommit2 = checkin(hg, "abc", "hg commit #302 2", "hg 2 guy", null, checkinTime);

        Pipeline pipelineOne = dbHelper.checkinRevisionsToBuild(build, upstreamWithMingle, new MaterialRevision(git, gitCommit1), new MaterialRevision(hg, hgCommit2, hgCommit1));

        Modification hgCommit3 = checkin(hg, "bcde", "hg commit 3 #303", "hg 3 guy", "hg.3@gmail.com", checkinTime);

        Modification gitCommit3 = checkin(git, "567", "git #403 commit 3", "git 2&3 guy", "git.2.and.3@gmail.com", checkinTime);

        Pipeline pipelineTwo = dbHelper.checkinRevisionsToBuild(build, upstreamWithMingle, new MaterialRevision(git, gitCommit3, gitCommit2), new MaterialRevision(hg, hgCommit3));

        Modification p4Commit1 = checkin(p4, "777", "#201 - p4 commit 1", "p4 1 guy", "p4.1@gmail.com", checkinTime);

        Pipeline pipelineP4 = dbHelper.checkinRevisionsToBuild(build, upstreamWithoutMingle, new MaterialRevision(p4, p4Commit1));

        ArrayList<MaterialRevision> materialRevisionsFor1 = new ArrayList<>();
        dbHelper.addDependencyRevisionModification(materialRevisionsFor1, dependencyMaterial, pipelineOne);
        dbHelper.addDependencyRevisionModification(materialRevisionsFor1, dependencyMaterialViaP4, pipelineP4);

        Modification svnCommit2 = checkin(svn, "999", "svn #102 commit 2", "svn 2 guy", "svn.2@gmail.com", checkinTime);

        materialRevisionsFor1.add(new MaterialRevision(svn, svnCommit2, svnCommit1));
        //save downstream pipeline 1
        dbHelper.passPipeline(dbHelper.checkinRevisionsToBuild(build, downstream, materialRevisionsFor1));

        Modification p4Commit2 = checkin(p4, "007", "#202 - p4 commit 2", "p4 2 guy", "p4.2@gmail.com", checkinTime);

        Pipeline pipeline2P4 = dbHelper.checkinRevisionsToBuild(build, upstreamWithoutMingle, new MaterialRevision(p4, p4Commit2));

        ArrayList<MaterialRevision> materialRevisionsFor2 = new ArrayList<>();
        dbHelper.addDependencyRevisionModification(materialRevisionsFor2, dependencyMaterial, pipelineTwo);
        dbHelper.addDependencyRevisionModification(materialRevisionsFor2, dependencyMaterialViaP4, pipeline2P4);

        Modification svnCommit3 = checkin(svn, "1000", "svn commit #103 3", "svn 3 guy", "svn.3@gmail.com", checkinTime);
        materialRevisionsFor2.add(new MaterialRevision(svn, svnCommit3));

        //save downstream pipeline 2
        dbHelper.passPipeline(dbHelper.checkinRevisionsToBuild(build, downstream, materialRevisionsFor2));
        return downstream;
    }

    private Modification checkin(Material material, String rev, String comment, String user, String email, Date checkinTime) {
        Modification commit = checkinWithComment(rev, comment, user, email, checkinTime);
        dbHelper.addRevisionsWithModifications(material, commit);//saved now, used later
        return commit;
    }
}


text:
from System import System
from Frequency import Frequency

redpajama_set_name: RedPajamaGithub


text:
package com.yxkang.android.image.core;

import java.util.Locale;

/**
 * ImageProtocol
 */
@SuppressWarnings("ALL")
public enum ImageProtocol {

    HTTP("http"), HTTPS("https"), FILE("file"), CONTENT("content");

    private String protocol;
    private String uriPrefix;

    ImageProtocol(String protocol) {
        this.protocol = protocol;
        this.uriPrefix = protocol + "://";
    }

    public boolean belongsTo(String uri) {
        return uri.toLowerCase(Locale.CHINA).startsWith(uriPrefix);
    }

    /**
     * Appends scheme to incoming path
     *
     * @param path the path
     * @return the path with the uri prefix
     */
    public String wrap(String path) {
        return uriPrefix + path;
    }

    /**
     * Removed scheme part ("scheme://") from incoming URI
     *
     * @param uri the incoming URI
     * @return the path without the uri prefix
     */
    public String crop(String uri) {
        if (!belongsTo(uri)) {
            throw new IllegalArgumentException(
                    String.format("URI [%1$s] doesn't have expected protocol [%2$s]", uri, protocol));
        }
        return uri.substring(uriPrefix.length());
    }
}


text:
@implementation XCTestCase (WMFVisualTestConvenience)

- (UILabel *)wmf_getLabelSizedToFitWidth:(CGFloat)width
                     configuredWithBlock:(void (^)(UILabel *))block {
    UILabel *label = [[UILabel alloc] init];
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.numberOfLines = 0;
    label.backgroundColor = [UIColor whiteColor];

    if (block) {
        block(label);
    }

    [label wmf_sizeToFitWidth:width];

    return label;
}

- (UITableViewCell *)wmf_getCellWithIdentifier:(NSString *)identifier
                                 fromTableView:(UITableView *)tableView
                               sizedToFitWidth:(CGFloat)width
                           configuredWithBlock:(void (^)(UITableViewCell *))block {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    if (block) {
        block(cell);
    }

    [cell wmf_sizeToFitWidth:width];

    return cell;
}

@end


text:
require 'spec_helper'

describe Formbuilder::ResponseField do

  let(:response_field) { Formbuilder::ResponseFieldText.new }
  subject { response_field }

  it { should be_valid }

  describe '#options_array' do
    its(:options_array) { should be_empty }

    context 'with options' do
      before { response_field.field_options['options'] = [{'checked' => 'false', 'label' => 'Choice #1'},
                                                          {'checked' => 'false', 'label' => 'Choice #2'}] }

      its(:options_array) { should == ['Choice #1', 'Choice #2'] }
    end
  end

end


text:
import Heading from '../Heading'

import SponsoredConference from './SponsoredConference'
import styles from './SponsoredConferences.module.scss'

const SPONSORED_CONFERENCES = [
  {
    img: '/sponsors/testcon.png',
    imgDark: '/sponsors/testcon.png',
    url: 'https://testcon.lt',
    name: 'TestCon Europe 2022',
    date: 'October 26-27, 2022 ・ Online',
    topics: ['testing'],
  },
  {
    img: '/sponsors/bidata.png',
    imgDark: '/sponsors/bidata-dark.png',
    url: 'https://bigdataconference.eu',
    name: 'Big Data Europe 2022',
    date: 'November 23-24, 2022 ・ Online',
    topics: ['data'],
  },
]
const SponsoredConferences = () => {
  return (

        <Heading element='h3' level={4}>
          Current sponsors{' '}

            ❤

        </Heading>

        {SPONSORED_CONFERENCES.map((sponsoredConf) => (
          <SponsoredConference {...sponsoredConf} />
        ))}

  )
}

export default SponsoredConferences


text:
<?php

use Concrete\Core\Conversation\Rating\Type as ConversationRatingType;
use Concrete\Core\Http\Request;
use Concrete\Core\Permission\IPService;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\User\User;

defined('C5_EXECUTE') or die('Access Denied.');

$app = Application::getFacadeApplication();
$request = $app->make(Request::class);
$post = $request->request;

$cnvMessageID = $post->get('cnvMessageID');
if ($app->make('helper/validation/numbers')->integer($cnvMessageID, 1)) {
    $msg = ConversationMessage::getByID($cnvMessageID);
    if ($msg !== null) {
        $msp = new Permissions($msg);
        if ($msp->canRateConversationMessage()) {
            $cnvRatingTypeHandle = $post->get('cnvRatingTypeHandle');
            $ratingType = is_string($cnvRatingTypeHandle) ? ConversationRatingType::getByHandle($cnvRatingTypeHandle) : null;
            if ($ratingType !== null) {
                $commentRatingUserID = 0;
                if (User::isLoggedIn()) {
                    $user = $app->make(Concrete\Core\User\User::class);
                    if ($user->isRegistered()) {
                        $commentRatingUserID = (int) $user->getUserID();
                    }
                }
                $commentRatingIP = (string) $app->make(IPService::class)->getRequestIPAddress();
                $msg->rateMessage($ratingType, $commentRatingIP, $commentRatingUserID);
            }
        }
    }
}


text:
package com.metaphyze.hackernewsfrontpage;

public class HackerNewsPost
{

	private String id;
	private String postedBy;
	private String postedAgo;
	private String title;
	private String points;
	private String commentCount;
	private String url;

	public HackerNewsPost()
	{

	}

	@Override
	public HackerNewsPost clone()
	{
		HackerNewsPost clonePost = new HackerNewsPost();
		clonePost.id = id;
		clonePost.postedBy = postedBy;
		clonePost.postedAgo = postedAgo;
		clonePost.title = title;
		clonePost.points = points;
		clonePost.commentCount = commentCount;
		clonePost.url = url;
		return clonePost;
	}

	public String getId()
	{
		return id;
	}

	public String getPostedBy()
	{
		return postedBy;
	}

	public String getPostedAgo()
	{
		return postedAgo;
	}

	public void setPostedAgo(String newPostTime)
	{
		this.postedAgo = newPostTime;
	}

	public String getTitle()
	{
		return title;
	}

	public String getPoints()
	{
		return points;
	}

	public String getCommentCount()
	{
		return commentCount;
	}

	public String getUrl()
	{
		return url;
	}
}


text:
#ifndef CXXLAPACK_INTERFACE_LAMCH_H
#define CXXLAPACK_INTERFACE_LAMCH_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename T>
    T
    lamch(char c);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_LAMCH_H 1


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
	xmlns:context="http://www.springframework.org/schema/context">

	<context:annotation-config/>

	<bean class="org.springframework.context.annotation.configuration.AutowiredConfigurationTests$ValueConfig" scope="prototype"/>

</beans>


text:
* generator compatible with Rails 3/4 (mumoshu)
* add LICENSE (pivotalfish)
* add optional environment flag for YamlRepository (cherbst-medidata)
* documentation fixes (asmega, crackofdusk)
* update to rspec 3

## 1.0.0 (2014-03-26)

* drop ruby 1.8 support
* support Rails 4 generator loading only (mauriciovieira)
* add Feature.switch method (FlavourSys)
* minor code and doc fixes and cleanup

## 0.7.0 (2013-12-07)

* add ActiveRecordRepository and a Rails::Generator (bigzed)

## 0.6.0 (2013-03-24)

* add capability for easier testing of activated or deactivated features

## 0.5.0 (2012-09-29)

* added erb support for yaml feature config (dscataglini)
* fixed travis integration
* added code climate link

## 0.4.1 (2012-03-20)

* bugfix: occured when having empty feature set using yaml config (benjaminoakes)

## 0.4.0 (2011-11-28)

* simplify repositories, they only have to respond to method active_features

## 0.3.0 (2011-11-23)

* assume all features as inactive that are not active, also unknown ones
* make yaml parsing in yaml repository more strict

## 0.2.1 (2011-11-22)

* refactored gemspec

## 0.2.0 (2011-11-22)

* add yaml config file repository

## 0.1.0 (2011-11-18)

* first version with basic functionality and simple feature repository


text:
#include <chrono>
#include <err.h>
#include <iostream>
#include <memory>
#include <string>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>

#include "SkGraphics.h"
#include "SkRemoteGlyphCache.h"
#include "SkScalerContext.h"
#include "SkSurface.h"

static std::string gSkpName;
static bool gUseGpu = true;
static bool gPurgeFontCaches = true;
static bool gUseProcess = true;

class ServerDiscardableManager : public SkStrikeServer::DiscardableHandleManager {
public:
    ServerDiscardableManager() = default;
    ~ServerDiscardableManager() override = default;

    SkDiscardableHandleId createHandle() override { return ++nextHandleId; }
    bool lockHandle(SkDiscardableHandleId handleId) override {
        return handleId > lastPurgedHandleId;
    }
    void purgeAll() { lastPurgedHandleId = nextHandleId; }

private:
    SkDiscardableHandleId nextHandleId = 0u;
    SkDiscardableHandleId lastPurgedHandleId = 0u;
};

class ClientDiscardableManager : public SkStrikeClient::DiscardableHandleManager {
public:
    class ScopedPurgeCache {
    public:
        ScopedPurgeCache(ClientDiscardableManager* manager) : fManager(manager) {
            if (fManager) fManager->allowPurging = true;
        }
        ~ScopedPurgeCache() {
            if (fManager) fManager->allowPurging = false;
        }

    private:
        ClientDiscardableManager* fManager;
    };

    ClientDiscardableManager() = default;
    ~ClientDiscardableManager() override = default;

    bool deleteHandle(SkDiscardableHandleId) override { return allowPurging; }

private:
    bool allowPurging = false;
};

static bool write_SkData(int fd, const SkData& data) {
    size_t size = data.size();
    ssize_t bytesWritten = ::write(fd, &size, sizeof(size));
    if (bytesWritten < 0) {
        err(1,"Failed write %zu", size);
        return false;
    }

    bytesWritten = ::write(fd, data.data(), data.size());
    if (bytesWritten < 0) {
        err(1,"Failed write %zu", size);
        return false;
    }

    return true;
}

static sk_sp<SkData> read_SkData(int fd) {
    size_t size;
    ssize_t readSize = ::read(fd, &size, sizeof(size));
    if (readSize <= 0) {
        if (readSize < 0) {
            err(1, "Failed read %zu", size);
        }
        return nullptr;
    }

    auto out = SkData::MakeUninitialized(size);
    auto data = (uint8_t*)out->data();

    size_t totalRead = 0;
    while (totalRead < size) {
        ssize_t sizeRead;
        sizeRead = ::read(fd, &data[totalRead], size - totalRead);
        if (sizeRead <= 0) {
            if (readSize < 0) {
                err(1, "Failed read %zu", size);
            }
            return nullptr;
        }
        totalRead += sizeRead;
    }

    return out;
}

class Timer {
public:
    void start() {
        fStart = std::chrono::high_resolution_clock::now();
    }

    void stop() {
        auto end = std::chrono::high_resolution_clock::now();
        fElapsedSeconds += end - fStart;
    }

    double elapsedSeconds() {
        return fElapsedSeconds.count();
    }

private:
    decltype(std::chrono::high_resolution_clock::now()) fStart;
    std::chrono::duration<double>                       fElapsedSeconds{0.0};
};

static bool push_font_data(const SkPicture& pic, SkStrikeServer* strikeServer,
                           sk_sp<SkColorSpace> colorSpace, int writeFd) {
    const SkIRect bounds = pic.cullRect().round();
    const SkSurfaceProps props(SkSurfaceProps::kLegacyFontHost_InitType);
    SkTextBlobCacheDiffCanvas filter(bounds.width(), bounds.height(), props,
                                     strikeServer, std::move(colorSpace));
    pic.playback(&filter);

    std::vector<uint8_t> fontData;
    strikeServer->writeStrikeData(&fontData);
    auto data = SkData::MakeWithoutCopy(fontData.data(), fontData.size());
    return write_SkData(writeFd, *data);
}

static void final_draw(std::string outFilename, SkData* picData, SkStrikeClient* client,
                       ClientDiscardableManager* discardableManager, int readFd, int writeFd) {
    SkDeserialProcs procs;
    auto decode = [](const void* data, size_t length, void* ctx) -> sk_sp<SkTypeface> {
        return reinterpret_cast<SkStrikeClient*>(ctx)->deserializeTypeface(data, length);
    };
    procs.fTypefaceProc = decode;
    procs.fTypefaceCtx = client;

    auto pic = SkPicture::MakeFromData(picData, &procs);

    auto cullRect = pic->cullRect();
    auto r = cullRect.round();

    auto s = SkSurface::MakeRasterN32Premul(r.width(), r.height());
    auto c = s->getCanvas();
    auto picUnderTest = SkPicture::MakeFromData(picData, &procs);

    Timer drawTime;
    auto randomData = SkData::MakeUninitialized(1u);
    for (int i = 0; i < 100; i++) {
        if (gPurgeFontCaches) {
            ClientDiscardableManager::ScopedPurgeCache purge(discardableManager);
            SkGraphics::PurgeFontCache();
            SkASSERT(SkGraphics::GetFontCacheUsed() == 0u);
        }

        drawTime.start();
        if (client != nullptr) {
            // Kick the renderer to send us the fonts.
            write_SkData(writeFd, *randomData);
            auto fontData = read_SkData(readFd);
            if (fontData && !fontData->isEmpty()) {
                if (!client->readStrikeData(fontData->data(), fontData->size()))
                    SK_ABORT("Bad serialization");
            }
        }
        c->drawPicture(picUnderTest);
        drawTime.stop();
    }

    std::cout << "useProcess: " << gUseProcess
              << " useGPU: " << gUseGpu
              << " purgeCache: " << gPurgeFontCaches << std::endl;
    fprintf(stderr, "%s use GPU %s elapsed time %8.6f s\n", gSkpName.c_str(),
            gUseGpu ? "true" : "false", drawTime.elapsedSeconds());

    auto i = s->makeImageSnapshot();
    auto data = i->encodeToData();
    SkFILEWStream f(outFilename.c_str());
    f.write(data->data(), data->size());
}

static void gpu(int readFd, int writeFd) {

    if (gUseGpu) {
        auto picData = read_SkData(readFd);
        if (picData == nullptr) {
            return;
        }

        sk_sp<ClientDiscardableManager> discardableManager = sk_make_sp<ClientDiscardableManager>();
        SkStrikeClient strikeClient(discardableManager);

        final_draw("test.png", picData.get(), &strikeClient, discardableManager.get(), readFd,
                   writeFd);
    }

    ::close(writeFd);
    ::close(readFd);

    printf("GPU is exiting\n");
}

static int renderer(
    const std::string& skpName, int readFd, int writeFd)
{
    ServerDiscardableManager discardableManager;
    SkStrikeServer server(&discardableManager);
    auto closeAll = [readFd, writeFd]() {
        ::close(writeFd);
        ::close(readFd);
    };

    auto skpData = SkData::MakeFromFileName(skpName.c_str());
    std::cout << "skp stream is " << skpData->size() << " bytes long " << std::endl;

    sk_sp<SkData> stream;
    if (gUseGpu) {
        auto pic = SkPicture::MakeFromData(skpData.get());
        auto colorSpace = SkColorSpace::MakeSRGB();
        SkSerialProcs procs;
        auto encode = [](SkTypeface* tf, void* ctx) -> sk_sp<SkData> {
            return reinterpret_cast<SkStrikeServer*>(ctx)->serializeTypeface(tf);
        };
        procs.fTypefaceProc = encode;
        procs.fTypefaceCtx = &server;

        stream = pic->serialize(&procs);

        if (!write_SkData(writeFd, *stream)) {
            closeAll();
            return 1;
        }

        while (true) {
            auto inBuffer = read_SkData(readFd);
            if (inBuffer == nullptr) {
                closeAll();
                return 0;
            }
            if (gPurgeFontCaches) discardableManager.purgeAll();
            push_font_data(*pic.get(), &server, colorSpace, writeFd);
        }
    } else {
        stream = skpData;
        final_draw("test-correct.png", stream.get(), nullptr, nullptr, -1, -1);
        closeAll();
        return 0;
    }
}

int main(int argc, char** argv) {
    std::string skpName = argc > 1 ? std::string{argv[1]} : std::string{"skps/desk_nytimes.skp"};
    int mode = argc > 2 ? atoi(argv[2]) : -1;
    printf("skp: %s\n", skpName.c_str());

    gSkpName = skpName;

    enum direction : int {kRead = 0, kWrite = 1};

    int render_to_gpu[2],
        gpu_to_render[2];

    for (int m = 0; m < 8; m++) {
        int r = pipe(render_to_gpu);
        if (r < 0) {
            perror("Can't write picture from render to GPU ");
            return 1;
        }
        r = pipe(gpu_to_render);
        if (r < 0) {
            perror("Can't write picture from render to GPU ");
            return 1;
        }

        gPurgeFontCaches = (m & 4) == 4;
        gUseGpu = (m & 2) == 2;
        gUseProcess = (m & 1) == 1;

        if (mode >= 0 && mode < 8 && mode != m) {
            continue;
        }

        if (gUseProcess) {
            pid_t child = fork();
            SkGraphics::Init();

            if (child == 0) {
                close(gpu_to_render[kRead]);
                close(render_to_gpu[kWrite]);
                gpu(render_to_gpu[kRead], gpu_to_render[kWrite]);
            } else {
                close(render_to_gpu[kRead]);
                close(gpu_to_render[kWrite]);
                renderer(skpName, gpu_to_render[kRead], render_to_gpu[kWrite]);
                waitpid(child, nullptr, 0);
            }
        } else {
            SkGraphics::Init();
            std::thread(gpu, render_to_gpu[kRead], gpu_to_render[kWrite]).detach();
            renderer(skpName, gpu_to_render[kRead], render_to_gpu[kWrite]);
        }
    }

    return 0;
}


text:
![Suma](img/suma-logo.png)

Overview
=====

Suma comprises a set of tools, including a mobile tablet-based (i.e. Apple iPad) data collection application, that will allow library staff to collect, aggregate, and interactively analyze real-time data about the usage of physical space and services. This tool will support the collection of more fine-grained data about physical space usage patterns by supporting the annotation of users with "activities." The data that this tool provides will allow the libraries to build on existing assessment practices by significantly improving our ability to analyze physical space usage trends against various milestones, as well as generating more dynamic and current data visualizations. As a result, this data can be both collected and utilized more frequently and at a much wider scope than before with relative ease.

This project is currently being used at NC State as a pilot project for a wider deployment. Examples of the current and planned uses for this toolkit include the collection and analysis of data relating to:

* Building headcounts
* Reference desk transactions
* Experimental technology usage
* Media production activities
* Experimental furniture usage

Disclaimer
======================
We have worked hard to make the code as stable as possible, but are eager to receive feedback on any issues you discover. While we at NCSU Libraries' have been using it in a production capacity since July 2011 with great success, and several other institutions have successfully implemented this code, you should still take appropriate precautions when deploying this application. These include but are not limited to carefully backing up databases, monitoring error logs, maintaining close relationships with users, and reporting any problems back to the project team. Thank you for helping to ensure that this project continues to grow.

As a safeguard, all JSON input from the client is logged. This will lead to large log files, but it allows for data recovery in the case of database problems or improperly rejected data. See the information about "JSON INPUT" entries in LOGS.md for more information. **We at NCSU Libraries have never needed to make use of this recovery feature.**

Documentation
==============

How to contribute?
===================
You want to contribute some code? Maybe some data reports, bug fixes, new clients, or even new core features? Awesome! Just contact us or fork the code on GitHub and create a pull request.

Project URLs
============
* Project page: http://www.lib.ncsu.edu/dli/projects/spaceassesstool/
* Repository: https://github.com/cazzerson/suma

Suma Community
==============

If you would like to be invited to a google group for the Suma users community, please email Joyce Chapman at joyce DOT chapman AT gmail DOT com

Credits and contacts
=====================

* Jason Casden (jmcasden AT ncsu DOT edu) – Project lead.
* Joyce Chapman (joyce DOT chapman AT gmail DOT com) – Community development and data analysis specialist.
* Bret Davidson - Technical lead.
* Rob Rucker – Project team member and our first stakeholder. Research Information Services department head responsible for NCSU D. H. Hill Libraries head counts and reference desk transactions.
* Eric McEachern – Backend developer, responsible for much of the development of the server-side components.
* Rusty Earl – Backend developer and technical consultant.


text:
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>test.</title>
  <!-- bower:css -->
  <link rel="stylesheet" href="../cwd_includeself/bower_components/bootstrap/dist/css/bootstrap.css" />
  <link rel="stylesheet" href="../cwd_includeself/sample-main.css" />
  <!-- endbower -->
</head>
<body>

  <!-- bower:js -->
  <script src="../cwd_includeself/bower_components/jquery/jquery.js"></script>
  <script src="../cwd_includeself/bower_components/bootstrap/dist/js/bootstrap.js"></script>
  <script src="../cwd_includeself/sample-main.js"></script>
  <!-- endbower -->
</body>
</html>


text:
package org.jkiss.dbeaver.ext.ui.locks.graph;

import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;

public class LockGraphEditPartFactory implements EditPartFactory {

	public EditPart createEditPart(EditPart context, Object model) {

		EditPart editPart = null;

		if (model instanceof LockGraph) {

			editPart = new LockGraphEditPart();

		} else if (model instanceof LockGraphEdge) {

			editPart = new LockGraphEdgeEditPart();

		} else if (model instanceof LockGraphNode) {

			editPart = new LockGraphNodeEditPart();

		}

		if (editPart != null) {

			editPart.setModel(model);
		}

		return editPart;
	}
}


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

namespace Crossover
{
    internal class Program
    {
        private static void Main()
        {
            Console.WriteLine("Most Often Subscription Application.\n");
            Console.WriteLine("Input parameters in format: ");
            Console.WriteLine("N");
            Console.WriteLine("K L M");
            Console.WriteLine("S");
            Console.WriteLine("\n* where 2 <= N <= 100,000");
            Console.WriteLine("   2 <= K <= L <= 26, L < N");
            Console.WriteLine("   2 <= M <= 26");
            Console.WriteLine("   S - string of length N");

            try
            {
                // Read input parameters
                var n = int.Parse(Console.ReadLine() ?? string.Empty);
                var klm = (Console.ReadLine() ?? string.Empty).Split();
                var k = int.Parse(klm[0]);
                var l = int.Parse(klm[1]);
                var m = int.Parse(klm[2]);
                var str = Console.ReadLine();
                if (string.IsNullOrEmpty(str) || str.Length != n)
                {
                    throw new ApplicationException(string.Format("Specified string '{0}' should be of length {1}", str, n));
                }

                str = str.ToLower();

                // Validate input parameters
                if (!(n >= 2 && n <= 100000))
                {
                    throw new ApplicationException(string.Format("Invalid N parameter specified: {0}", n));
                }
                if (!(k >= 2 && k <= 26) || !(l >= 2 && l <= 26) || !(k <= l) && !(l < n))
                {
                    throw new ApplicationException(string.Format("Invalid K & L parameters specified: {0} & {1}", k, l));
                }
                if (!(m >= 2 && m <= 26))
                {
                    throw new ApplicationException(string.Format("Invalid M parameter specified: {0}", m));
                }

                // Searching for substrings
                var substrings = new Dictionary<string, int>();
                for (var i = 0; i < n; ++i)
                {
                    // building substrings of length between k and l
                    for (var j = k; j <= l && (i + j - 1 < n); j++)
                    {
                        var substr = str.Substring(i, j);
                        if (CountUniqueChars(substr) > m)
                        {
                            continue;
                        }

                        if (substrings.ContainsKey(substr))
                        {
                            substrings[substr]++;
                        }
                        else
                        {
                            substrings.Add(substr, 1);
                        }
                    }
                }

                if (substrings.Any())
                {
                    var mostOftenSubstringCount = substrings.Max(s => s.Value);
                    Console.WriteLine(mostOftenSubstringCount);
                }
                else
                {
                    Console.WriteLine(0);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e);
            }

            Console.ReadKey();
        }

        private static int CountUniqueChars(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return 0;
            }

            var chars = new HashSet<char>();
            foreach (var chr in str)
            {
                chars.Add(chr);
            }

            return chars.Count;
        }
    }
}


text:
/**************************************************************************************************
 *** This file was autogenerated from GrSweepGradientLayout.fp; do not modify.
 **************************************************************************************************/
#include "GrSweepGradientLayout.h"
#include "glsl/GrGLSLFragmentProcessor.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLProgramBuilder.h"
#include "GrTexture.h"
#include "SkSLCPP.h"
#include "SkSLUtil.h"
class GrGLSLSweepGradientLayout : public GrGLSLFragmentProcessor {
public:
    GrGLSLSweepGradientLayout() {}
    void emitCode(EmitArgs& args) override {
        GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
        const GrSweepGradientLayout& _outer = args.fFp.cast<GrSweepGradientLayout>();
        (void)_outer;
        auto gradientMatrix = _outer.gradientMatrix();
        (void)gradientMatrix;
        auto bias = _outer.bias();
        (void)bias;
        auto scale = _outer.scale();
        (void)scale;
        fBiasVar = args.fUniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "bias");
        fScaleVar =
                args.fUniformHandler->addUniform(kFragment_GrShaderFlag, kHalf_GrSLType, "scale");
        SkString sk_TransformedCoords2D_0 = fragBuilder->ensureCoords2D(args.fTransformedCoords[0]);
        fragBuilder->codeAppendf(
                "half angle;\nif (sk_Caps.atan2ImplementedAsAtanYOverX) {\n    angle = half(2.0 * "
                "atan(-%s.y, length(%s) - %s.x));\n} else {\n    angle = half(atan(-%s.y, "
                "-%s.x));\n}\nhalf t = ((angle * 0.15915494309180001 + 0.5) + %s) * %s;\n%s = "
                "half4(t, 1.0, 0.0, 0.0);\n",
                sk_TransformedCoords2D_0.c_str(), sk_TransformedCoords2D_0.c_str(),
                sk_TransformedCoords2D_0.c_str(), sk_TransformedCoords2D_0.c_str(),
                sk_TransformedCoords2D_0.c_str(), args.fUniformHandler->getUniformCStr(fBiasVar),
                args.fUniformHandler->getUniformCStr(fScaleVar), args.fOutputColor);
    }

private:
    void onSetData(const GrGLSLProgramDataManager& pdman,
                   const GrFragmentProcessor& _proc) override {
        const GrSweepGradientLayout& _outer = _proc.cast<GrSweepGradientLayout>();
        {
            float biasValue = _outer.bias();
            if (fBiasPrev != biasValue) {
                fBiasPrev = biasValue;
                pdman.set1f(fBiasVar, biasValue);
            }
            float scaleValue = _outer.scale();
            if (fScalePrev != scaleValue) {
                fScalePrev = scaleValue;
                pdman.set1f(fScaleVar, scaleValue);
            }
        }
    }
    float fBiasPrev = SK_FloatNaN;
    float fScalePrev = SK_FloatNaN;
    UniformHandle fBiasVar;
    UniformHandle fScaleVar;
};
GrGLSLFragmentProcessor* GrSweepGradientLayout::onCreateGLSLInstance() const {
    return new GrGLSLSweepGradientLayout();
}
void GrSweepGradientLayout::onGetGLSLProcessorKey(const GrShaderCaps& caps,
                                                  GrProcessorKeyBuilder* b) const {}
bool GrSweepGradientLayout::onIsEqual(const GrFragmentProcessor& other) const {
    const GrSweepGradientLayout& that = other.cast<GrSweepGradientLayout>();
    (void)that;
    if (fGradientMatrix != that.fGradientMatrix) return false;
    if (fBias != that.fBias) return false;
    if (fScale != that.fScale) return false;
    return true;
}
GrSweepGradientLayout::GrSweepGradientLayout(const GrSweepGradientLayout& src)
        : INHERITED(kGrSweepGradientLayout_ClassID, src.optimizationFlags())
        , fGradientMatrix(src.fGradientMatrix)
        , fBias(src.fBias)
        , fScale(src.fScale)
        , fCoordTransform0(src.fCoordTransform0) {
    this->addCoordTransform(&fCoordTransform0);
}
std::unique_ptr<GrFragmentProcessor> GrSweepGradientLayout::clone() const {
    return std::unique_ptr<GrFragmentProcessor>(new GrSweepGradientLayout(*this));
}
GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSweepGradientLayout);
#if GR_TEST_UTILS
std::unique_ptr<GrFragmentProcessor> GrSweepGradientLayout::TestCreate(GrProcessorTestData* d) {
    SkScalar scale = GrGradientShader::RandomParams::kGradientScale;
    SkPoint center = {d->fRandom->nextRangeScalar(0.0f, scale),
                      d->fRandom->nextRangeScalar(0.0f, scale)};

    GrGradientShader::RandomParams params(d->fRandom);
    auto shader = params.fUseColors4f
                          ? SkGradientShader::MakeSweep(center.fX, center.fY, params.fColors4f,
                                                        params.fColorSpace, params.fStops,
                                                        params.fColorCount)
                          : SkGradientShader::MakeSweep(center.fX, center.fY, params.fColors,
                                                        params.fStops, params.fColorCount);
    GrTest::TestAsFPArgs asFPArgs(d);
    std::unique_ptr<GrFragmentProcessor> fp = as_SB(shader)->asFragmentProcessor(asFPArgs.args());
    GrAlwaysAssert(fp);
    return fp;
}
#endif

std::unique_ptr<GrFragmentProcessor> GrSweepGradientLayout::Make(const SkSweepGradient& grad,
                                                                 const GrFPArgs& args) {
    SkMatrix matrix;
    if (!grad.totalLocalMatrix(args.fPreLocalMatrix, args.fPostLocalMatrix)->invert(&matrix)) {
        return nullptr;
    }
    matrix.postConcat(grad.getGradientMatrix());
    return std::unique_ptr<GrFragmentProcessor>(
            new GrSweepGradientLayout(matrix, grad.getTBias(), grad.getTScale()));
}


text:
package it.frech.jhealth;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

public class FullGCTriggerTest {

	private static final double CHUNK_RATIO = .2;
	private static final double KEEP_RATIO = .8;
	private static final int MAX_CHUNKS = (int) (1 / CHUNK_RATIO * KEEP_RATIO);

	private static Random random = new Random();

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("chunk ratio: " + CHUNK_RATIO
				+ " / max no. of chunks: " + MAX_CHUNKS);
		MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();

		MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
		long max = heapMemoryUsage.getMax();

		Map<Long, String> map = new TreeMap<Long, String>();

		LinkedList<Object> list = new LinkedList<Object>();

		long index = 0;
		long maxIndex = Long.MAX_VALUE;

		boolean measuring = true;

		while (true) {
			String s = concatSomeStuff();
			map.put(index++, s);
//			map.remove(index / 2);
//			map.remove(index / 3);
//			map.remove(index / 5);

			if (measuring && index % 20 == 0) {

				heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

				if (measuring && heapMemoryUsage.getUsed() > max * CHUNK_RATIO) {
					measuring = false;
					maxIndex = index;
					System.out.println("MaxIndex is: " + maxIndex);

				}
			}
			if (index > maxIndex) {
				heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();

				list.addFirst(map);
				if (list.size() >= MAX_CHUNKS) {
					list.removeLast();
				}

				index = 0;
				map = new HashMap<Long, String>();
				System.out.println("Starting new map, usage: "
						+ heapMemoryUsage.getUsed() / 1024 / 1024
						+ " MB  committed:" + heapMemoryUsage.getCommitted()
						/ 1024 / 1024 + " MB  max:" + heapMemoryUsage.getMax()
						/ 1024 / 1024 + " MB");
			}
		}
	}

	private static String concatSomeStuff() {
		int i = random.nextInt();
		long l = random.nextLong();
		double d = random.nextGaussian();
		String s = "I" + i + Integer.toOctalString(i)
				+ Integer.toBinaryString(i) + "L" + l + Long.toHexString(l)
				+ Long.toBinaryString(l) + "D" + d + Double.toHexString(d);

//		for (int j = 0; j < ; j++) {
//			s += s;
//		}

		if ((System.currentTimeMillis()/1000)%10 != 0) {
			for (int j = 0; j < 10; j++) {
				s += s;
			}
		}

		return s;
	}
}


text:
namespace remoting {

// Filtering VideoStub implementation which configures a MouseInputFilter to
// clamp mouse events to fall within the dimensions of the most-recently
// received video frame.
class MouseClampingFilter : public protocol::VideoStub {
 public:
  explicit MouseClampingFilter(protocol::InputStub* input_stub);
  virtual ~MouseClampingFilter();

  protocol::InputStub* input_filter() { return &input_filter_; }

  void set_video_stub(protocol::VideoStub* video_stub) {
    video_stub_ = video_stub;
  }

  // protocol::VideoStub implementation.
  virtual void ProcessVideoPacket(scoped_ptr<VideoPacket> video_packet,
                                  const base::Closure& done) OVERRIDE;

 private:
  // Clamps mouse event coordinates to the video dimensions.
  protocol::MouseInputFilter input_filter_;

  protocol::VideoStub* video_stub_;

  DISALLOW_COPY_AND_ASSIGN(MouseClampingFilter);
};

}  // namespace remoting

#endif  // REMOTING_HOST_MOUSE_CLAMPING_FILTER_H_


text:
package com.nvapp.android.reminder;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class OnAlermReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {

	}

}


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

<title>Class Hierarchy</title>
<meta name="date" content="2016-02-21">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

com.codizer.model,

com.codizer.pojo,

com.codizer.view

Class Hierarchy

java.lang.Object

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

java.awt.Window (implements javax.accessibility.Accessible)

java.awt.Frame (implements java.awt.MenuContainer)

javax.swing.JFrame (implements javax.accessibility.Accessible, javax.swing.RootPaneContainer, javax.swing.WindowConstants)

com.codizer.view.LoginUISingleton (implements java.awt.event.ActionListener, java.awt.event.FocusListener)

com.codizer.view.MyPullsUISingleton

com.codizer.view.PullUISingleton (implements java.awt.event.ActionListener)

com.codizer.model.DBSingleton

Init

com.codizer.pojo.Message

com.codizer.model.MessageDaoImp (implements com.codizer.model.MessageDao)

com.codizer.pojo.User

com.codizer.model.UserDaoImp (implements com.codizer.model.UserDao)

com.codizer.model.UserSessionSingleton

Interface Hierarchy

com.codizer.model.MessageDao

com.codizer.model.UserDao

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<!doctype html>

<title>Holder Testing</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" class="holderjs">
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css' class="holderjs">
<link href='http://fonts.googleapis.com/css?family=Droid+Sans' rel='stylesheet' type='text/css'>

		 Plain placeholder

		 Themed placeholder

		Placeholder with random theme

		Placeholder with rgb color values

		Placeholder with rgba color values

		 Placeholder with text

		 Placeholder with lengthy text

		Canvas placeholder with lengthy text

		 Placeholder with very lengthy text

		 Placeholder with custom newline

		 Placeholder with disabled line wrap

		 Placeholder with left-aligned text

		 Placeholder with right-aligned text

		 Placeholder with right-aligned text and custom margin

		Placeholder with (randomly) missing image source

		 Auto-sized placeholder

		 Auto-sized placeholder in exact mode

		<div> with background placeholder

		<div> with data-background-src placeholder

		 Placeholder added using addImage with a selector

		Auto-sized canvas placeholder with custom domain and theme

		 Placeholder using Pacifico font

	<object data-src="holder.js/300x200?font=Pacifico&bg=4466ff&fg=fff&text=Pacifico"></object>

		object placeholder using Pacifico font

		 Placeholders demonstrating adaptive text size

		Placeholder with custom font size

		SVG and canvas placeholders with outline enabled

		Placeholders with automatic foreground color

		Placeholders with automatic and default color

		Placeholders with automatic foreground color, grayscale

		Placeholder added using addImage with a DOM node

		Placeholder that triggers an error due to an invalid bg color

		 Full-page fluid placeholder

	<object data-src="holder.js/90px80p?theme=vine"></object>

		 Full-page fluid object placeholder

		 Full-page fluid placeholder in literal mode

		 Full-page fluid placeholder with embedded dimension text

		 Full-page fluid placeholder that toggles resizable updates when clicked

		Fluid placeholder inside invisible parent element.

		 Full-page fluid placeholder with outline enabled


text:
from time import strftime
from .base.update_wait import Update_wait

class Seven_segment_clock(Update_wait):
    def __init__(self, ss_dev, sep="-", fmt=None, update_every=1):
        self.ss_dev = ss_dev
        self.sep = sep
        # entry point for testing
        self.strftime = strftime
        self.fmt = "%H{}%M{}%S".format(*(sep * 2)) if not fmt else fmt
        super().__init__(update_every)

    def update(self):
        if not self.iftimeout():
            return
        for i, char in enumerate(reversed(self.get_fm_time())):
            self.ss_dev.write(char, i)

    def get_fm_time(self):
        return self.strftime(self.fmt)


text:
package Gamess.gamessGUI.IncompatibilityPackage.ConditionLogic;

import java.util.Hashtable;

import org.w3c.dom.Node;

public class ConditionBuilder
{
	private static Hashtable<Object, Condition> ConditionCache = new Hashtable<Object, Condition>();

	public static Condition buildCondition(String Data)
	{
		//if there is a hit then return the value
		if(hit(Data))
			return ConditionCache.get(Data);

		//Create a new And Condition and return it
		Condition cond = new And(Data);
		cond.trim();
		//Add the condition to the Cache
		ConditionCache.put(Data, cond);
		return cond;
	}

	public static Condition buildCondition(Node condNode)
	{
		if(condNode == null)
			return null;
		//if there is a hit then return the value
		if(hit(condNode))
			return ConditionCache.get(condNode);

		Condition cond = null;

		//Check if the current node has any siblings.
		//if it has then create a new And logic and return it
		Node nextSibNode = null;
		for(nextSibNode = condNode.getNextSibling(); nextSibNode != null && nextSibNode.getNodeType() == Node.TEXT_NODE; nextSibNode = nextSibNode.getNextSibling());
		if(nextSibNode != null)
			cond = new And(condNode);

		//Else check if the current node belongs to And/Or/Not/Entity.
		//Create a new logic based on that and return it.
		if(cond == null && condNode.getNodeName().equalsIgnoreCase("And"))
			cond = new And(condNode);
		else if(cond == null && condNode.getNodeName().equalsIgnoreCase("Or"))
			cond = new Or(condNode);
		else if(cond == null && condNode.getNodeName().equalsIgnoreCase("Not"))
			cond = new Not(condNode);
		else
			cond = new And(condNode);

		cond.trim();
		//Add the condition to the Cache
		ConditionCache.put(condNode, cond);
		return cond;
	}

	private static boolean hit(Object obj)
	{
		return ConditionCache.containsKey(obj);
	}
}


text:
import Color from 'graphics/color/BaseColor.js';

import Canvas from 'canvas/Canvas.js';
import AddToDOM from 'dom/AddToDOM.js';
import BackgroundColor from 'canvas/BackgroundColor.js';

let canvas = Canvas(512, 512);

BackgroundColor(canvas, 'rgb(0, 0, 0)');

AddToDOM(canvas, 'game');

let ctx = canvas.getContext('2d');

let color = new Color();

for (let y = 0; y < 8; y++)
{
    for (let x = 0; x < 8; x++)
    {
        color.fromRandom();
        ctx.fillStyle = color.rgba;
        ctx.fillRect(x * 64, y * 64, 64, 64);
    }
}


text: Website for author Jeannette Ng


text:
[![Code Climate](https://codeclimate.com/github/garethrees/coderwall_ruby.png)](https://codeclimate.com/github/garethrees/coderwall_ruby)

Simple wrapper around [Coderwall's](http://coderwall.com) users API for a [Tech Talk](https://speakerdeck.com/gareth/hello-ruby) at [Box UK](http://boxuk.com).

For code as demoed see [d2eff31d07](https://github.com/garethrees/coderwall_ruby/commit/d2eff31d07c6aa95b7089fa7c17cc6a4b279aa44).

## Usage

```ruby
> me = CoderwallRuby::User.new('garethrees')
#=> Returns a Hash of data from the API
> me.username
#=> 'garethrees'
> me.location
#=> 'Cardiff, Wales UK'
# etc...
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
namespace base {
class CancelableTaskTracker;
}

namespace favicon_base {
struct FaviconImageResult;
}

class WebPageNotifierController : public NotifierController {
 public:
  explicit WebPageNotifierController(Observer* observer);
  ~WebPageNotifierController() override;

  std::vector<ash::NotifierMetadata> GetNotifierList(Profile* profile) override;

  void SetNotifierEnabled(Profile* profile,
                          const message_center::NotifierId& notifier_id,
                          bool enabled) override;

 private:
  void OnFaviconLoaded(const GURL& url,
                       const favicon_base::FaviconImageResult& favicon_result);

  std::map<std::string, ContentSettingsPattern> patterns_;

  // The task tracker for loading favicons.
  std::unique_ptr<base::CancelableTaskTracker> favicon_tracker_;

  // Lifetime of parent must be longer than the source.
  Observer* observer_;
};

#endif  // CHROME_BROWSER_NOTIFICATIONS_WEB_PAGE_NOTIFIER_CONTROLLER_H_


text:
package uk.gov.dvla.vehicles.presentation.common.mappings

import org.joda.time.LocalDate
import play.api.data.Forms.{of, optional}
import uk.gov.dvla.vehicles.presentation.common.services.DateService
import Date.formatter
import Date.notInTheFuture

object OptionalDate {

    val optionalDateMapping = optional(of[LocalDate](formatter()))

    def optionalNonFutureDateMapping(implicit dateService: DateService) =
      optional(of[LocalDate](formatter()) verifying notInTheFuture())

}


text:
<!DOCTYPE html>
<title>Canvas test: 2d.composite.solid.destination-over</title>

<link rel="stylesheet" href="../tests.css">
<link rel="prev" href="2d.composite.solid.source-over.html" title="2d.composite.solid.source-over">
<link rel="next" href="2d.composite.solid.source-in.html" title="2d.composite.solid.source-in">

 <
 [index]
 >

2d.composite.solid.destination-over

References:

2d.composite.destination-over

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>

Expected output:


text:
from har_api.resources.tests import HarTestSingle, HarTestCollection
from har_api.resources.pages import HarPageSingle, HarPageCollection

def create_routes(api):
    """
    Given an instance of a Flask-RESTFul Api object, binds the routes.
    """
    api.add_resource(HarTestCollection, '/tests/')
    api.add_resource(HarTestSingle, '/tests/<int:test_id>/')
    api.add_resource(HarPageCollection, '/pages/')
    api.add_resource(HarPageSingle, '/pages/<int:page_id>/')


text:
<?php

namespace Google\Service\Compute;

class InterconnectAttachmentPrivateInfo extends \Google\Model
{
  /**
   * @var string
   */
  public $tag8021q;

  /**
   * @param string
   */
  public function setTag8021q($tag8021q)
  {
    $this->tag8021q = $tag8021q;
  }
  /**
   * @return string
   */
  public function getTag8021q()
  {
    return $this->tag8021q;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(InterconnectAttachmentPrivateInfo::class, 'Google_Service_Compute_InterconnectAttachmentPrivateInfo');