text:
package org.jboss.pnc.demo.data;

import com.google.common.base.Preconditions;
import org.jboss.pnc.common.concurrent.Sequence;
import org.jboss.pnc.common.json.moduleconfig.DemoDataConfig;
import org.jboss.pnc.common.json.moduleconfig.SystemConfig;
import org.jboss.pnc.enums.ArtifactQuality;
import org.jboss.pnc.enums.BuildStatus;
import org.jboss.pnc.enums.BuildType;
import org.jboss.pnc.enums.MilestoneCloseStatus;
import org.jboss.pnc.enums.RepositoryType;
import org.jboss.pnc.enums.SupportLevel;
import org.jboss.pnc.enums.SystemImageType;
import org.jboss.pnc.model.Artifact;
import org.jboss.pnc.model.BuildConfigSetRecord;
import org.jboss.pnc.model.BuildConfiguration;
import org.jboss.pnc.model.BuildConfigurationAudited;
import org.jboss.pnc.model.BuildConfigurationSet;
import org.jboss.pnc.model.BuildEnvironment;
import org.jboss.pnc.model.BuildRecord;
import org.jboss.pnc.model.IdRev;
import org.jboss.pnc.model.Product;
import org.jboss.pnc.model.ProductMilestone;
import org.jboss.pnc.model.ProductMilestoneRelease;
import org.jboss.pnc.model.ProductRelease;
import org.jboss.pnc.model.ProductVersion;
import org.jboss.pnc.model.Project;
import org.jboss.pnc.model.RepositoryConfiguration;
import org.jboss.pnc.model.TargetRepository;
import org.jboss.pnc.model.User;
import org.jboss.pnc.spi.datastore.Datastore;
import org.jboss.pnc.spi.datastore.repositories.ArtifactAuditedRepository;
import org.jboss.pnc.spi.datastore.repositories.ArtifactRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigSetRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationAuditedRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildConfigurationSetRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildEnvironmentRepository;
import org.jboss.pnc.spi.datastore.repositories.BuildRecordRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductMilestoneReleaseRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductMilestoneRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductReleaseRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductRepository;
import org.jboss.pnc.spi.datastore.repositories.ProductVersionRepository;
import org.jboss.pnc.spi.datastore.repositories.ProjectRepository;
import org.jboss.pnc.spi.datastore.repositories.RepositoryConfigurationRepository;
import org.jboss.pnc.spi.datastore.repositories.SequenceHandlerRepository;
import org.jboss.pnc.spi.datastore.repositories.TargetRepositoryRepository;
import org.jboss.pnc.spi.datastore.repositories.UserRepository;

import javax.ejb.Singleton;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import static org.jboss.pnc.spi.datastore.predicates.ArtifactPredicates.withIdentifierAndSha256;

/**
 * Data for the DEMO. Note: The database initialization requires two separate transactions in order for the build
 * configuration audit record to be created and then linked to a build record.
 */
@Singleton
public class DatabaseDataInitializer {

    public static final Logger log = Logger.getLogger(DatabaseDataInitializer.class.getName());

    public static final String PNC_PRODUCT_NAME = "Project Newcastle Demo Product";

    public static final String PNC_PRODUCT_VERSION_1 = "1.0";

    public static final String PNC_PRODUCT_VERSION_2 = "2.0";

    public static final String PNC_PRODUCT_RELEASE = "1.0.0.GA";

    public static final String PNC_PRODUCT_MILESTONE1 = "1.0.0.Build1";

    public static final String PNC_PRODUCT_MILESTONE2 = "1.0.0.Build2";

    public static final String PNC_PRODUCT_MILESTONE3 = "1.0.0.Build3";

    public static final String PNC_PROJECT_1_NAME = "Project Newcastle Demo Project 1";

    public static final String PNC_PROJECT_BUILD_CFG_ID = "pnc-1.0.0.DR1";

    @Inject
    private ArtifactRepository artifactRepository;

    @Inject
    private ArtifactAuditedRepository artifactAuditedRepository;

    @Inject
    private TargetRepositoryRepository targetRepositoryRepository;

    @Inject
    private ProjectRepository projectRepository;

    @Inject
    private ProductRepository productRepository;

    @Inject
    private RepositoryConfigurationRepository repositoryConfigurationRepository;

    @Inject
    private BuildConfigurationRepository buildConfigurationRepository;

    @Inject
    BuildConfigurationAuditedRepository buildConfigurationAuditedRepository;

    @Inject
    private ProductVersionRepository productVersionRepository;

    @Inject
    private ProductMilestoneRepository productMilestoneRepository;

    @Inject
    private ProductMilestoneReleaseRepository productMilestoneReleaseRepository;

    @Inject
    private ProductReleaseRepository productReleaseRepository;

    @Inject
    private BuildConfigurationSetRepository buildConfigurationSetRepository;

    @Inject
    private UserRepository userRepository;

    @Inject
    private BuildRecordRepository buildRecordRepository;

    @Inject
    private BuildConfigSetRecordRepository buildConfigSetRecordRepository;

    @Inject
    private BuildEnvironmentRepository environmentRepository;

    @Inject
    private SequenceHandlerRepository sequenceHandlerRepository;

    @Inject
    private Datastore datastore;

    @Inject
    DemoDataConfig demoDataConfig;

    @Inject
    SystemConfig systemConfig;

    BuildConfiguration buildConfiguration1;

    BuildConfiguration buildConfiguration2;

    BuildConfigurationSet buildConfigurationSet1;

    ProductMilestone demoProductMilestone1;

    User demoUser;

    User pncAdminUser;

    public void verifyData() {
        // Check number of entities in DB
        Preconditions.checkState(projectRepository.count() > 0, "Expecting number of Projects > 0");
        Preconditions.checkState(productRepository.count() > 0, "Expecting number of Products > 0");
        Preconditions
                .checkState(buildConfigurationRepository.count() > 0, "Expecting number of BuildConfigurations > 0");
        Preconditions.checkState(productVersionRepository.count() > 0, "Expecting number of ProductVersions > 0");
        Preconditions
                .checkState(buildConfigurationSetRepository.count() > 0, "Expecting number of BuildRepositorySets > 0");
        Preconditions.checkState(artifactRepository.count() > 0, "Expecting number of Artifacts > 0");

        BuildConfiguration buildConfigurationDB = buildConfigurationRepository.queryAll().get(0);

        // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated
        BuildConfigurationSet buildConfigurationSet = buildConfigurationDB.getBuildConfigurationSets()
                .iterator()
                .next();
        Preconditions.checkState(
                buildConfigurationSet.getProductVersion() != null,
                "Product version of buildConfiguration must be not null");

        BuildConfigurationSet buildConfigurationSetDB = buildConfigurationSetRepository.queryAll().get(0);

        Preconditions.checkState(
                buildConfigurationSetDB.getProductVersion() != null,
                "Product version of buildConfigurationSet must be not null");

        // Check that mapping between Product and Build Configuration via BuildConfigurationSet is correct
        Preconditions.checkState(
                buildConfigurationSetDB.getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME),
                "Product mapped to Project must be " + PNC_PRODUCT_NAME);
        Preconditions.checkState(
                buildConfigurationSetDB.getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION_1),
                "Product version mapped to Project must be " + PNC_PRODUCT_VERSION_1);

        // Check that BuildConfiguration and BuildConfigurationSet have a ProductVersion associated
        Preconditions.checkState(
                buildConfigurationSet.getProductVersion().getVersion().equals(PNC_PRODUCT_VERSION_1),
                "Product version mapped to BuildConfiguration must be " + PNC_PRODUCT_VERSION_1);
        Preconditions.checkState(
                buildConfigurationSet.getProductVersion().getProduct().getName().equals(PNC_PRODUCT_NAME),
                "Product mapped to BuildConfiguration must be " + PNC_PRODUCT_NAME);

        // Check data of BuildConfiguration
        Preconditions.checkState(
                buildConfigurationDB.getProject().getName().equals(PNC_PROJECT_1_NAME),
                "Project mapped to BuildConfiguration must be " + PNC_PROJECT_1_NAME);

    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void initiliazeProjectProductData() {

        BuildEnvironment environment1Unsaved = BuildEnvironment.Builder.newBuilder()
                .name("Demo Environment 1")
                .description("Basic Java and Maven Environment")
                .attribute("JDK", "1.7.0")
                .attribute("OS", "Linux")
                .systemImageId("12345678")
                .systemImageRepositoryUrl("my.registry/newcastle")
                .systemImageType(SystemImageType.DOCKER_IMAGE)
                .deprecated(false)
                .build();
        BuildEnvironment environment1 = environmentRepository.save(environment1Unsaved);

        BuildEnvironment environment2Unsaved = BuildEnvironment.Builder.newBuilder()
                .name("Demo Environment 2")
                .description("Basic Java and Maven Environment")
                .attribute("JDK", "1.7.0")
                .attribute("OS", "Linux")
                .systemImageId("12345679")
                .systemImageRepositoryUrl("my.registry/newcastle")
                .systemImageType(SystemImageType.DOCKER_IMAGE)
                .deprecated(true)
                .build();
        BuildEnvironment environment2 = environmentRepository.save(environment2Unsaved);

        /*
         * All the bi-directional mapping settings are managed inside the Builders
         */
        // Example product and product version
        Product product = Product.Builder.newBuilder()
                .name(PNC_PRODUCT_NAME)
                .abbreviation("PNC")
                .description("Example Product for Project Newcastle Demo")
                .build();
        product = productRepository.save(product);

        // Example product version, release, and milestone of the product
        ProductVersion productVersion1 = ProductVersion.Builder.newBuilder()
                .version(PNC_PRODUCT_VERSION_1)
                .product(product)
                .generateBrewTagPrefix(
                        product.getAbbreviation(),
                        PNC_PRODUCT_VERSION_1,
                        systemConfig.getBrewTagPattern())
                .build();
        productVersion1 = productVersionRepository.save(productVersion1);

        ProductVersion productVersion2 = ProductVersion.Builder.newBuilder()
                .version(PNC_PRODUCT_VERSION_2)
                .product(product)
                .generateBrewTagPrefix(
                        product.getAbbreviation(),
                        PNC_PRODUCT_VERSION_2,
                        systemConfig.getBrewTagPattern())
                .build();
        productVersion2 = productVersionRepository.save(productVersion2);

        final int DAYS_IN_A_WEEK = 7;
        final Date TODAY = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
        final Date ONE_WEEK_BEFORE_TODAY = Date
                .from(LocalDateTime.now().minusDays(DAYS_IN_A_WEEK).atZone(ZoneId.systemDefault()).toInstant());
        final Date ONE_WEEK_AFTER_TODAY = Date
                .from(LocalDateTime.now().plusDays(DAYS_IN_A_WEEK).atZone(ZoneId.systemDefault()).toInstant());

        demoProductMilestone1 = ProductMilestone.Builder.newBuilder()
                .version(PNC_PRODUCT_MILESTONE1)
                .startingDate(ONE_WEEK_BEFORE_TODAY)
                .plannedEndDate(TODAY)
                .productVersion(productVersion1)
                .build();
        demoProductMilestone1 = productMilestoneRepository.save(demoProductMilestone1);

        ProductMilestone demoProductMilestone2 = ProductMilestone.Builder.newBuilder()
                .version(PNC_PRODUCT_MILESTONE2)
                .startingDate(TODAY)
                .plannedEndDate(ONE_WEEK_AFTER_TODAY)
                .productVersion(productVersion1)
                .build();
        demoProductMilestone2 = productMilestoneRepository.save(demoProductMilestone2);

        Instant t0 = TODAY.toInstant();
        Instant successTime = t0.plus(10, ChronoUnit.MINUTES);

        ProductMilestone demoProductMilestone3 = ProductMilestone.Builder.newBuilder()
                .version(PNC_PRODUCT_MILESTONE3)
                .startingDate(TODAY)
                .plannedEndDate(ONE_WEEK_AFTER_TODAY)
                .endDate(ONE_WEEK_AFTER_TODAY)
                .productVersion(productVersion1)
                .build();
        demoProductMilestone3 = productMilestoneRepository.save(demoProductMilestone3);

        ProductMilestoneRelease milestoneRelease1 = new ProductMilestoneRelease();
        milestoneRelease1.setId(Sequence.nextId());
        milestoneRelease1.setMilestone(demoProductMilestone3);
        // first store with latter starting date to test sort function
        milestoneRelease1.setStartingDate(Date.from(t0.plus(2, ChronoUnit.MINUTES)));
        milestoneRelease1.setStatus(MilestoneCloseStatus.SYSTEM_ERROR);
        productMilestoneReleaseRepository.save(milestoneRelease1);

        ProductMilestoneRelease milestoneRelease2 = new ProductMilestoneRelease();
        milestoneRelease2.setId(Sequence.nextId());
        milestoneRelease2.setMilestone(demoProductMilestone3);
        milestoneRelease2.setStartingDate(Date.from(t0));
        milestoneRelease2.setStatus(MilestoneCloseStatus.FAILED);
        productMilestoneReleaseRepository.save(milestoneRelease2);

        ProductMilestoneRelease milestoneRelease3 = new ProductMilestoneRelease();
        milestoneRelease3.setId(Sequence.nextId());
        milestoneRelease3.setMilestone(demoProductMilestone3);
        milestoneRelease3.setStartingDate(Date.from(successTime));
        milestoneRelease3.setStatus(MilestoneCloseStatus.SUCCEEDED);
        productMilestoneReleaseRepository.save(milestoneRelease3);

        ProductRelease productRelease = ProductRelease.Builder.newBuilder()
                .version(PNC_PRODUCT_RELEASE)
                .productMilestone(demoProductMilestone1)
                .supportLevel(SupportLevel.EARLYACCESS)
                .build();
        productRelease = productReleaseRepository.save(productRelease);

        productVersion1.setCurrentProductMilestone(demoProductMilestone3);
        productVersion1 = productVersionRepository.save(productVersion1);

        // Example projects
        Project project1 = Project.Builder.newBuilder()
                .name(PNC_PROJECT_1_NAME)
                .description("Example Project for Newcastle Demo")
                .projectUrl("https://github.com/project-ncl/pnc")
                .build();
        Project project2 = Project.Builder.newBuilder()
                .name("Causeway")
                .description("Causeway - Koji integration")
                .projectUrl("https://github.com/project-ncl/causeway")
                .build();
        Project project3 = Project.Builder.newBuilder()
                .name("Pnc Build Agent")
                .description("Pnc Build Agent - remote client to execute commands.")
                .projectUrl("https://github.com/project-ncl/pnc-build-agent")
                .build();
        Project project4 = Project.Builder.newBuilder()
                .name("Dependency Analysis")
                .description("Dependency Analysis - Analise project dependencies.")
                .projectUrl("https://github.com/project-ncl/dependency-analysis")
                .build();
        Project project5 = Project.Builder.newBuilder()
                .name("termd")
                .description("Remote shell.")
                .projectUrl("https://github.com/project-ncl/termd")
                .build();

        projectRepository.save(project1);
        projectRepository.save(project2);
        projectRepository.save(project3);
        projectRepository.save(project4);
        projectRepository.save(project5);

        RepositoryConfiguration repositoryConfiguration1 = createRepositoryConfiguration(
                demoDataConfig.getInternalRepo(0),
                "https://github.com/project-ncl/pnc.git");
        RepositoryConfiguration repositoryConfiguration2 = createRepositoryConfiguration(
                demoDataConfig.getInternalRepo(1),
                null);
        RepositoryConfiguration repositoryConfiguration3 = createRepositoryConfiguration(
                demoDataConfig.getInternalRepo(2),
                null);
        RepositoryConfiguration repositoryConfiguration4 = createRepositoryConfiguration(
                demoDataConfig.getInternalRepo(3),
                null);
        RepositoryConfiguration repositoryConfiguration5 = createRepositoryConfiguration(
                demoDataConfig.getInternalRepo(4),
                null);

        repositoryConfigurationRepository.save(repositoryConfiguration1);
        repositoryConfigurationRepository.save(repositoryConfiguration2);
        repositoryConfigurationRepository.save(repositoryConfiguration3);
        repositoryConfigurationRepository.save(repositoryConfiguration4);
        repositoryConfigurationRepository.save(repositoryConfiguration5);

        // Example build configurations
        Map<String, String> genericParameters = new HashMap<>();
        genericParameters.put("KEY", "VALUE");
        buildConfiguration1 = BuildConfiguration.Builder.newBuilder()
                .id(sequenceHandlerRepository.getNextID(BuildConfiguration.SEQUENCE_NAME).intValue())
                .name(PNC_PROJECT_BUILD_CFG_ID)
                .project(project1)
                .description("Test build config for project newcastle")
                .buildType(BuildType.MVN)
                .buildEnvironment(environment1)
                .buildScript("mvn deploy -DskipTests=true")
                .repositoryConfiguration(repositoryConfiguration1)
                .productVersion(productVersion1)
                .scmRevision("*/v0.2")
                .genericParameters(genericParameters)
                .build();
        buildConfiguration1 = buildConfigurationRepository.save(buildConfiguration1);

        buildConfiguration2 = BuildConfiguration.Builder.newBuilder()
                .id(sequenceHandlerRepository.getNextID(BuildConfiguration.SEQUENCE_NAME).intValue())
                .name("termd")
                .project(project2)
                .buildType(BuildType.MVN)
                .description("Test configueration for Termd.")
                .buildEnvironment(environment1)
                .buildScript("mvn deploy -DskipTests=true")
                .productVersion(productVersion1)
                .repositoryConfiguration(repositoryConfiguration2)
                .scmRevision("master")
                .build();
        buildConfiguration2 = buildConfigurationRepository.save(buildConfiguration2);

        BuildConfiguration buildConfiguration3 = BuildConfiguration.Builder.newBuilder()
                .id(sequenceHandlerRepository.getNextID(BuildConfiguration.SEQUENCE_NAME).intValue())
                .name("pnc-build-agent-0.4")
                .project(project3)
                .description("Test config for Pnc Build Agent.")
                .buildType(BuildType.MVN)
                .buildEnvironment(environment1)
                .buildScript("mvn deploy -DskipTests=true")
                .productVersion(productVersion2)
                .repositoryConfiguration(repositoryConfiguration3)
                .dependency(buildConfiguration2)
                .build();
        buildConfiguration3 = buildConfigurationRepository.save(buildConfiguration3);

        BuildConfiguration buildConfiguration4 = BuildConfiguration.Builder.newBuilder()
                .id(sequenceHandlerRepository.getNextID(BuildConfiguration.SEQUENCE_NAME).intValue())
                .name("dependency-analysis-1.3")
                .project(project4)
                .description("Test config for Dependency Analysis.")
                .buildType(BuildType.MVN)
                .buildEnvironment(environment1)
                .buildScript("mvn deploy -DskipTests=true")
                .repositoryConfiguration(repositoryConfiguration4)
                .dependency(buildConfiguration1)
                .build();
        buildConfiguration4 = buildConfigurationRepository.save(buildConfiguration4);

        BuildConfiguration buildConfiguration5 = BuildConfiguration.Builder.newBuilder()
                .id(sequenceHandlerRepository.getNextID(BuildConfiguration.SEQUENCE_NAME).intValue())
                .name("maven-plugin-test")
                .project(project5)
                .description("Test build for Plugins with external downloads")
                .buildType(BuildType.MVN)
                .buildEnvironment(environment1)
                .buildScript("mvn clean deploy")
                .repositoryConfiguration(repositoryConfiguration5)
                .build();
        buildConfiguration5 = buildConfigurationRepository.save(buildConfiguration5);

        // Build config set containing the three example build configs
        buildConfigurationSet1 = BuildConfigurationSet.Builder.newBuilder()
                .name("Example Build Group 1")
                .buildConfiguration(buildConfiguration1)
                .buildConfiguration(buildConfiguration2)
                .buildConfiguration(buildConfiguration3)
                .productVersion(productVersion1)
                .build();

        BuildConfigurationSet buildConfigurationSet2 = BuildConfigurationSet.Builder.newBuilder()
                .name("Fabric Build Group")
                .buildConfiguration(buildConfiguration4)
                .productVersion(productVersion1)
                .build();

        demoUser = User.Builder.newBuilder()
                .username("demo-user")
                .firstName("Demo First Name")
                .lastName("Demo Last Name")
                .email("demo-user@pnc.com")
                .build();

        pncAdminUser = User.Builder.newBuilder()
                .username("pnc-admin")
                .firstName("pnc-admin")
                .lastName("pnc-admin")
                .email("pnc-admin@pnc.com")
                .build();

        buildConfigurationSetRepository.save(buildConfigurationSet1);
        buildConfigurationSetRepository.save(buildConfigurationSet2);
        demoUser = userRepository.save(demoUser);
        pncAdminUser = userRepository.save(pncAdminUser);

    }

    /**
     * Build record needs to be initialized in a separate transaction so that the audited build configuration can be
     * set.
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void initiliazeBuildRecordDemoData() {

        TargetRepository targetRepository = TargetRepository.newBuilder()
                .repositoryType(RepositoryType.MAVEN)
                .repositoryPath("builds-untested")
                .identifier("indy-maven")
                .temporaryRepo(false)
                .build();

        targetRepositoryRepository.save(targetRepository);

        Artifact builtArtifact1 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact1:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 1")
                .md5("4af310bf0ef67bc7d143f35818ea1ed2")
                .sha1("3a8ff25c890f2a4a283876a91037ff6c57474a14")
                .sha256("1660168483cb8a05d1cc2e77c861682a42ed9517ba945159d5538950c5db00fa")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .build();
        Artifact builtArtifact2 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact2:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 2")
                .md5("4af310bf0ef67bc7d143f35818ea1ed2")
                .sha1("61dad16e14438d2d8c8cbd18b267d62944f37898")
                .sha256("2fafc2ed0f752ac2540283d48c5cd663254a853c5cb13dec02dce023fc7471a9")
                .size(11L)
                .artifactQuality(ArtifactQuality.NEW)
                .build();
        Artifact builtArtifact3 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact11:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 11")
                .md5("5c8e1503e77dc8e370610098e01f0a8e")
                .sha1("550748f6f58ed8d4f6b63850a867ac207da30013")
                .sha256("b39f88c9937f201981767e539025121971e72bc590ea20ed7fdfffafc05f55a9")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .build();
        Artifact builtArtifact4 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact22:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 21")
                .md5("48312fb24c7b2a116c2139d5b39bad66")
                .sha1("6ce2fd75c35e7eed2c45338b943be34d0b974f16")
                .sha256("61c9ccd3ba0013311ddb89cb9a29389b6761061bdcdfb48f0096bf98c7279a21")
                .size(11L)
                .artifactQuality(ArtifactQuality.NEW)
                .build();

        builtArtifact1 = artifactRepository.save(builtArtifact1);
        builtArtifact2 = artifactRepository.save(builtArtifact2);
        builtArtifact3 = artifactRepository.save(builtArtifact3);
        builtArtifact4 = artifactRepository.save(builtArtifact4);

        Artifact importedArtifact1 = Artifact.Builder.newBuilder()
                .identifier("demo:imported-artifact1:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo imported artifact 1")
                .originUrl("http://central/import1.jar")
                .importDate(Date.from(Instant.now()))
                .md5("md-fake-abcd1234")
                .sha1("sha1-fake-abcd1234")
                .sha256("sha256-fake-abcd1234")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/imported1")
                .build();
        Artifact importedArtifact2 = Artifact.Builder.newBuilder()
                .identifier("demo:imported-artifact2:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo imported artifact 2")
                .originUrl("http://central/import2.jar")
                .importDate(Date.from(Instant.now()))
                .md5("md-fake-abcd1234")
                .sha1("sha1-fake-abcd1234")
                .sha256("sha256-fake-abcd1234")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/imported2")
                .build();

        importedArtifact1 = artifactRepository.save(importedArtifact1);
        importedArtifact2 = artifactRepository.save(importedArtifact2);

        Set<BuildRecord> buildRecords = new HashSet<>();

        final int INITIAL_REVISION = 1;
        IdRev buildConfig1AuditIdRev = new IdRev(buildConfiguration1.getId(), INITIAL_REVISION);
        BuildConfigurationAudited buildConfigAudited1 = buildConfigurationAuditedRepository
                .queryById(buildConfig1AuditIdRev);
        if (buildConfigAudited1 != null) {

            int nextId = datastore.getNextBuildRecordId();
            log.info("####nextId: " + nextId);

            BuildRecord buildRecord1 = BuildRecord.Builder.newBuilder()
                    .id(nextId)
                    .buildConfigurationAudited(buildConfigAudited1)
                    .submitTime(Timestamp.from(Instant.now().minus(8, ChronoUnit.MINUTES)))
                    .startTime(Timestamp.from(Instant.now().minus(5, ChronoUnit.MINUTES)))
                    .endTime(Timestamp.from(Instant.now()))
                    .dependency(importedArtifact1)
                    .dependency(importedArtifact2)
                    .user(pncAdminUser)
                    .repourLog("This is a wannabe alignment log.")
                    .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.")
                    .status(BuildStatus.SUCCESS)
                    .productMilestone(demoProductMilestone1)
                    .sshCommand("ssh worker@localhost -P 9999")
                    .sshPassword("dontchangeme")
                    .buildEnvironment(buildConfigAudited1.getBuildEnvironment())
                    .scmRepoURL(buildConfigAudited1.getRepositoryConfiguration().getInternalUrl())
                    .scmRevision(buildConfigAudited1.getScmRevision())
                    .executionRootName("org.jboss.pnc:parent")
                    .executionRootVersion("1.2.3")
                    .temporaryBuild(false)
                    .build();

            log.info("Saving buildRecord1: " + buildRecord1);
            BuildRecord savedBuildRecord1 = buildRecordRepository.save(buildRecord1);
            builtArtifact1.setBuildRecord(savedBuildRecord1);
            builtArtifact2.setBuildRecord(savedBuildRecord1);

            log.info(
                    "Saved buildRecord1: " + savedBuildRecord1 + "BuildConfigurationAuditedIdRev: "
                            + savedBuildRecord1.getBuildConfigurationAuditedIdRev());
            buildRecords.add(buildRecord1);

            nextId = datastore.getNextBuildRecordId();
            log.info("####nextId: " + nextId);

            BuildRecord tempRecord1 = BuildRecord.Builder.newBuilder()
                    .id(nextId)
                    .buildConfigurationAudited(buildConfigAudited1)
                    .submitTime(Timestamp.from(Instant.now()))
                    .startTime(Timestamp.from(Instant.now()))
                    .endTime(Timestamp.from(Instant.now()))
                    .user(pncAdminUser)
                    .repourLog("This is a wannabe alignment log.")
                    .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.")
                    .status(BuildStatus.SUCCESS)
                    .buildEnvironment(buildConfigAudited1.getBuildEnvironment())
                    .scmRepoURL(buildConfigAudited1.getRepositoryConfiguration().getInternalUrl())
                    .scmRevision(buildConfigAudited1.getScmRevision())
                    .executionRootName("org.jboss.pnc:parent")
                    .executionRootVersion("1.2.3")
                    .temporaryBuild(true)
                    .build();

            log.info("Saving tempRecord1: " + tempRecord1);
            BuildRecord savedTempRecord1 = buildRecordRepository.save(tempRecord1);
            builtArtifact3.setBuildRecord(savedTempRecord1);
            builtArtifact4.setBuildRecord(savedTempRecord1);
            log.info(
                    "Saved buildRecord1: " + savedTempRecord1 + "BuildConfigurationAuditedIdRev: "
                            + savedTempRecord1.getBuildConfigurationAuditedIdRev());
            buildRecords.add(tempRecord1);

        }

        Artifact builtArtifact5 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact3:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 3")
                .md5("17353a18678c6c249e3052edec2e4c5c")
                .sha1("61dad16e14438d2d8c8cbd18b267d62944f37898")
                .sha256("1660168483cb8a05d1cc2e77c861682a42ed9517ba945159d5538950c5db00fa")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/built3")
                .build();
        Artifact builtArtifact6 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact4:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 4")
                .md5("md-fake-abcd1234")
                .sha1("sha1-fake-abcd1234")
                .sha256("sha256-fake-abcd1234")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/built4")
                .build();

        Artifact builtArtifact7 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact5:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 7")
                .md5("adsfs6df548w1327cx78he873217df98")
                .sha1("a56asdf87a3cvx231b87987fasd6f5ads4f32sdf")
                .sha256("sad5f64sf87b3cvx2b1v87tr89h7d3f5g432xcz1zv87fawrv23n8796534564er")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/built5")
                .build();
        Artifact builtArtifact8 = Artifact.Builder.newBuilder()
                .identifier("demo:built-artifact6:jar:1.0")
                .targetRepository(targetRepository)
                .filename("demo built artifact 8")
                .md5("md-fake-abcdefg1234")
                .sha1("sha1-fake-abcdefg1234")
                .sha256("sha256-fake-abcdefg1234")
                .size(10L)
                .artifactQuality(ArtifactQuality.NEW)
                .deployPath("/built6")
                .build();

        builtArtifact5 = artifactRepository.save(builtArtifact5);
        builtArtifact6 = artifactRepository.save(builtArtifact6);
        builtArtifact7 = artifactRepository.save(builtArtifact7);
        builtArtifact8 = artifactRepository.save(builtArtifact8);

        Artifact dependencyBuiltArtifact1 = artifactRepository
                .queryByPredicates(withIdentifierAndSha256(builtArtifact1.getIdentifier(), builtArtifact1.getSha256()));

        // For timestamp tests where concrete timestamp is needed
        Calendar calendar = Calendar.getInstance();
        calendar.set(2019, Calendar.JANUARY, 10);
        IdRev buildConfig2AuditIdRev = new IdRev(buildConfiguration2.getId(), INITIAL_REVISION);
        BuildConfigurationAudited buildConfigAudited2 = buildConfigurationAuditedRepository
                .queryById(buildConfig2AuditIdRev);
        if (buildConfigAudited2 != null) {

            int nextId = datastore.getNextBuildRecordId();
            log.info("####nextId: " + nextId);

            BuildRecord buildRecord2 = BuildRecord.Builder.newBuilder()
                    .id(nextId)
                    .buildConfigurationAudited(buildConfigAudited2)
                    .submitTime(Timestamp.from(Instant.now().minus(8, ChronoUnit.MINUTES)))
                    .startTime(Timestamp.from(Instant.now().minus(5, ChronoUnit.MINUTES)))
                    .endTime(Timestamp.from(Instant.now()))
                    .dependency(dependencyBuiltArtifact1)
                    .dependency(importedArtifact1)
                    .user(demoUser)
                    .buildLog("Very short demo log: The quick brown fox jumps over the lazy dog.")
                    .status(BuildStatus.SUCCESS)
                    .buildEnvironment(buildConfigAudited2.getBuildEnvironment())
                    .executionRootName("org.jboss.pnc:parent")
                    .executionRootVersion("1.2.4")
                    .temporaryBuild(false)
                    .build();

            nextId = datastore.getNextBuildRecordId();
            log.info("####nextId: " + nextId);

            BuildRecord savedBuildRecord2 = buildRecordRepository.save(buildRecord2);
            builtArtifact5.setBuildRecord(savedBuildRecord2);
            builtArtifact6.setBuildRecord(savedBuildRecord2);
            buildRecords.add(buildRecord2);

            BuildRecord tempRecord1 = BuildRecord.Builder.newBuilder()
                    .id(nextId)
                    .buildConfigurationAudited(buildConfigAudited2)
                    .submitTime(Timestamp.from(calendar.toInstant().minus(8, ChronoUnit.HOURS)))
                    .startTime(Timestamp.from(calendar.toInstant().minus(5, ChronoUnit.HOURS)))
                    .endTime(Timestamp.from(calendar.toInstant()))
                    .user(demoUser)
                    .buildLog("Is it free?")
                    .status(BuildStatus.SUCCESS)
                    .buildEnvironment(buildConfigAudited2.getBuildEnvironment())
                    .executionRootName("org.jboss.pnc:parent")
                    .executionRootVersion("1.2.4")
                    .temporaryBuild(true)
                    .build();

            BuildRecord savedTempRecord1 = buildRecordRepository.save(tempRecord1);

            builtArtifact7.setBuildRecord(savedTempRecord1);
            builtArtifact8.setBuildRecord(savedTempRecord1);
            buildRecords.add(tempRecord1);
        }

        BuildConfigSetRecord buildConfigSetRecord1 = BuildConfigSetRecord.Builder.newBuilder()
                .buildConfigurationSet(buildConfigurationSet1)
                .startTime(Timestamp.from(Instant.now()))
                .endTime(Timestamp.from(Instant.now()))
                .user(demoUser)
                .status(BuildStatus.FAILED)
                .temporaryBuild(false)
                .build();
        buildConfigSetRecordRepository.save(buildConfigSetRecord1);

        BuildConfigSetRecord buildConfigSetRecord2 = BuildConfigSetRecord.Builder.newBuilder()
                .buildConfigurationSet(buildConfigurationSet1)
                .buildRecords(buildRecords)
                .startTime(Timestamp.from(Instant.now()))
                .endTime(Timestamp.from(Instant.now()))
                .user(demoUser)
                .status(BuildStatus.SUCCESS)
                .temporaryBuild(false)
                .build();
        buildConfigSetRecordRepository.save(buildConfigSetRecord2);

        BuildConfigSetRecord buildConfigSetRecord3 = BuildConfigSetRecord.Builder.newBuilder()
                .buildConfigurationSet(buildConfigurationSet1)
                .startTime(Timestamp.from(calendar.toInstant().minus(20, ChronoUnit.DAYS)))
                .endTime(Timestamp.from(calendar.toInstant().minus(20, ChronoUnit.DAYS)))
                .user(demoUser)
                .status(BuildStatus.SUCCESS)
                .temporaryBuild(true)
                .build();
        buildConfigSetRecordRepository.save(buildConfigSetRecord3);

        demoProductMilestone1 = productMilestoneRepository.queryById(demoProductMilestone1.getId());
        demoProductMilestone1.addDistributedArtifact(builtArtifact1);
        demoProductMilestone1.addDistributedArtifact(builtArtifact5);
        demoProductMilestone1.addDistributedArtifact(importedArtifact2);
        demoProductMilestone1 = productMilestoneRepository.save(demoProductMilestone1);
    }

    private RepositoryConfiguration createRepositoryConfiguration(String internalScmUrl, String externalUrl) {
        return RepositoryConfiguration.Builder.newBuilder()
                .internalUrl(internalScmUrl)
                .externalUrl(externalUrl)
                .build();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.me.helloswiftworld">
  <!-- the android:debuggable="true" attribute is overwritten by the compiler when the debug info option is set -->
  <application android:label="@string/app_name" android:icon="@drawable/icon" android:debuggable="true">
    <activity android:label="@string/app_name" android:name="org.me.helloswiftworld.MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
  <uses-sdk android:minSdkVersion="4" />
</manifest>

redpajama_set_name: RedPajamaGithub


text:
<?php

use DTS\eBaySDK\Trading\Types\GetApiAccessRulesResponseType;

class GetApiAccessRulesResponseTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new GetApiAccessRulesResponseType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\GetApiAccessRulesResponseType', $this->obj);
    }

    public function testExtendsAbstractResponseType()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\Trading\Types\AbstractResponseType', $this->obj);
    }
}


text:
package org.apache.kylin.rest.service;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.kylin.common.KylinConfig;
import org.apache.kylin.common.util.CliCommandExecutor;
import org.apache.kylin.common.util.Pair;
import org.apache.kylin.metadata.badquery.BadQueryEntry;
import org.apache.kylin.metadata.badquery.BadQueryHistory;
import org.apache.kylin.rest.exception.BadRequestException;
import org.apache.kylin.rest.msg.Message;
import org.apache.kylin.rest.msg.MsgPicker;
import org.apache.kylin.rest.util.AclEvaluate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

@Component("diagnosisService")
public class DiagnosisService extends BasicService {

    private static final Logger logger = LoggerFactory.getLogger(DiagnosisService.class);

    @Autowired
    private AclEvaluate aclEvaluate;

    @Autowired
    private JobService jobService;

    private String getDiagnosisPackageName(File destDir) {
        Message msg = MsgPicker.getMsg();

        File[] files = destDir.listFiles();
        if (files == null) {
            throw new BadRequestException(
                    String.format(Locale.ROOT, msg.getDIAG_PACKAGE_NOT_AVAILABLE(), destDir.getAbsolutePath()));
        }
        for (File subDir : files) {
            if (subDir.isDirectory()) {
                for (File file : subDir.listFiles()) {
                    if (file.getName().endsWith(".zip")) {
                        return file.getAbsolutePath();
                    }
                }
            }
        }
        throw new BadRequestException(
                String.format(Locale.ROOT, msg.getDIAG_PACKAGE_NOT_FOUND(), destDir.getAbsolutePath()));
    }

    public BadQueryHistory getProjectBadQueryHistory(String project) throws IOException {
        aclEvaluate.checkProjectOperationPermission(project);
        return getBadQueryHistoryManager().getBadQueriesForProject(project);
    }

    public String dumpProjectDiagnosisInfo(String project, File exportPath) throws IOException {
        aclEvaluate.checkProjectOperationPermission(project);
        String[] args = { project, exportPath.getAbsolutePath() };
        runDiagnosisCLI(args);
        return getDiagnosisPackageName(exportPath);
    }

    public String dumpJobDiagnosisInfo(String jobId, File exportPath) throws IOException {
        aclEvaluate.checkProjectOperationPermission(jobService.getJobInstance(jobId));
        String[] args = { jobId, exportPath.getAbsolutePath() };
        runDiagnosisCLI(args);
        return getDiagnosisPackageName(exportPath);
    }

    private void runDiagnosisCLI(String[] args) throws IOException {
        Message msg = MsgPicker.getMsg();

        File cwd = new File("");
        logger.debug("Current path: " + cwd.getAbsolutePath());

        logger.debug("DiagnosisInfoCLI args: " + Arrays.toString(args));
        File script = new File(KylinConfig.getKylinHome() + File.separator + "bin", "diag.sh");
        if (!script.exists()) {
            throw new BadRequestException(
                    String.format(Locale.ROOT, msg.getDIAG_NOT_FOUND(), script.getAbsolutePath()));
        }

        String diagCmd = script.getAbsolutePath() + " " + StringUtils.join(args, " ");
        CliCommandExecutor executor = KylinConfig.getInstanceFromEnv().getCliCommandExecutor();
        Pair<Integer, String> cmdOutput = executor.execute(diagCmd);

        if (cmdOutput.getFirst() != 0) {
            throw new BadRequestException(msg.getGENERATE_DIAG_PACKAGE_FAIL());
        }
    }

    public List<BadQueryEntry> getQueriesByType(List<BadQueryEntry> allBadEntries, String queryType)
            throws IOException {

        List<BadQueryEntry> filteredEntries = Lists.newArrayList();
        for (BadQueryEntry entry : allBadEntries) {
            if (null != entry && entry.getAdj().equals(queryType)) {
                filteredEntries.add(entry);
            }
        }
        return filteredEntries;
    }

    public Map<String, Object> getQueries(Integer pageOffset, Integer pageSize, String queryType,
            List<BadQueryEntry> allBadEntries) throws IOException {
        HashMap<String, Object> data = new HashMap<>();
        List<BadQueryEntry> filteredEntries = getQueriesByType(allBadEntries, queryType);

        int offset = pageOffset * pageSize;
        int limit = pageSize;

        if (filteredEntries.size() <= offset) {
            offset = filteredEntries.size();
            limit = 0;
        }

        if ((filteredEntries.size() - offset) < limit) {
            limit = filteredEntries.size() - offset;
        }

        data.put("badQueries", filteredEntries.subList(offset, offset + limit));
        data.put("size", filteredEntries.size());
        return data;
    }

}


text:
<template class="phase-template">

Section B

</template>


text: var sth = "sth"; //comment


text:
class CFileMatcher
{
public:
	CFileMatcher(LPTSTR pszMask);
	virtual ~CFileMatcher();
	static int FileNameMatch(LPCTSTR pattern, LPCTSTR string, BOOL fMatchedDot=FALSE);
	BOOL Match(LPTSTR pszName, BOOL fDirectory);

protected:
	void ParseMultiple(LPTSTR pszMultiple);
    TCHAR  m_szMultiple[MAX_PATH+2];
	LPTSTR m_pszDirBuffer;
	LPTSTR m_pszMask;
	LPTSTR m_pszMaskDir;
	LPTSTR m_pszMultipleDir;
	LPTSTR m_pszMultiple;
	BOOL m_fMatchAll;
	BOOL m_fMatchAllDir;
};


text:
.br-off {
  white-space: nowrap !important;
}

.br-on {
  white-space: normal !important;
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<dt-option library="Buttons">
	<name>buttons</name>
	<summary>Buttons configuration object</summary>
	<since>1.0.0</since>

	<type type="array">
		<description>
			The majority of button configurations are not concerned with the DOM configuration and other options that Buttons presents, but rather just with what buttons are presented and how they are individually constructed. As such, to provide a short-cut this option can be provided as an array. This array will be mapped automatically to the `b-init buttons.buttons` option.

			For example the following two configurations are functionally identical:

			```js
			// Using `buttons` as an array
			$('#myTable').DataTable( {
				buttons: [ 'copy', 'csv', 'excel' ]
			} );
			```

			```js
			// Using `buttons.buttons`
			$('#myTable').DataTable( {
				buttons: {
					buttons: [ 'copy', 'csv', 'excel' ]
				}
			} );
			```
		</description>
	</type>

	<type type="boolean">
		<description>
			As a boolean `true` value, this option will trigger the creation of a Buttons instance with the default values (as defined by `$.fn.dataTable.Buttons.defaults`).
		</description>
	</type>

	<type type="object">
		<description>
			As an object this option provides the ability to configure a single instance of the DataTables Buttons extension that will be created when the DataTable is initialised. For the full range of parameters that are available to be used in this object, please refer to the remainder of the Buttons initialisation reference.
		</description>
	</type>

	<description>
		This option provides the ability to have a Buttons instance created automatically when a new DataTable is created. The button collection can then be inserted into the DataTables controlled DOM by using the `B` option in the `dt-init dom` parameter, or through the `b-api buttons().container()` API method.
	</description>

	<example title="Creation of Buttons using defaults and insertion by `dt-init dom`"><![CDATA[

$('#example').DataTable( {
	dom: 'B<"clear">lfrtip',
	buttons: true
} );

]]></example>

	<example title="Creation of Buttons with array configuration of buttons and insertion by `dt-init dom`"><![CDATA[

$('#example').DataTable( {
	dom: 'B<"clear">lfrtip',
	buttons: [ 'copy', 'csv', 'excel' ]
} );

]]></example>

	<example title="Creation of Buttons with object configuration and insertion by `dt-init dom`"><![CDATA[

$('#example').DataTable( {
	dom: 'B<"clear">lfrtip',
	buttons: {
		name: 'primary',
		buttons: [ 'copy', 'csv', 'excel' ]
	}
} );

]]></example>

	<example title="Creation of Buttons using defaults are API insertion to the DOM"><![CDATA[

var table = $('#example').DataTable( {
	buttons: true
} );

table
	.buttons()
	.container()
	.appendTo( '#controlPanel' );

]]></example>
</dt-option>


text:
<!DOCTYPE html>

<html>

<head>
    <!--  basic meta information -->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta http-equiv="Content-Type" content="application/json; charset=utf-8">
    <meta content="width=device-width,initial-scale=1,maximum-scale=5,user-scalable=yes" name="viewport">

    <title>My ARchitect World</title>

    <link rel="stylesheet" href="world.css">
    <script src="architect://architect.js"></script>

    <!-- World logic-->
    <!-- <script type="text/javascript" src="ade.js"></script> -->
    <script type="text/javascript" src="world.js"></script>
</head>

<body onLoad="javascript:AR.logger.activateDebugMode();"></body>

</html>


text:
using JoinRpg.DataModel;
using JoinRpg.Domain;
using JoinRpg.Helpers;
using Newtonsoft.Json;

namespace JoinRpg.Web.Models.Accommodation;

public class AccRequestViewModel
{
    public int Id { get; protected set; }

    [JsonIgnore]
    public int ProjectId { get; protected set; }

    [JsonIgnore]
    public int AccommodationTypeId { get; protected set; }

    public int RoomId { get; protected set; }

    [JsonIgnore]
    public RoomViewModel Room { get; set; }

    [JsonIgnore]
    public IReadOnlyList<RequestParticipantViewModel> Participants { get; protected set; }

    public int Persons
        => Participants?.Count ?? 0;

    public string PersonsList => Participants.Select(p => p.UserName).JoinStrings(@", ");

    public object? Instance => null;

    public int FeeTotal { get; protected set; }

    public int FeeToPay { get; protected set; }

    public string PaymentStatusCssClass { get; protected set; }

    public string PaymentStatusTitle
        => FeeToPay > 0 ? $@"Не оплачено {FeeToPay} из {FeeTotal}" : "Все оплачено полностью";

    public AccRequestViewModel(AccommodationRequest entity)
    {
        Id = entity.Id;
        ProjectId = entity.ProjectId;
        AccommodationTypeId = entity.AccommodationTypeId;
        RoomId = entity.AccommodationId ?? 0;
        Participants = entity.Subjects.Select(c => new RequestParticipantViewModel(c)).ToList();
        FeeTotal = Participants.Sum(p => p.FeeTotal);
        FeeToPay = Participants.Sum(p => p.FeeToPay);
        FeeToPay = FeeToPay > 0 ? FeeToPay : 0; // if FeeToPay < 0 we have overpaid
        var percent = FeeToPay == 0 ? 100 : (FeeToPay == FeeTotal ? 0 : 100 * FeeToPay / FeeTotal);
        PaymentStatusCssClass = percent == 100 ? @"success" : (percent >= 25 ? @"warning" : @"danger");
    }
}

public class RequestParticipantViewModel
{
    public int UserId;
    public User User;
    public int ClaimId;
    public Claim Claim;

    public int FeeToPay;
    public int FeeTotal;

    public string UserName
        => User?.GetDisplayName() ?? "";

    public RequestParticipantViewModel(Claim claim)
    {
        ClaimId = claim.ClaimId;
        Claim = claim;
        UserId = claim.PlayerUserId;
        User = claim.Player;
        FeeTotal = Claim.ClaimTotalFee();
        FeeToPay = Claim.ClaimFeeDue();
    }
}


text:
import {dict} from '#core/types/object';

import {isExperimentOn} from '#experiments';

import {userAssert} from '#utils/log';

import {BaseElement} from './base-element';

import {CSS} from '../../../build/amp-instagram-1.0.css';

/** @const {string} */
const TAG = 'amp-instagram';

class AmpInstagram extends BaseElement {
  /** @override */
  isLayoutSupported(layout) {
    userAssert(
      isExperimentOn(this.win, 'bento') ||
        isExperimentOn(this.win, 'bento-instagram'),
      'expected global "bento" or specific "bento-instagram" experiment to be enabled'
    );
    return super.isLayoutSupported(layout);
  }

  /** @override */
  init() {
    return dict({
      'requestResize': (height) => this.attemptChangeHeight(height),
    });
  }
}

AMP.extension(TAG, '1.0', (AMP) => {
  AMP.registerElement(TAG, AmpInstagram, CSS);
});


text:
import { RenovateConfig, getConfig, getName } from '../../../test/util';
import {
  CONFIG_SECRETS_EXPOSED,
  CONFIG_VALIDATION,
  EXTERNAL_HOST_ERROR,
  MANAGER_LOCKFILE_ERROR,
  NO_VULNERABILITY_ALERTS,
  PLATFORM_AUTHENTICATION_ERROR,
  PLATFORM_BAD_CREDENTIALS,
  PLATFORM_INTEGRATION_UNAUTHORIZED,
  PLATFORM_RATE_LIMIT_EXCEEDED,
  REPOSITORY_ACCESS_FORBIDDEN,
  REPOSITORY_ARCHIVED,
  REPOSITORY_BLOCKED,
  REPOSITORY_CANNOT_FORK,
  REPOSITORY_CHANGED,
  REPOSITORY_DISABLED,
  REPOSITORY_EMPTY,
  REPOSITORY_FORKED,
  REPOSITORY_MIRRORED,
  REPOSITORY_NOT_FOUND,
  REPOSITORY_NO_PACKAGE_FILES,
  REPOSITORY_RENAMED,
  REPOSITORY_UNINITIATED,
  SYSTEM_INSUFFICIENT_DISK_SPACE,
  SYSTEM_INSUFFICIENT_MEMORY,
  TEMPORARY_ERROR,
  UNKNOWN_ERROR,
} from '../../constants/error-messages';
import { ExternalHostError } from '../../types/errors/external-host-error';
import handleError from './error';

jest.mock('./error-config');

let config: RenovateConfig;
beforeEach(() => {
  jest.resetAllMocks();
  config = getConfig();
});

describe(getName(), () => {
  describe('handleError()', () => {
    const errors = [
      REPOSITORY_UNINITIATED,
      REPOSITORY_EMPTY,
      REPOSITORY_DISABLED,
      REPOSITORY_CHANGED,
      REPOSITORY_FORKED,
      REPOSITORY_NO_PACKAGE_FILES,
      CONFIG_SECRETS_EXPOSED,
      CONFIG_VALIDATION,
      REPOSITORY_ARCHIVED,
      REPOSITORY_MIRRORED,
      REPOSITORY_RENAMED,
      REPOSITORY_BLOCKED,
      REPOSITORY_NOT_FOUND,
      REPOSITORY_ACCESS_FORBIDDEN,
      PLATFORM_BAD_CREDENTIALS,
      PLATFORM_RATE_LIMIT_EXCEEDED,
      MANAGER_LOCKFILE_ERROR,
      SYSTEM_INSUFFICIENT_DISK_SPACE,
      SYSTEM_INSUFFICIENT_MEMORY,
      NO_VULNERABILITY_ALERTS,
      REPOSITORY_CANNOT_FORK,
      PLATFORM_INTEGRATION_UNAUTHORIZED,
      PLATFORM_AUTHENTICATION_ERROR,
      TEMPORARY_ERROR,
    ];
    errors.forEach((err) => {
      it(`errors ${err}`, async () => {
        const res = await handleError(config, new Error(err));
        expect(res).toEqual(err);
      });
    });
    it(`handles ExternalHostError`, async () => {
      const res = await handleError(
        config,
        new ExternalHostError(new Error(), 'some-host-type')
      );
      expect(res).toEqual(EXTERNAL_HOST_ERROR);
    });
    it('rewrites git 5xx error', async () => {
      const gitError = new Error(
        "fatal: unable to access 'https://**redacted**@gitlab.com/learnox/learnox.git/': The requested URL returned error: 500\n"
      );
      const res = await handleError(config, gitError);
      expect(res).toEqual(EXTERNAL_HOST_ERROR);
    });
    it('rewrites git remote error', async () => {
      const gitError = new Error(
        'fatal: remote error: access denied or repository not exported: /b/nw/bd/27/47/159945428/108610112.git\n'
      );
      const res = await handleError(config, gitError);
      expect(res).toEqual(EXTERNAL_HOST_ERROR);
    });
    it('rewrites git fatal error', async () => {
      const gitError = new Error(
        'fatal: not a git repository (or any parent up to mount point /mnt)\nStopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).\n'
      );
      const res = await handleError(config, gitError);
      expect(res).toEqual(TEMPORARY_ERROR);
    });
    it('handles unknown error', async () => {
      const res = await handleError(config, new Error('abcdefg'));
      expect(res).toEqual(UNKNOWN_ERROR);
    });
  });
});


text:
use serde::Deserialize;
use std::env;
use std::fs;
use std::io::{self, Write};
use std::path::PathBuf;

#[derive(Deserialize)]
struct Sections {
    #[serde(default)]
    expand: Config,
}

#[derive(Deserialize, Default)]
pub struct Config {
    pub theme: Option<String>,
    pub color: Option<String>,
    #[serde(default)]
    pub pager: bool,
    /// Format using rustfmt instead of prettyplease. This is significantly
    /// slower, and less reliable on macro-generated code, but produces more
    /// aesthetic formatting when it works.
    #[serde(default)]
    pub rustfmt: bool,
}

pub fn deserialize() -> Config {
    try_deserialize().unwrap_or_default()
}

fn try_deserialize() -> Option<Config> {
    let cargo_home = env::var_os("CARGO_HOME").map(PathBuf::from)?;
    let config_names = ["config", "config.toml"];
    let config_path = config_names
        .iter()
        .map(|name| cargo_home.join(name))
        .find(|path| path.exists())?;

    let content = fs::read(&config_path).ok()?;

    let full_config: Sections = match toml::from_slice(&content) {
        Ok(config) => config,
        Err(err) => {
            _ = writeln!(io::stderr(), "Warning: {}: {}", config_path.display(), err);
            return None;
        }
    };

    Some(full_config.expand)
}


text:
System.register(['angular2/core', './todo_list', './todo_form'], function(exports_1) {
    var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
        else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    var __metadata = (this && this.__metadata) || function (k, v) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
    };
    var core_1, todo_list_1, todo_form_1;
    var TodoApp;
    return {
        setters:[
            function (core_1_1) {
                core_1 = core_1_1;
            },
            function (todo_list_1_1) {
                todo_list_1 = todo_list_1_1;
            },
            function (todo_form_1_1) {
                todo_form_1 = todo_form_1_1;
            }],
        execute: function() {
            TodoApp = (function () {
                function TodoApp() {
                    this.todos = [
                        { text: 'learn angular', done: true },
                        { text: 'build an angular app', done: false }
                    ];
                }
                Object.defineProperty(TodoApp.prototype, "remaining", {
                    get: function () {
                        return this.todos.reduce(function (count, todo) { return count + +!todo.done; }, 0);
                    },
                    enumerable: true,
                    configurable: true
                });
                TodoApp.prototype.archive = function () {
                    var _this = this;
                    var oldTodos = this.todos;
                    this.todos = [];
                    oldTodos.forEach(function (todo) {
                        if (!todo.done)
                            _this.todos.push(todo);
                    });
                };
                TodoApp.prototype.addTask = function (task) {
                    this.todos.push(task);
                };
                TodoApp = __decorate([
                    core_1.Component({
                        selector: 'todo-app',
                        templateUrl: 'templates/todo-app.html',
                        directives: [todo_list_1.TodoList, todo_form_1.TodoForm]
                    }),
                    __metadata('design:paramtypes', [])
                ], TodoApp);
                return TodoApp;
            })();
            exports_1("TodoApp", TodoApp);
        }
    }
});
//# sourceMappingURL=todo_app.js.map


text:
<?php

namespace Phalcon\Tests\unit\Phalcon\Translate\Adapter\Csv;

use Phalcon\Translate\Adapter\Csv as PhTTranslateAdapterCsv;
use Phalcon\Translate\Exception as PhTTranslateException;
use \Codeception\TestCase\Test as CdTest;
use \Codeception\Specify as CdSpecify;

class TranslateCsvTest extends CdTest
{
    use CdSpecify;

    private $config = null;

    /**
     * Initialize data for the tests
     */
    public function _before()
    {
        $this->config = array(
            'ru' => array(
                'content' => PATH_DATA . 'translation/csv/ru_RU.csv',
            ),
        );
    }

    /**
     * Catch Exception
     *
     * @author Ivan Zubok <chi_no@ukr.net>
     * @since  2014-11-04
     */
    public function testContentParamExist()
    {
        $this->specify(
            "Parameter 'content' is required",
            function () {
                new PhTTranslateAdapterCsv(array());
            },
            ['throws' => new PhTTranslateException]
        );
    }

    /**
     * Tests whether a key not exists in the array
     *
     * @author Ivan Zubok <chi_no@ukr.net>
     * @since  2014-11-04
     */
    public function testNotExists()
    {
        $this->specify(
            "The key does not exist with exists",
            function () {
                $params = $this->config['ru'];
                $translator = new PhTTranslateAdapterCsv($params);

                expect($translator->exists('Hi!'))->false();
            }
        );
    }

    /**
     * Tests whether a key exists in the array
     *
     * @author Ivan Zubok <chi_no@ukr.net>
     * @since  2014-11-04
     */
    public function testExists()
    {
        $this->specify(
            "The key exist with expect",
            function () {
                $params = $this->config['ru'];
                $translator = new PhTTranslateAdapterCsv($params);

                expect($translator->exists('Hello!'))->true();
            }
        );
    }

    /**
     * Translate into russian
     *
     * @author Ivan Zubok <chi_no@ukr.net>
     * @since  2014-11-04
     */
    public function testRuTranslate()
    {
        $this->specify(
            "The key exist with expect with additional params",
            function () {
                $params = $this->config['ru'];
                $translator = new PhTTranslateAdapterCsv($params);

                expect($translator->query('Hello!'))->equals('Привет!');
                expect($translator->query(
                    'Hello %fname% %mname% %lname%!',
                    array("fname" => "TestFname", "mname" => "TestMname", "lname" => "TestLname")
                ))->equals('Привет, TestFname TestMname TestLname!');
            }
        );
    }

}


text:
package com.amazonaws.service.codecommit.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * No encryption key was found.
 * </p>
 */
public class EncryptionKeyNotFoundException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new EncryptionKeyNotFoundException with the specified error
     * message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public EncryptionKeyNotFoundException(String message) {
        super(message);
    }

}


text:
<?php namespace Buonzz\Frontier\Fetching;

use GuzzleHttp\Client;

class GuzzleFetchingStrategy implements FetchingStrategyInterface{
	public function fetch($site){
		$client = new Client();
		$response = $client->get($site['url']);
		$body = $response->getBody();
		return $body;

	}
}


text:
module.exports = function RandomService(dependencies) {
    var dependencies = dependencies;

    // Returns a random number between min (inclusive) and max (exclusive)
    var randomInt = function (min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
    };

    return {
        randomInt: randomInt
    }

};


text:
@interface UrlFormatter : XCTestCase

@end

@implementation UrlFormatter

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

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

- (void)testFormatter {
    XCTAssertThrows([[DNLLUrlFormatter alloc] initWithUrl:[NSURL URLWithString:@""]]);
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mortierella subtilissma Oudem.

### Remarks
null


text:
//********************************************************************
//
// File         : oc_scriptdatabase.cpp
//
// Classes      : OC_DataBase_c
//                OC_ScriptInfo_c
//                OC_Common_ScriptInfo_c
//                |-OC_DataAcquisition_ScriptInfo_c
//                |-OC_Test_ScriptInfo_c
//                |-OC_FWUpdate_ScriptInfo_c
//                |-OC_Decode_ScriptInfo_c
//                |-OC_Parse_ScriptInfo_c
//                |-OC_STicket_ScriptInfo_c
//
//

#ifndef OC_ONCE_SCRIPTDATABASE
#define OC_ONCE_SCRIPTDATABASE

#include <oc_include.h>

const OC_ULong_t  g_MaxBufferLength         = 1024;

typedef enum
{
  OC_Scripts_Common_e                       = 0,
  OC_Scripts_DataAcq_e                      = 1,
  OC_Scripts_Decode_e                       = 2,
  OC_Scripts_Parse_e                        = 3,
  OC_Scripts_STicket_e                      = 4,
  OC_Scripts_FWUpdate_e                     = 5,
  OC_Scripts_Test_e                         = 6
} OC_Scripts_t;

typedef enum
{
    OC_External_e = 0,
    OC_Internal_e
}OC_Option_type_t;

/*
Order of MetaData Attributes in a Script
1	TYPE:
2	VERSION:
3	RTEVERSION:
 	  [
4	    DEPENDENTSCRIPTS:
5	    DEVICEASSOC:
	    [
6	      TESTOPTION:
7	      TESTDESCRIPTION:
8	      TESTNAME:
      ]
	  ]
9	[BKVERSION:]
*/

typedef enum
{
  OC_ScriptAttribute_Type_e                 = 0,  //Should Be 0' as used in the ReadMetaData()
  OC_ScriptAttribute_Version_e              = 1,  //m_Attributes vector needs to be initialized in the same order!
  OC_ScriptAttribute_RTEVersion_e           = 2,
  OC_ScriptAttribute_BRKVersion_e           = 3,
  OC_ScriptAttribute_DependentScripts_e     = 4,
  OC_ScriptAttribute_SubScripts_e           = 5,
  OC_ScriptAttribute_DeviceAssoc_e          = 6,
  OC_ScriptAttribute_TestName_e             = 7,
  OC_ScriptAttribute_TestDescription_e      = 8,
  OC_ScriptAttribute_TestIntOption_e        = 9,
  OC_ScriptAttribute_TestExtOption_e        = 10
}OC_ScriptAttributes_t;

//********************************************************************
//
// Class:       OC_Common_ScriptInfo_c
// Method:
// Description:
// Parameters:  <none>
// Returns:     <none>
// Comments:

class OC_Common_ScriptInfo_c
{
private:
  OC_String_t               m_ScriptName;
  OC_String_t               m_ScriptType;
	OC_String_t               m_ScriptVersion;
  OC_String_t               m_RteVersion;
  OC_String_t               m_BreakVersion;
protected:
  //Shared by all the Childs
  OC_StringList_t           m_Attributes;
  OC_StringList_t           m_DependentScripts;     //Immediate Dependency Information
  OC_StringList_t           m_SubScriptsList;       //List for Sub Scripts
  OC_ULong_t                m_CommonAttributeCount; //Holds the Count of the CommonAttributes;
  OC_String_t               m_ScriptsRootDirectory;

  void                      PopulateCommonMetaData    ( OC_Compression_c  a_Comp,
                                                        OC_String_t       a_FileName  );
  void                      PopulateCommonMetaData    ( OC_String_t       a_FileName );

  OC_String_t               GetAttributeValue         ( OC_String_t       a_Line,
                                                        OC_String_t       a_AttrName );     //This is just a helper Function to read the Value from Parameter One.
  void                      GetAttributeValueList     ( OC_String_t       a_ValueString,
                                                        OC_StringList_t&  a_ReturnList,
                                                        OC_Char_t         a_Delimetere  = ',',
                                                        bool              a_FlagDepList = false); //To fill the DepedencyList
//Ctor & Dtor
public:
                            OC_Common_ScriptInfo_c    ();
                            ~OC_Common_ScriptInfo_c   ();
  //Returns the Reference here;
  OC_StringList_t&          DependencyScriptsReference()  { return m_DependentScripts;  }
  OC_StringList_t&          SubScriptsReference       ()  { return m_SubScriptsList;    }
  // The following API is to get the Immediate Dependents, Called from Recursive Function
  OC_StringList_t           GetDependencyList         ()  { return m_DependentScripts;  }
  OC_StringList_t           GetSubScriptsList         ()  { return m_SubScriptsList;    }
  virtual OC_StringList_t   GetDeviceAssociationList  ()  { OC_StringList_t a_TempDevAssc;
							    OC_ASSERT_INVALIDPATH;
							    return(a_TempDevAssc);  } //Common Scripts are for all Devices;
  //Set Methods
  void                      SetScriptName             ( OC_String_t  a_ScriptName        )  { m_ScriptName    = a_ScriptName;    }
  void                      SetScriptType             ( OC_String_t  a_ScriptType        )  { m_ScriptType    = a_ScriptType;    }
  void                      SetScriptVersion          ( OC_String_t  a_ScriptVersion     )  { m_ScriptVersion = a_ScriptVersion; }
  void                      SetRTEVersion             ( OC_String_t  a_RteVersion        )  { m_RteVersion    = a_RteVersion;    }
  void                      SetBrokenVersion          ( OC_String_t  a_BrokenVersion     )  { m_BreakVersion   = a_BrokenVersion;}
  //Get Methods
  OC_String_t               GetScriptName             (void)  {return m_ScriptName;}
  OC_String_t               GetScriptType             (void)  {return m_ScriptType;}
  OC_String_t               GetScriptVersion          (void)  {return m_ScriptVersion;}
  OC_String_t               GetRTEVersion             (void)  {return m_RteVersion;}
  OC_String_t               GetBrokenVersion          (void)  {return m_BreakVersion;}

  // Reads MetaData Attributes from the fptr
  virtual void ReadMetaData         ( OC_String_t a_FileName, OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_DataAcquisition_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:
class OC_DataAcquisition_ScriptInfo_c: public OC_Common_ScriptInfo_c
{
private:
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_DataAcquisition_ScriptInfo_c   (void); //Calls super to set the attributes.
                            ~OC_DataAcquisition_ScriptInfo_c  (void);
  void                      SetDeviceAssociation              (OC_StringList_t  a_DeviceAssociation)
                                                              {m_DeviceAssocList = a_DeviceAssociation;}
  OC_StringList_t           GetDeviceAssociationList          (void)
                                                              {return m_DeviceAssocList;}
  // Reads metaData in the fileHandle and fills the attributes
  void                      ReadMetaData                      ( OC_String_t a_FileName,
                                                                OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_Test_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:

class OC_Test_ScriptInfo_c: public OC_Common_ScriptInfo_c
{

private:
  OC_String_t               m_TestName;
  OC_String_t               m_TestDescr;
  OC_String_t               m_GrpTestName;
  OC_String_t               m_GrpTestScrName;
  //OC_String_t             m_TestOption;
  OC_StringList_t           m_TestIntOption;
  OC_StringList_t           m_TestExtOption;
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_Test_ScriptInfo_c      (void); //Calls parentCtor and populates
                            ~OC_Test_ScriptInfo_c     (void);
  //Set Methods
  void                      SetTestName               (OC_String_t  a_TestName)   {m_TestName = a_TestName;}
  void                      SetTestDescription        (OC_String_t  a_TestDescr)  {m_TestDescr = a_TestDescr;}
  //void                      SetTestOption             (OC_String_t  a_TestOption) {m_TestOption = a_TestOption;}
  void                      SetTestOption             (OC_Option_type_t  Optiontype,
                                                       OC_String_t       Option);
  //Get Methods
  OC_String_t               GetTestName               (void){return m_TestName;}
  OC_String_t               GetTestDescription        (void){return m_TestDescr;}
  //OC_String_t               GetTestOption             (void){return m_TestOption;}
  OC_StringList_t           GetTestOption             (OC_Option_type_t  Optiontype);
  OC_StringList_t           GetDeviceAssociationList  (  void   )  {      return m_DeviceAssocList;   }

  void                      ReadMetaData              (OC_String_t a_FileName,
                                                       OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_FWUpdate_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:

class OC_FWUpdate_ScriptInfo_c: public OC_Common_ScriptInfo_c
{
private:
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_FWUpdate_ScriptInfo_c    (void); //Calls super to set the attributes.
                            ~OC_FWUpdate_ScriptInfo_c   (void);
  //GetMethods
  OC_StringList_t           GetDeviceAssociationList    (void){return m_DeviceAssocList;}
  void                      ReadMetaData                (OC_String_t a_FileName,
                                                         OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_Decode_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:

//Decode Scripts
class OC_Decode_ScriptInfo_c: public OC_Common_ScriptInfo_c
{
private:
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_Decode_ScriptInfo_c      (void); //Calls super to set the attributes.
                            ~OC_Decode_ScriptInfo_c     (void);
  //GetMethods
  OC_StringList_t           GetDeviceAssociationList    (void){return m_DeviceAssocList;}
  void                      ReadMetaData                ( OC_String_t a_FileName,
                                                          OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_Parse_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:

class OC_Parse_ScriptInfo_c: public OC_Common_ScriptInfo_c
{
private:
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_Parse_ScriptInfo_c         (void); //Calls super to set the attributes.
                            ~OC_Parse_ScriptInfo_c        (void);
  OC_StringList_t           GetDeviceAssociationList      (void){return m_DeviceAssocList;}
  void                      ReadMetaData                  ( OC_String_t a_FileName,
                                                            OC_Char_t a_Delimetere = ',');
};

//********************************************************************
//
// Class	:      OC_STicket_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:

class OC_STicket_ScriptInfo_c: public OC_Common_ScriptInfo_c
{
private:
  OC_StringList_t           m_DeviceAssocList;
//Ctor & Dtor
public:
                            OC_STicket_ScriptInfo_c   (void); //Calls super to set the attributes.
                            ~OC_STicket_ScriptInfo_c  (void);
  //GetMethods
  OC_StringList_t           GetDeviceAssociationList  (void){return m_DeviceAssocList;}
  void                      ReadMetaData              ( OC_String_t a_FileName,
                                                        OC_Char_t a_Delimetere = ',');
};

typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_CommonScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_SubScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_STicketScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_FWUpdateScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_TestScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_DataAcqScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_DecodeScriptsMap_t;
typedef map< OC_String_t, OC_Common_ScriptInfo_c* >    OC_ParseScriptsMap_t;
typedef map< OC_String_t, OC_String_t>  OC_ScriptMap_t;

//********************************************************************
//
// Class	:      OC_ScriptInfo_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:  Main ScriptInfo Class Declaration
class OC_ScriptInfo_c
{
private:
  static  OC_CommonScriptsMap_t             m_CommonScriptsMap; //Common Meta-Data For All the Scripts
  static  OC_SubScriptsMap_t                m_SubScriptsMap;    //SubScript Meta-Data For All the Scripts
          OC_STicketScriptsMap_t            m_STicketScriptsMap;
          OC_FWUpdateScriptsMap_t           m_FWUpdateScriptsMap;
          OC_TestScriptsMap_t               m_TestScriptsMap;
          OC_DataAcqScriptsMap_t            m_DataAcquisitionScriptsMap;
          OC_DecodeScriptsMap_t             m_DecodeScriptsMap;
          OC_ParseScriptsMap_t              m_ParseScriptsMap;
//Ctors and Dtors
public:
                                            OC_ScriptInfo_c               (void);   //By default all the maps are of size 0
                                            ~OC_ScriptInfo_c              (void);
  //Methods for Member References
          OC_CommonScriptsMap_t&            CommonScriptsMapReference     (void){return m_CommonScriptsMap;}
          OC_SubScriptsMap_t&               SubScriptsMapReference        (void){return m_SubScriptsMap;}
          OC_STicketScriptsMap_t&           STicketScriptsMapReference    (void){return m_STicketScriptsMap;}
          OC_FWUpdateScriptsMap_t&          FWUpdateScriptsMapReference   (void){return m_FWUpdateScriptsMap;}
          OC_TestScriptsMap_t&              TestScriptsMapReference       (void){return m_TestScriptsMap;}
          OC_DataAcqScriptsMap_t&           DataAcqScriptsMapReference    (void){return m_DataAcquisitionScriptsMap;}
          OC_DecodeScriptsMap_t&            DecodeScriptsMapReference     (void){return m_DecodeScriptsMap;}
          OC_ParseScriptsMap_t&             ParseScriptsMapReference      (void){return m_ParseScriptsMap;}
          bool                              IsScriptExist                 (OC_String_t a_ScriptName);
          OC_ULong_t                        GetVersionAsNumber            ( OC_String_t a_VersionString);
          bool                              CheckDependency               ( OC_String_t a_ScriptName,
                                                                            OC_StringList_t& a_DependencyList);
  //Getters Return the MetaData Object for the a_ScriptName
          OC_Common_ScriptInfo_c*           GetCommonObject               (OC_String_t a_ScriptName);
          OC_Common_ScriptInfo_c*           GetSubScriptObject            (OC_String_t a_ScriptName);
          OC_STicket_ScriptInfo_c*          GetSTicketObject              (OC_String_t a_ScriptName);
          OC_FWUpdate_ScriptInfo_c*         GetFWUpdateObject             (OC_String_t a_ScriptName);
          OC_Test_ScriptInfo_c*             GetTestObject                 (OC_String_t a_ScriptName);
          OC_DataAcquisition_ScriptInfo_c*  GetDataAcqObject              (OC_String_t a_ScriptName);
          OC_Decode_ScriptInfo_c*           GetDecodeObject               (OC_String_t a_ScriptName);
          OC_Parse_ScriptInfo_c*            GetParseObject                (OC_String_t a_ScriptName);
          OC_Common_ScriptInfo_c*           GetObject                     (OC_String_t a_ScriptName);
          OC_StringList_t                   GetScrList                    (OC_Scripts_t   a_ScrType);
};

typedef map< OC_String_t, OC_ScriptInfo_c* > OC_ScriptInfoMap_t;

//********************************************************************
//
// Class	:      OC_DataBase_c
// Method	:
// Description	:
// Parameters	: <none>
// Returns	: <none>
// Comments	:
class OC_DataBase_c
{
private:
    OC_ScriptInfoMap_t      m_DataBase;
    OC_ScriptMap_t          m_ScriptsMap;
    void                    DeallocateMaps();
    void                    RemoveReferences      ( OC_String_t             a_DeviceID,
                                                    OC_String_t             a_Filename,
                                                    OC_ULong_t              a_ScriptType,
                                                    OC_CommonScriptsMap_t&  a_MapRef      );
public:
  const OC_String_t g_lszCommonScriptsKey;
//Ctor, Dtor
public:
                            OC_DataBase_c         (void);
                            ~OC_DataBase_c        (void);
  //Helper function
  OC_Long_t                 GetScriptType         ( OC_String_t a_Path);
  //Populates the entire DataBase
  bool                      Initialize            (void);
  void                      UpdateMap             (OC_Common_ScriptInfo_c* a_MetaDataObject) ;
  void                      TraverseDirectories   ( OC_String_t a_RootDirectory,
                                                    OC_Long_t a_ActualScriptType  = -1  ) ; //-1 for Scripts Root Directory
  // Returns the Container Object for the Given Key.
  // Returns a MainObject pointer if the Key is found in DataBase NULL OtherWise
  OC_ScriptInfo_c*          GetScriptInfo         ( OC_String_t a_Key );
  void                      Refresh();
  void                      InsertEntry(OC_String_t a_Filename, OC_Long_t a_ActualScriptType);
  bool                      IsScriptExist(OC_String_t a_ScrName, OC_String_t a_DeviceID, OC_Scripts_t a_ScrType);
  OC_StringList_t           Get_ScriptList(OC_String_t a_DeviceID, OC_Scripts_t a_ScrType);
  void                      RemoveEntry           ( OC_String_t             a_DeviceID,
                                                    OC_String_t             a_Filename,
                                                    OC_Long_t               a_ActualScriptType  );
};

#endif //#ifndef OC_ONCE_SCRIPTDATABASE


text:
/**
 *
 */
package com.qiyi.usercloud.carve.demoservice;

import com.qiyi.usercloud.carve.wrapper.ServiceContext;

/**
 * @author xinyun.du
 *
 */
public class DemoTest {
	public static void main(String[] args) {
//		ServiceContext.create(DemoService.class,null,null);
	}

}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Overview (JTransforms 3.1 API)</title>
<meta name="date" content="2015-09-08">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

JTransforms 3.1 API

Packages

Package
Description

org.jtransforms.dct

Discrete Cosine Transforms.

org.jtransforms.dht

Discrete Hartley Transforms.

org.jtransforms.dst

Discrete Sine Transforms.

org.jtransforms.fft

Discrete Fourier Transforms.

org.jtransforms.utils

Utility classes.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015. All rights reserved.


text:
using NUnit.Framework;

namespace WhenItsDone.Models.Tests.AddressTests
{
    [TestFixture]
    public class AddressConstructorTests
    {
        [Test]
        public void Address_ShouldHave_ParameterlessConstructor()
        {
            var obj = new Address();

            Assert.IsInstanceOf<Address>(obj);
        }

        [Test]
        public void Constructor_ShouldNotSet_IdProperty()
        {
            var obj = new Address();

            Assert.AreEqual(0, obj.Id);
        }

        [Test]
        public void Constructor_ShouldNotSet_CountryProperty()
        {
            var obj = new Address();

            Assert.AreEqual(null, obj.Country);
        }

        [Test]
        public void Constructor_ShouldNotSet_CityProperty()
        {
            var obj = new Address();

            Assert.AreEqual(null, obj.City);
        }

        [Test]
        public void Constructor_ShouldNotSet_StreetProperty()
        {
            var obj = new Address();

            Assert.AreEqual(null, obj.Street);
        }

        [Test]
        public void Constructor_ShouldNotSet_IsDeletedProperty()
        {
            var obj = new Address();

            Assert.IsFalse(obj.IsDeleted);
        }
    }
}


text:
      {{title}}

          Equipe

            Partidos

              {{party.label}}

          Código-Fonte

          Contato


text:
package org.apache.mahout.cf.taste.transforms;

import org.apache.mahout.cf.taste.common.Refreshable;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.model.Preference;

/**
 * <p>
 * Implementations encapsulate a transform on a {@link Preference}'s value. These transformations are
 * typically applied to values before they are used to compute a similarity value. They are typically not
 * applied elsewhere; in particular {@link org.apache.mahout.cf.taste.model.DataModel}s no longer use a
 * transform like this to transform all of their preference values at the source.
 * </p>
 */
public interface PreferenceTransform extends Refreshable {

  float getTransformedValue(Preference pref) throws TasteException;

}


text:
require File.dirname(__FILE__) + '/../spec_helper.rb'

describe BulkObservationFile, "import_file" do
  let(:user) { User.make! }
  before do
    @work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
    @headers = [:name, :date, :description, :place, :latitude, :longitude, :tags, :geoprivacy]
    load_test_taxa
    CSV.open(@work_path, 'w') do |csv|
      csv << @headers
      csv << [
        @Calypte_anna.name,
        "2007-08-20",
        "Beautiful little creature",
        "Leona Canyon Regional Park, Oakland, CA, USA",
        37.7454,
        -122.111,
        "cute, snakes",
        "open"
      ]
    end
  end
  elastic_models( Observation )

  it "should create an observation with the right species_guess" do
    bof = BulkObservationFile.new(@work_path, user.id)
    bof.perform
    expect(user.observations.last.species_guess).to eq @Calypte_anna.name
  end

  it "should create an observation with a geom" do
    bof = BulkObservationFile.new(@work_path, user.id)
    bof.perform
    expect(user.observations.last.geom).not_to be_blank
  end

  it "should still validate coordinates" do
    work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
    CSV.open(@work_path, 'w') do |csv|
      csv << @headers
      csv << [
        @Calypte_anna.name,
        "2007-08-20",
        "Beautiful little creature",
        "Leona Canyon Regional Park, Oakland, CA, USA",
        200.7454,
        -122.111,
        "cute, snakes",
        "open"
      ]
    end
    bof = BulkObservationFile.new(@work_path, user.id)
    user.observations.destroy_all
    bof.perform
    expect(user.observations).to be_blank
  end

  it "should allow blank rows" do
    work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
    CSV.open(@work_path, 'w') do |csv|
      csv << @headers
      csv << [
        @Calypte_anna.name,
        "2007-08-20",
        "Beautiful little creature",
        "Leona Canyon Regional Park, Oakland, CA, USA",
        1,
        2,
        "cute, snakes",
        "open"
      ]
      csv << ['','','','','','','']
      csv << ['','','','','','','']
      csv << ['','','','','','','']
    end
    bof = BulkObservationFile.new(@work_path, user.id)
    user.observations.destroy_all
    bof.perform
    user.reload
    expect( user.observations.count ).to eq 1
  end

  it "should skip rows with leading pound sign" do
    t = Taxon.make!
    File.open(@work_path, 'w') do |f|
      f << <<-CSV
species guess,Date,Description,Location,Latitude / y coord / northing,Longitude / x coord / easting,Tags,Geoprivacy
#{t.name},2013-01-01 09:10:11,,1,1,,"List,Of,Tags",Private
# Buteo jamaicensis,2013-01-01 09:10:11,,1,1,,"List,Of,Tags",Private
      CSV
    end
    bof = BulkObservationFile.new(@work_path, user.id)
    user.observations.destroy_all
    bof.perform
    user.reload
    expect( user.observations.count ).to eq 1
  end

  it "should validate quotes in coordinates" do
    File.open(@work_path, 'w') do |f|
      t = Taxon.make!
      f << <<-CSV
species guess,Date,Description,Location,Latitude / y coord / northing,Longitude / x coord / easting,Tags,Geoprivacy
#{t.name},2013-01-01 09:10:11,,1",1,,"List,Of,Tags",Private
      CSV
    end
    bof = BulkObservationFile.new(@work_path, user.id)
    user.observations.destroy_all
    bof.perform
    expect(user.observations).to be_blank
  end

  describe "with project" do
    before do
      @project_user = ProjectUser.make!
      @project = @project_user.project
    end
    it "should add to project" do
      bof = BulkObservationFile.new(@work_path, @project_user.user_id, project_id: @project.id)
      bof.perform
      expect(@project_user.user.observations.last.projects).to include(@project)
    end
    it "should not add an extra identification" do
      bof = BulkObservationFile.new(@work_path, @project_user.user_id, project_id: @project.id)
      bof.perform
      expect(@project_user.user.observations.last.identifications.count).to eq 1
    end
    it "should add project observation fields" do
      of1 = ObservationField.make!
      of2 = ObservationField.make!
      @project.project_observation_fields.create!( observation_field: of1 )
      @project.project_observation_fields.create!( observation_field: of2 )
      of1_value = "barf"
      of2_value = "12345"
      work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
      CSV.open(@work_path, 'w') do |csv|
        csv << @headers + [of1.name, of2.name]
        csv << [
          @Calypte_anna.name,
          "2007-08-20",
          "Beautiful little creature",
          "Leona Canyon Regional Park, Oakland, CA, USA",
          37.7454,
          -122.111,
          "cute, snakes",
          "open",
          of1_value,
          of2_value,
          ''
        ]
      end
      bof = BulkObservationFile.new(@work_path, user.id, project_id: @project.id)
      user.observations.destroy_all
      bof.perform
      user.reload
      expect( user.observations.count ).to eq 1
      expect( user.observations.last.observation_field_values ).not_to be_blank
      expect( user.observations.last.observation_field_values.first.value ).to eq of1_value
      expect( user.observations.last.observation_field_values.last.value ).to eq of2_value
    end
  end

  describe "with coordinate system" do
    let(:proj4_nzmg) {
      "+proj=nzmg +lat_0=-41 +lon_0=173 +x_0=2510000 +y_0=6023150 +ellps=intl +datum=nzgd49 +units=m +no_defs"
    }
    before do
      @work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
      @headers = [:name, :date, :description, :place, :latitude, :longitude, :tags, :geoprivacy]
      CSV.open(@work_path, 'w') do |csv|
        csv << @headers
        csv << [
          @Calypte_anna.name,
          "2000-12-23",
          "Pair seen in swamp off Kuripapango Rd.",
          "Hastings, Hawke's Bay, NZ",
          5635569, # these coordinates should be NZMG for Lat -39.380943828, Lon 176.3574072522
          1889191,
          "some,tags",
          "open"
        ]
      end
    end

    it "should create an observation with a geom" do
      bof = BulkObservationFile.new(@work_path, user.id, coord_system: proj4_nzmg)
      bof.perform
      expect(user.observations.last.geom).not_to be_blank
    end

    it "should validate coordinates" do
      work_path = File.join(Dir::tmpdir, "import_file_test-#{Time.now.to_i}.csv")
      CSV.open(work_path, 'w') do |csv|
        csv << @headers
        csv << [
          @Calypte_anna.name,
          "2000-12-23",
          "Pair seen in swamp off Kuripapango Rd.",
          "Hastings, Hawke's Bay, NZ",
          1889206,
          5599343, # these are reversed NZMG coordinates which should fail
          "some,tags",
          "open"
        ]
      end
      bof = BulkObservationFile.new(work_path, user.id, coord_system: proj4_nzmg)
      user.observations.destroy_all
      bof.perform
      expect(user.observations).to be_blank
    end
  end
end


text:
package org.openforis.collect.service;

import java.util.ArrayList;
import java.util.List;

import org.openforis.collect.manager.SpeciesManager;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.CollectTaxonomy;
import org.openforis.collect.model.TaxonTree;
import org.openforis.collect.model.TaxonTree.Node;
import org.openforis.idm.metamodel.Languages;
import org.openforis.idm.metamodel.Languages.Standard;
import org.openforis.idm.metamodel.ReferenceDataSchema.TaxonomyDefinition;
import org.openforis.idm.metamodel.SpeciesListService;
import org.openforis.idm.metamodel.Survey;
import org.openforis.idm.model.species.Taxon;
import org.openforis.idm.model.species.Taxon.TaxonRank;
import org.openforis.idm.model.species.TaxonVernacularName;
import org.openforis.idm.model.species.Taxonomy;
import org.springframework.beans.factory.annotation.Autowired;

public class CollectSpeciesListService implements SpeciesListService {

	public static final String CODE_ATTRIBUTE = "code";
	public static final String FAMILY_ATTRIBUTE = "family";
	public static final String FAMILY_SCIENTIFIC_NAME_ATTRIBUTE = "familyScientificName";
	public static final String FAMILY_NAME_ATTRIBUTE = "familyName";
	public static final String GENUS_ATTRIBUTE = "genus";
	public static final String SCIENTIFIC_NAME_ATTRIBUTE = "scientificName";

	public static final String[] GENERIC_ATTRIBUTES = new String[]{
		CODE_ATTRIBUTE, FAMILY_ATTRIBUTE, FAMILY_NAME_ATTRIBUTE, FAMILY_SCIENTIFIC_NAME_ATTRIBUTE, GENUS_ATTRIBUTE, SCIENTIFIC_NAME_ATTRIBUTE
	};

	@Autowired
	private SpeciesManager speciesManager;

	@Override
	public Taxonomy loadTaxonomyByName(Survey survey, String name) {
		return speciesManager.loadTaxonomyByName((CollectSurvey) survey, name);
	}

	@Override
	public List<String> loadSpeciesListNames(Survey survey) {
		List<CollectTaxonomy> taxonomies = speciesManager.loadTaxonomiesBySurvey((CollectSurvey) survey);
		List<String> result = new ArrayList<String>(taxonomies.size());
		for (CollectTaxonomy taxonomy : taxonomies) {
			result.add(taxonomy.getName());
		}
		return result;
	}

	@Override
	public Object loadSpeciesListData(Survey survey, String taxonomyName, String attribute, String speciesCode) {
		CollectTaxonomy taxonomy = speciesManager.loadTaxonomyByName((CollectSurvey) survey, taxonomyName);
		TaxonTree taxonTree = speciesManager.loadTaxonTree(taxonomy);
		Taxon taxon = taxonTree.findTaxonByCode(speciesCode);
		if (taxon == null) {
			return null;
		}
		Node taxonNode = taxonTree.getNodeBySystemId(taxon.getSystemId());
		if (FAMILY_ATTRIBUTE.equals(attribute) ||
				FAMILY_NAME_ATTRIBUTE.equals(attribute) ||
				FAMILY_SCIENTIFIC_NAME_ATTRIBUTE.equals(attribute)) {
			//family name
			Node familyNode = taxonNode.getAncestor(TaxonRank.FAMILY);
			return familyNode == null ? null : familyNode.getTaxon().getScientificName();
		} else if (GENUS_ATTRIBUTE.equals(attribute)) {
			Node genusNode = taxonNode.getAncestor(TaxonRank.GENUS);
			return genusNode == null ? null : genusNode.getTaxon().getScientificName();
		} else if (SCIENTIFIC_NAME_ATTRIBUTE.equals(attribute)) {
			return taxon.getScientificName();
		} else if (CODE_ATTRIBUTE.equals(attribute)) {
			return taxon.getCode();
		} else if (Languages.exists(Standard.ISO_639_3, attribute)) {
			TaxonVernacularName vernacularName = taxonNode.getVernacularName(attribute);
			return vernacularName == null ? null : vernacularName.getVernacularName();
		} else {
			//info (extra) attribute
			TaxonomyDefinition taxonDefinition = survey.getReferenceDataSchema().getTaxonomyDefinition(taxonomyName);
			if (taxonDefinition == null) {
				throw new IllegalArgumentException("No reference data schema found for taxonomy: " + taxonomyName);
			} else {
				int attributeIndex = taxonDefinition.getAttributeNames().indexOf(attribute);
				if (attributeIndex < 0) {
					throw new IllegalArgumentException("Unsupported attribute: " + attribute);
				} else {
					return taxon.getInfoAttribute(attributeIndex);
				}
			}
		}
	}

	@Override
	public Taxon loadTaxonByCode(Survey survey, String taxonomyName, String code) {
		CollectTaxonomy taxonomy = speciesManager.loadTaxonomyByName((CollectSurvey) survey, taxonomyName);
		return speciesManager.loadTaxonByCode(taxonomy, code);
	}

	public void setSpeciesManager(SpeciesManager speciesManager) {
		this.speciesManager = speciesManager;
	}

}