text:
package org.gradle.plugins.ide.internal.tooling;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.initialization.IncludedBuild;
import org.gradle.api.internal.project.ProjectStateRegistry;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.TaskDependency;
import org.gradle.internal.build.IncludedBuildState;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.xml.XmlTransformer;
import org.gradle.plugins.ide.api.XmlFileContentMerger;
import org.gradle.plugins.ide.eclipse.EclipsePlugin;
import org.gradle.plugins.ide.eclipse.model.AbstractClasspathEntry;
import org.gradle.plugins.ide.eclipse.model.AbstractLibrary;
import org.gradle.plugins.ide.eclipse.model.AccessRule;
import org.gradle.plugins.ide.eclipse.model.BuildCommand;
import org.gradle.plugins.ide.eclipse.model.Classpath;
import org.gradle.plugins.ide.eclipse.model.ClasspathEntry;
import org.gradle.plugins.ide.eclipse.model.Container;
import org.gradle.plugins.ide.eclipse.model.EclipseClasspath;
import org.gradle.plugins.ide.eclipse.model.EclipseJdt;
import org.gradle.plugins.ide.eclipse.model.EclipseModel;
import org.gradle.plugins.ide.eclipse.model.Library;
import org.gradle.plugins.ide.eclipse.model.Link;
import org.gradle.plugins.ide.eclipse.model.Output;
import org.gradle.plugins.ide.eclipse.model.ProjectDependency;
import org.gradle.plugins.ide.eclipse.model.SourceFolder;
import org.gradle.plugins.ide.internal.configurer.EclipseModelAwareUniqueProjectNameProvider;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultAccessRule;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultClasspathAttribute;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseBuildCommand;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseClasspathContainer;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseExternalDependency;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseJavaSourceSettings;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseLinkedResource;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseOutputLocation;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseProject;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseProjectDependency;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseProjectNature;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseSourceDirectory;
import org.gradle.plugins.ide.internal.tooling.eclipse.DefaultEclipseTask;
import org.gradle.plugins.ide.internal.tooling.java.DefaultInstalledJdk;
import org.gradle.plugins.ide.internal.tooling.model.DefaultGradleProject;
import org.gradle.tooling.model.UnsupportedMethodException;
import org.gradle.tooling.model.eclipse.EclipseRuntime;
import org.gradle.tooling.model.eclipse.EclipseWorkspace;
import org.gradle.tooling.model.eclipse.EclipseWorkspaceProject;
import org.gradle.tooling.provider.model.ParameterizedToolingModelBuilder;
import org.gradle.util.CollectionUtils;
import org.gradle.util.GUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class EclipseModelBuilder implements ParameterizedToolingModelBuilder<EclipseRuntime> {
    private final GradleProjectBuilder gradleProjectBuilder;
    private final EclipseModelAwareUniqueProjectNameProvider uniqueProjectNameProvider;

    private boolean projectDependenciesOnly;
    private DefaultEclipseProject result;
    private List<DefaultEclipseProject> eclipseProjects;
    private TasksFactory tasksFactory;
    private DefaultGradleProject rootGradleProject;
    private Project currentProject;
    private EclipseRuntime eclipseRuntime;
    private Map<String, Boolean> projectOpenStatus = new HashMap<>();

    @VisibleForTesting
    public EclipseModelBuilder(GradleProjectBuilder gradleProjectBuilder, ServiceRegistry services, EclipseModelAwareUniqueProjectNameProvider uniqueProjectNameProvider) {
        this.gradleProjectBuilder = gradleProjectBuilder;
        this.uniqueProjectNameProvider = uniqueProjectNameProvider;
    }

    public EclipseModelBuilder(GradleProjectBuilder gradleProjectBuilder, ServiceRegistry services) {
        this(gradleProjectBuilder, services, new EclipseModelAwareUniqueProjectNameProvider(services.get(ProjectStateRegistry.class)));
    }

    @Override
    public boolean canBuild(String modelName) {
        return modelName.equals("org.gradle.tooling.model.eclipse.EclipseProject")
            || modelName.equals("org.gradle.tooling.model.eclipse.HierarchicalEclipseProject");
    }

    @Override
    public Class<EclipseRuntime> getParameterType() {
        return EclipseRuntime.class;
    }

    @Override
    public Object buildAll(String modelName, EclipseRuntime eclipseRuntime, Project project) {
        this.eclipseRuntime = eclipseRuntime;
        List<EclipseWorkspaceProject> projects = eclipseRuntime.getWorkspace().getProjects();
        HashSet<EclipseWorkspaceProject> projectsInBuild = new HashSet<>(projects);
        projectsInBuild.removeAll(gatherExternalProjects(project.getRootProject(), projects));
        projectOpenStatus = projectsInBuild.stream().collect(Collectors.toMap(EclipseWorkspaceProject::getName, EclipseModelBuilder::isProjectOpen, (a, b) -> a | b));

        return buildAll(modelName, project);
    }

    public static boolean isProjectOpen(EclipseWorkspaceProject project) {
        // TODO we should refactor this to general, compatibility mapping solution, as we have it for model loading. See HasCompatibilityMapping class.
        try {
            return project.isOpen();
        } catch (UnsupportedMethodException e) {
            // isOpen was added in gradle 5.6. for 5.5 we default to true
            return true;
        }
    }

    @Override
    public DefaultEclipseProject buildAll(String modelName, Project project) {
        boolean includeTasks = modelName.equals("org.gradle.tooling.model.eclipse.EclipseProject");
        tasksFactory = new TasksFactory(includeTasks);
        projectDependenciesOnly = modelName.equals("org.gradle.tooling.model.eclipse.HierarchicalEclipseProject");
        currentProject = project;
        eclipseProjects = Lists.newArrayList();
        Project root = project.getRootProject();
        rootGradleProject = gradleProjectBuilder.buildAll(project);
        tasksFactory.collectTasks(root);
        applyEclipsePlugin(root);
        deduplicateProjectNames(root);
        buildHierarchy(root);
        populate(root);
        return result;
    }

    private void deduplicateProjectNames(Project root) {
        uniqueProjectNameProvider.setReservedProjectNames(calculateReservedProjectNames(root, eclipseRuntime));
        for (Project project : root.getAllprojects()) {
            EclipseModel eclipseModel = project.getExtensions().findByType(EclipseModel.class);
            if (eclipseModel != null) {
                eclipseModel.getProject().setName(uniqueProjectNameProvider.getUniqueName(project));
            }
        }
    }

    private void applyEclipsePlugin(Project root) {
        Set<Project> allProjects = root.getAllprojects();
        for (Project p : allProjects) {
            p.getPluginManager().apply(EclipsePlugin.class);
        }
        for (IncludedBuild includedBuild : root.getGradle().getIncludedBuilds()) {
            IncludedBuildState includedBuildInternal = (IncludedBuildState) includedBuild;
            applyEclipsePlugin(includedBuildInternal.getConfiguredBuild().getRootProject());
        }
    }

    private DefaultEclipseProject buildHierarchy(Project project) {
        List<DefaultEclipseProject> children = new ArrayList<DefaultEclipseProject>();
        for (Project child : project.getChildProjects().values()) {
            children.add(buildHierarchy(child));
        }

        EclipseModel eclipseModel = project.getExtensions().getByType(EclipseModel.class);
        org.gradle.plugins.ide.eclipse.model.EclipseProject internalProject = eclipseModel.getProject();
        String name = internalProject.getName();
        String description = GUtil.elvis(internalProject.getComment(), null);
        DefaultEclipseProject eclipseProject =
            new DefaultEclipseProject(name, project.getPath(), description, project.getProjectDir(), children)
                .setGradleProject(rootGradleProject.findByPath(project.getPath()));

        for (DefaultEclipseProject child : children) {
            child.setParent(eclipseProject);
        }
        addProject(project, eclipseProject);
        return eclipseProject;
    }

    private void addProject(Project project, DefaultEclipseProject eclipseProject) {
        if (project == currentProject) {
            result = eclipseProject;
        }
        eclipseProjects.add(eclipseProject);
    }

    private void populate(Project project) {
        EclipseModel eclipseModel = project.getExtensions().getByType(EclipseModel.class);

        boolean projectDependenciesOnly = this.projectDependenciesOnly;

        ClasspathElements classpathElements = gatherClasspathElements(projectOpenStatus, eclipseModel.getClasspath(), projectDependenciesOnly);

        DefaultEclipseProject eclipseProject = findEclipseProject(project);

        eclipseProject.setClasspath(classpathElements.getExternalDependencies());
        eclipseProject.setProjectDependencies(classpathElements.getProjectDependencies());
        eclipseProject.setSourceDirectories(classpathElements.getSourceDirectories());
        eclipseProject.setClasspathContainers(classpathElements.getClasspathContainers());
        eclipseProject.setOutputLocation(classpathElements.getEclipseOutputLocation() != null ? classpathElements.getEclipseOutputLocation() : new DefaultEclipseOutputLocation("bin"));
        eclipseProject.setAutoBuildTasks(!eclipseModel.getAutoBuildTasks().getDependencies(null).isEmpty());

        org.gradle.plugins.ide.eclipse.model.Project xmlProject = new org.gradle.plugins.ide.eclipse.model.Project(new XmlTransformer());

        XmlFileContentMerger projectFile = eclipseModel.getProject().getFile();
        if (projectFile == null) {
            xmlProject.configure(eclipseModel.getProject());
        } else {
            eclipseModel.getProject().mergeXmlProject(xmlProject);
        }

        populateEclipseProjectTasks(eclipseProject, tasksFactory.getTasks(project));
        populateEclipseProject(eclipseProject, xmlProject);
        populateEclipseProjectJdt(eclipseProject, eclipseModel.getJdt());

        for (Project childProject : project.getChildProjects().values()) {
            populate(childProject);
        }
    }

    public static ClasspathElements gatherClasspathElements(Map<String, Boolean> projectOpenStatus, EclipseClasspath eclipseClasspath, boolean projectDependenciesOnly) {
        ClasspathElements classpathElements = new ClasspathElements();
        eclipseClasspath.setProjectDependenciesOnly(projectDependenciesOnly);

        List<ClasspathEntry> classpathEntries;
        if (eclipseClasspath.getFile() == null) {
            classpathEntries = eclipseClasspath.resolveDependencies();
        } else {
            Classpath classpath = new Classpath(eclipseClasspath.getFileReferenceFactory());
            eclipseClasspath.mergeXmlClasspath(classpath);
            classpathEntries = classpath.getEntries();
        }

        final Map<String, DefaultEclipseProjectDependency> projectDependencyMap = new HashMap<>();

        for (ClasspathEntry entry : classpathEntries) {
            //we don't handle Variables at the moment because users didn't request it yet
            //and it would probably push us to add support in the tooling api to retrieve the variable mappings.
            if (entry instanceof Library) {
                AbstractLibrary library = (AbstractLibrary) entry;
                final File file = library.getLibrary().getFile();
                final File source = library.getSourcePath() == null ? null : library.getSourcePath().getFile();
                final File javadoc = library.getJavadocPath() == null ? null : library.getJavadocPath().getFile();
                DefaultEclipseExternalDependency dependency = new DefaultEclipseExternalDependency(file, javadoc, source, library.getModuleVersion(), library.isExported(), createAttributes(library), createAccessRules(library));
                classpathElements.getExternalDependencies().add(dependency);
            } else if (entry instanceof ProjectDependency) {
                final ProjectDependency projectDependency = (ProjectDependency) entry;
                // By removing the leading "/", this is no longer a "path" as defined by Eclipse
                final String path = StringUtils.removeStart(projectDependency.getPath(), "/");
                boolean isProjectOpen = projectOpenStatus.getOrDefault(path, true);
                if (!isProjectOpen) {
                    final File source = projectDependency.getPublicationSourcePath() == null ? null : projectDependency.getPublicationSourcePath().getFile();
                    final File javadoc = projectDependency.getPublicationJavadocPath() == null ? null : projectDependency.getPublicationJavadocPath().getFile();
                    classpathElements.getExternalDependencies().add(new DefaultEclipseExternalDependency(projectDependency.getPublication().getFile(), javadoc, source, null, projectDependency.isExported(), createAttributes(projectDependency), createAccessRules(projectDependency)));
                    classpathElements.getBuildDependencies().add(projectDependency.getBuildDependencies());
                } else {
                    projectDependencyMap.put(path, new DefaultEclipseProjectDependency(path, projectDependency.isExported(), createAttributes(projectDependency), createAccessRules(projectDependency)));
                }
            } else if (entry instanceof SourceFolder) {
                final SourceFolder sourceFolder = (SourceFolder) entry;
                String path = sourceFolder.getPath();
                List<String> excludes = sourceFolder.getExcludes();
                List<String> includes = sourceFolder.getIncludes();
                String output = sourceFolder.getOutput();
                classpathElements.getSourceDirectories().add(new DefaultEclipseSourceDirectory(path, sourceFolder.getDir(), excludes, includes, output, createAttributes(sourceFolder), createAccessRules(sourceFolder)));
            } else if (entry instanceof Container) {
                final Container container = (Container) entry;
                classpathElements.getClasspathContainers().add(new DefaultEclipseClasspathContainer(container.getPath(), container.isExported(), createAttributes(container), createAccessRules(container)));
            } else if (entry instanceof Output) {
                classpathElements.setEclipseOutputLocation(new DefaultEclipseOutputLocation(((Output) entry).getPath()));
            }
        }
        classpathElements.getProjectDependencies().addAll(projectDependencyMap.values());
        return classpathElements;
    }

    private static void populateEclipseProjectTasks(DefaultEclipseProject eclipseProject, Iterable<Task> projectTasks) {
        List<DefaultEclipseTask> tasks = new ArrayList<DefaultEclipseTask>();
        for (Task t : projectTasks) {
            tasks.add(new DefaultEclipseTask(eclipseProject, t.getPath(), t.getName(), t.getDescription()));
        }
        eclipseProject.setTasks(tasks);
    }

    private static void populateEclipseProject(DefaultEclipseProject eclipseProject, org.gradle.plugins.ide.eclipse.model.Project xmlProject) {
        List<DefaultEclipseLinkedResource> linkedResources = new LinkedList<DefaultEclipseLinkedResource>();
        for (Link r : xmlProject.getLinkedResources()) {
            linkedResources.add(new DefaultEclipseLinkedResource(r.getName(), r.getType(), r.getLocation(), r.getLocationUri()));
        }
        eclipseProject.setLinkedResources(linkedResources);

        List<DefaultEclipseProjectNature> natures = new ArrayList<DefaultEclipseProjectNature>();
        for (String n : xmlProject.getNatures()) {
            natures.add(new DefaultEclipseProjectNature(n));
        }
        eclipseProject.setProjectNatures(natures);

        List<DefaultEclipseBuildCommand> buildCommands = new ArrayList<DefaultEclipseBuildCommand>();
        for (BuildCommand b : xmlProject.getBuildCommands()) {
            Map<String, String> arguments = Maps.newLinkedHashMap();
            for (Map.Entry<String, String> entry : b.getArguments().entrySet()) {
                arguments.put(convertGString(entry.getKey()), convertGString(entry.getValue()));
            }
            buildCommands.add(new DefaultEclipseBuildCommand(b.getName(), arguments));
        }
        eclipseProject.setBuildCommands(buildCommands);
    }

    private static void populateEclipseProjectJdt(DefaultEclipseProject eclipseProject, EclipseJdt jdt) {
        if (jdt != null) {
            eclipseProject.setJavaSourceSettings(new DefaultEclipseJavaSourceSettings()
                .setSourceLanguageLevel(jdt.getSourceCompatibility())
                .setTargetBytecodeVersion(jdt.getTargetCompatibility())
                .setJdk(DefaultInstalledJdk.current())
            );
        }
    }

    private DefaultEclipseProject findEclipseProject(final Project project) {
        return CollectionUtils.findFirst(eclipseProjects, new Spec<DefaultEclipseProject>() {
            @Override
            public boolean isSatisfiedBy(DefaultEclipseProject element) {
                return element.getGradleProject().getPath().equals(project.getPath());
            }
        });
    }

    private static List<DefaultClasspathAttribute> createAttributes(AbstractClasspathEntry classpathEntry) {
        List<DefaultClasspathAttribute> result = Lists.newArrayList();
        Map<String, Object> attributes = classpathEntry.getEntryAttributes();
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            Object value = entry.getValue();
            result.add(new DefaultClasspathAttribute(convertGString(entry.getKey()), value == null ? "" : value.toString()));
        }
        return result;
    }

    private static List<DefaultAccessRule> createAccessRules(AbstractClasspathEntry classpathEntry) {
        List<DefaultAccessRule> result = Lists.newArrayList();
        for (AccessRule accessRule : classpathEntry.getAccessRules()) {
            result.add(createAccessRule(accessRule));
        }
        return result;
    }

    private static DefaultAccessRule createAccessRule(AccessRule accessRule) {
        int kindCode;
        String kind = accessRule.getKind();
        switch (kind) {
            case "accessible":
            case "0":
                kindCode = 0;
                break;
            case "nonaccessible":
            case "1":
                kindCode = 1;
                break;
            case "discouraged":
            case "2":
                kindCode = 2;
                break;
            default:
                kindCode = 0;
                break;
        }
        return new DefaultAccessRule(kindCode, accessRule.getPattern());
    }

    private List<Project> collectAllProjects(List<Project> all, Gradle gradle) {
        all.addAll(gradle.getRootProject().getAllprojects());
        for (IncludedBuild includedBuild : gradle.getIncludedBuilds()) {
            collectAllProjects(all, ((IncludedBuildState) includedBuild).getConfiguredBuild());
        }
        return all;
    }

    private Gradle getRootBuild(Gradle gradle) {
        if (gradle.getParent() == null) {
            return gradle;
        }
        return gradle.getParent();
    }

    private List<String> calculateReservedProjectNames(Project rootProject, EclipseRuntime parameter) {
        if (parameter == null) {
            return Collections.emptyList();
        }

        EclipseWorkspace workspace = parameter.getWorkspace();
        if (workspace == null) {
            return Collections.emptyList();
        }

        List<EclipseWorkspaceProject> projects = workspace.getProjects();
        if (projects == null) {
            return Collections.emptyList();
        }

        List<String> reservedProjectNames = new ArrayList<>();
        List<EclipseWorkspaceProject> externalProjects = gatherExternalProjects(rootProject, projects);
        for (EclipseWorkspaceProject externalProject : externalProjects) {
            reservedProjectNames.add(externalProject.getName());
        }

        return reservedProjectNames;
    }

    private List<EclipseWorkspaceProject> gatherExternalProjects(Project rootProject, List<EclipseWorkspaceProject> projects) {
        // The eclipse workspace contains projects from root and included builds. Check projects from all builds
        // so that models built for included builds do not consider projects from parent builds as external.
        Set<File> gradleProjectLocations = collectAllProjects(new ArrayList<>(), getRootBuild(rootProject.getGradle())).stream()
            .map(p -> p.getProjectDir().getAbsoluteFile()).collect(Collectors.toSet());
        List<EclipseWorkspaceProject> externalProjects = new ArrayList<>();
        for (EclipseWorkspaceProject project : projects) {
            if (project == null || project.getLocation() == null || project.getName() == null || project.getLocation() == null) {
                continue;
            }
            if (!gradleProjectLocations.contains(project.getLocation().getAbsoluteFile())) {
                externalProjects.add(project);
            }
        }
        return externalProjects;
    }

    /*
     * Groovy manipulates the JVM to let GString extend String.
     * Whenever we have a Set or Map containing Strings, it might also
     * contain GStrings. This breaks deserialization on the client.
     * This method forces GString to String conversion.
     */
    private static String convertGString(CharSequence original) {
        return original.toString();
    }

    public static class ClasspathElements {
        private final List<DefaultEclipseExternalDependency> externalDependencies = new ArrayList<>();
        private final List<DefaultEclipseProjectDependency> projectDependencies = new ArrayList<>();
        private final List<DefaultEclipseSourceDirectory> sourceDirectories = new ArrayList<>();
        private final List<DefaultEclipseClasspathContainer> classpathContainers = new ArrayList<>();
        private final List<TaskDependency> buildDependencies = new ArrayList<>();
        private DefaultEclipseOutputLocation eclipseOutputLocation;

        public List<DefaultEclipseExternalDependency> getExternalDependencies() {
            return externalDependencies;
        }

        public List<DefaultEclipseProjectDependency> getProjectDependencies() {
            return projectDependencies;
        }

        public List<DefaultEclipseSourceDirectory> getSourceDirectories() {
            return sourceDirectories;
        }

        public List<DefaultEclipseClasspathContainer> getClasspathContainers() {
            return classpathContainers;
        }

        public List<TaskDependency> getBuildDependencies() {
            return buildDependencies;
        }

        public DefaultEclipseOutputLocation getEclipseOutputLocation() {
            return eclipseOutputLocation;
        }

        public void setEclipseOutputLocation(DefaultEclipseOutputLocation eclipseOutputLocation) {
            this.eclipseOutputLocation = eclipseOutputLocation;
        }
    }
}


text:
<?php

namespace Symfony\Cmf\Bundle\RoutingAutoBundle\Tests\Resources\Fixtures;

class ChildClass extends ParentClass
{
}

redpajama_set_name: RedPajamaGithub


text:
<stix:STIX_Package
	xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
	xmlns:cybox="http://cybox.mitre.org/cybox-2"
	xmlns:cyboxVocabs="http://cybox.mitre.org/default_vocabularies-2"
	xmlns:example="http://example.com"
	xmlns:incident="http://stix.mitre.org/Incident-1"
	xmlns:ttp="http://stix.mitre.org/TTP-1"
	xmlns:ta="http://stix.mitre.org/ThreatActor-1"
	xmlns:stixCommon="http://stix.mitre.org/common-1"
	xmlns:stixVocabs="http://stix.mitre.org/default_vocabularies-1"
	xmlns:stix-ciqidentity="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1"
	xmlns:stix="http://stix.mitre.org/stix-1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:xal="urn:oasis:names:tc:ciq:xal:3"
	xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3"
	xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3"
	xsi:schemaLocation="
	http://cybox.mitre.org/common-2 http://cybox.mitre.org/XMLSchema/common/2.1/cybox_common.xsd
	http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.1/cybox_core.xsd
	http://cybox.mitre.org/default_vocabularies-2 http://cybox.mitre.org/XMLSchema/default_vocabularies/2.1/cybox_default_vocabularies.xsd
	http://stix.mitre.org/Incident-1 http://stix.mitre.org/XMLSchema/incident/1.1.1/incident.xsd
	http://stix.mitre.org/TTP-1 http://stix.mitre.org/XMLSchema/ttp/1.1.1/ttp.xsd
	http://stix.mitre.org/ThreatActor-1 http://stix.mitre.org/XMLSchema/threat_actor/1.1.1/threat_actor.xsd
	http://stix.mitre.org/common-1 http://stix.mitre.org/XMLSchema/common/1.1.1/stix_common.xsd
	http://stix.mitre.org/default_vocabularies-1 http://stix.mitre.org/XMLSchema/default_vocabularies/1.1.1/stix_default_vocabularies.xsd
	http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1 http://stix.mitre.org/XMLSchema/extensions/identity/ciq_3.0/1.1.1/ciq_3.0_identity.xsd
	http://stix.mitre.org/stix-1 http://stix.mitre.org/XMLSchema/core/1.1.1/stix_core.xsd
	urn:oasis:names:tc:ciq:xal:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xAL.xsd
	urn:oasis:names:tc:ciq:xnl:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xNL.xsd
	urn:oasis:names:tc:ciq:xpil:3 http://stix.mitre.org/XMLSchema/external/oasis_ciq_3.0/xPIL.xsd" id="example:Package-3ff3d6e1-9b90-41d0-ba7d-084846478d97" version="1.1.1" timestamp="2013-08-20T14:20:24+00:00">
    <stix:TTPs>
        <stix:TTP id="example:ttp-f764f1b7-3403-4334-ab03-2302eca5d950" timestamp="2014-12-22T16:30:13.593000+00:00" xsi:type='ttp:TTPType'>
            <ttp:Behavior>
                <ttp:Attack_Patterns>
                    <ttp:Attack_Pattern>
                        <ttp:Title>Unknown</ttp:Title>
                    </ttp:Attack_Pattern>
                </ttp:Attack_Patterns>
            </ttp:Behavior>
        </stix:TTP>
    </stix:TTPs>
    <stix:Incidents>
        <stix:Incident id="example:incident-999624c7-c7a0-493b-b51c-8d82694b63c1" timestamp="2014-05-10T19:23:22+00:00" xsi:type='incident:IncidentType'>
            <incident:Title>Hacker MrCreepy gains access to Mahanagar Telephone Nigam Limited (MTNL), an Indian state-owned telecommunications company and defaces it.</incident:Title>
            <incident:External_ID source="VERIS">7960115E-AA39-4E89-817F-AD749CAB0718</incident:External_ID>
            <incident:Time>
                <incident:Initial_Compromise precision="day">2013-08-15T00:00:00</incident:Initial_Compromise>
                <incident:Containment_Achieved precision="day">2013-08-15T12:00:00</incident:Containment_Achieved>
            </incident:Time>
            <incident:Reporter>
                <stixCommon:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                    <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">blackfist</xnl:NameLine>
  </xpil:PartyName>
</ExtSch:Specification>
                </stixCommon:Identity>
            </incident:Reporter>
            <incident:Victim xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:PartyName xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xnl:NameLine xmlns:xnl="urn:oasis:names:tc:ciq:xnl:3">Mahanagar Telephone Nigam Limited</xnl:NameLine>
  </xpil:PartyName>
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>IN</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </incident:Victim>
            <incident:Affected_Assets>
                <incident:Affected_Asset>
                    <incident:Type>Web application</incident:Type>
                    <incident:Nature_Of_Security_Effect>
                        <incident:Property_Affected>
                            <incident:Property xsi:type="stixVocabs:LossPropertyVocab-1.0">Integrity</incident:Property>
                            <incident:Description_Of_Effect>Log tampering,Modify configuration,Modify data</incident:Description_Of_Effect>
                        </incident:Property_Affected>
                    </incident:Nature_Of_Security_Effect>
                </incident:Affected_Asset>
            </incident:Affected_Assets>
            <incident:Impact_Assessment>
                <incident:Impact_Qualification xsi:type="stixVocabs:ImpactQualificationVocab-1.0">Unknown</incident:Impact_Qualification>
            </incident:Impact_Assessment>
            <incident:Leveraged_TTPs>
                <incident:Leveraged_TTP>
                    <stixCommon:TTP idref="example:ttp-f764f1b7-3403-4334-ab03-2302eca5d950" xsi:type='ttp:TTPType'/>
                </incident:Leveraged_TTP>
            </incident:Leveraged_TTPs>
            <incident:Attributed_Threat_Actors>
                <incident:Threat_Actor>
                    <stixCommon:Threat_Actor idref="example:threatactor-7c70ffae-4af8-4c7f-9fb2-f6c249624d6e" xsi:type='ta:ThreatActorType'/>
                </incident:Threat_Actor>
            </incident:Attributed_Threat_Actors>
            <incident:Security_Compromise xsi:type="stixVocabs:SecurityCompromiseVocab-1.0">Yes</incident:Security_Compromise>
            <incident:Discovery_Method xsi:type="stixVocabs:DiscoveryMethodVocab-1.0">Unknown</incident:Discovery_Method>
            <incident:Information_Source>
                <stixCommon:Identity>
                    <stixCommon:Name>vcdb</stixCommon:Name>
                </stixCommon:Identity>
                <stixCommon:Tools>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>veris2stix</cyboxCommon:Name>
                        <cyboxCommon:Vendor>MITRE</cyboxCommon:Vendor>
                        <cyboxCommon:Version>0.1</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                    <cyboxCommon:Tool>
                        <cyboxCommon:Name>VERIS schema</cyboxCommon:Name>
                        <cyboxCommon:Vendor>Verizon</cyboxCommon:Vendor>
                        <cyboxCommon:Version>1.3.0</cyboxCommon:Version>
                    </cyboxCommon:Tool>
                </stixCommon:Tools>
                <stixCommon:References>
                    <stixCommon:Reference>http://articles.timesofindia.indiatimes.com/2013-08-17/india/41420475_1_mtnl-mahanagar-telephone-nigam-ltd-hackers (20130820) http://news.softpedia.com/news/Website-of-Indian-Telecoms-Firm-MTNL-Defaced-by-Pakistani-Hacker-376251.shtml (20130820)</stixCommon:Reference>
                </stixCommon:References>
            </incident:Information_Source>
        </stix:Incident>
    </stix:Incidents>
    <stix:Threat_Actors>
        <stix:Threat_Actor id="example:threatactor-7c70ffae-4af8-4c7f-9fb2-f6c249624d6e" timestamp="2014-12-22T16:30:13.593000+00:00" xsi:type='ta:ThreatActorType'>
            <ta:Identity xsi:type='stix-ciqidentity:CIQIdentity3.0InstanceType'>
                <ExtSch:Specification xmlns:ExtSch="http://stix.mitre.org/extensions/Identity#CIQIdentity3.0-1">
  <xpil:Addresses xmlns:xpil="urn:oasis:names:tc:ciq:xpil:3">
    <xpil:Address>
      <xal:Country xmlns:xal="urn:oasis:names:tc:ciq:xal:3">
        <xal:NameElement>Unknown</xal:NameElement>
      </xal:Country>
    </xpil:Address>
  </xpil:Addresses>
</ExtSch:Specification>
            </ta:Identity>
            <ta:Type timestamp="2014-12-22T16:30:13.593000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:ThreatActorTypeVocab-1.0">Hacktivist</stixCommon:Value>
            </ta:Type>
            <ta:Motivation timestamp="2014-12-22T16:30:13.593000+00:00">
                <stixCommon:Value xsi:type="stixVocabs:MotivationVocab-1.1">Ideological</stixCommon:Value>
            </ta:Motivation>
            <ta:Observed_TTPs>
                <ta:Observed_TTP>
                    <stixCommon:TTP idref="example:ttp-f764f1b7-3403-4334-ab03-2302eca5d950" xsi:type='ttp:TTPType'/>
                </ta:Observed_TTP>
            </ta:Observed_TTPs>
        </stix:Threat_Actor>
    </stix:Threat_Actors>
</stix:STIX_Package>


text:
namespace ash {

const int kResizeAreaCornerSize = 16;
const int kResizeOutsideBoundsSize = 6;
const int kResizeOutsideBoundsScaleForTouch = 5;
const int kResizeInsideBoundsSize = 1;

#if defined(OS_CHROMEOS)
const SkColor kChromeOsBootColor = SkColorSetRGB(0xfe, 0xfe, 0xfe);
#endif

const SkColor kFocusBorderColor = SkColorSetRGB(64, 128, 250);

}  // namespace ash


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const util = require("util");
const SortableSet = require("./util/SortableSet");
const GraphHelpers = require("./GraphHelpers");
let debugId = 1000;
const ERR_CHUNK_ENTRY = "Chunk.entry was removed. Use hasRuntime()";
const ERR_CHUNK_INITIAL =
	"Chunk.initial was removed. Use canBeInitial/isOnlyInitial()";

const sortById = (a, b) => {
	if (a.id < b.id) return -1;
	if (b.id < a.id) return 1;
	return 0;
};

const sortByIdentifier = (a, b) => {
	if (a.identifier() > b.identifier()) return 1;
	if (a.identifier() < b.identifier()) return -1;
	return 0;
};

const getModulesIdent = set => {
	set.sort();
	let str = "";
	for (const m of set) {
		str += m.identifier() + "#";
	}
	return str;
};

const getArray = set => Array.from(set);

const getModulesSize = set => {
	let count = 0;
	for (const module of set) {
		count += module.size();
	}
	return count;
};

class Chunk {
	constructor(name) {
		this.id = null;
		this.ids = null;
		this.debugId = debugId++;
		this.name = name;
		this.entryModule = undefined;
		this._modules = new SortableSet(undefined, sortByIdentifier);
		this._groups = new SortableSet(undefined, sortById);
		this.files = [];
		this.rendered = false;
		this.hash = undefined;
		this.renderedHash = undefined;
		this.chunkReason = undefined;
		this.extraAsync = false;
	}

	get entry() {
		throw new Error(ERR_CHUNK_ENTRY);
	}

	set entry(data) {
		throw new Error(ERR_CHUNK_ENTRY);
	}

	get initial() {
		throw new Error(ERR_CHUNK_INITIAL);
	}

	set initial(data) {
		throw new Error(ERR_CHUNK_INITIAL);
	}

	hasRuntime() {
		for (const chunkGroup of this._groups) {
			// We only need to check the first one
			return chunkGroup.isInitial() && chunkGroup.getRuntimeChunk() === this;
		}
		return false;
	}

	canBeInitial() {
		for (const chunkGroup of this._groups) {
			if (chunkGroup.isInitial()) return true;
		}
		return false;
	}

	isOnlyInitial() {
		if (this._groups.size <= 0) return false;
		for (const chunkGroup of this._groups) {
			if (!chunkGroup.isInitial()) return false;
		}
		return true;
	}

	hasEntryModule() {
		return !!this.entryModule;
	}

	addModule(module) {
		if (!this._modules.has(module)) {
			this._modules.add(module);
			return true;
		}
		return false;
	}

	removeModule(module) {
		if (this._modules.delete(module)) {
			module.removeChunk(this);
			return true;
		}
		return false;
	}

	setModules(modules) {
		this._modules = new SortableSet(modules, sortByIdentifier);
	}

	getNumberOfModules() {
		return this._modules.size;
	}

	get modulesIterable() {
		return this._modules;
	}

	addGroup(chunkGroup) {
		if (this._groups.has(chunkGroup)) return false;
		this._groups.add(chunkGroup);
		return true;
	}

	removeGroup(chunkGroup) {
		if (!this._groups.has(chunkGroup)) return false;
		this._groups.delete(chunkGroup);
		return true;
	}

	isInGroup(chunkGroup) {
		return this._groups.has(chunkGroup);
	}

	getNumberOfGroups() {
		return this._groups.size;
	}

	get groupsIterable() {
		return this._groups;
	}

	compareTo(otherChunk) {
		this._modules.sort();
		otherChunk._modules.sort();
		if (this._modules.size > otherChunk._modules.size) return -1;
		if (this._modules.size < otherChunk._modules.size) return 1;
		const a = this._modules[Symbol.iterator]();
		const b = otherChunk._modules[Symbol.iterator]();
		// eslint-disable-next-line
		while (true) {
			const aItem = a.next();
			const bItem = b.next();
			if (aItem.done) return 0;
			const aModuleIdentifier = aItem.value.identifier();
			const bModuleIdentifier = bItem.value.identifier();
			if (aModuleIdentifier > bModuleIdentifier) return -1;
			if (aModuleIdentifier < bModuleIdentifier) return 1;
		}
	}

	containsModule(module) {
		return this._modules.has(module);
	}

	getModules() {
		return this._modules.getFromCache(getArray);
	}

	getModulesIdent() {
		return this._modules.getFromUnorderedCache(getModulesIdent);
	}

	remove(reason) {
		// cleanup modules
		// Array.from is used here to create a clone, because removeChunk modifies this._modules
		for (const module of Array.from(this._modules)) {
			module.removeChunk(this);
		}
		for (const chunkGroup of this._groups) {
			chunkGroup.removeChunk(this);
		}
	}

	moveModule(module, otherChunk) {
		GraphHelpers.disconnectChunkAndModule(this, module);
		GraphHelpers.connectChunkAndModule(otherChunk, module);
		module.rewriteChunkInReasons(this, [otherChunk]);
	}

	integrate(otherChunk, reason) {
		if (!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		// Array.from is used here to create a clone, because moveModule modifies otherChunk._modules
		for (const module of Array.from(otherChunk._modules)) {
			otherChunk.moveModule(module, this);
		}
		otherChunk._modules.clear();

		for (const chunkGroup of otherChunk._groups) {
			chunkGroup.replaceChunk(otherChunk, this);
			this.addGroup(chunkGroup);
		}
		otherChunk._groups.clear();

		if (this.name && otherChunk.name) {
			if (this.name.length !== otherChunk.name.length)
				this.name =
					this.name.length < otherChunk.name.length
						? this.name
						: otherChunk.name;
			else
				this.name = this.name < otherChunk.name ? this.name : otherChunk.name;
		}

		return true;
	}

	split(newChunk) {
		for (const chunkGroup of this._groups) {
			chunkGroup.insertChunk(newChunk, this);
			newChunk.addGroup(chunkGroup);
		}
	}

	isEmpty() {
		return this._modules.size === 0;
	}

	updateHash(hash) {
		hash.update(`${this.id} `);
		hash.update(this.ids ? this.ids.join(",") : "");
		hash.update(`${this.name || ""} `);
		for (const m of this._modules) {
			hash.update(m.hash);
		}
	}

	canBeIntegrated(otherChunk) {
		const isAvailable = (a, b) => {
			const queue = new Set(b.groupsIterable);
			for (const chunkGroup of queue) {
				if (a.isInGroup(chunkGroup)) continue;
				if (chunkGroup.isInitial()) return false;
				for (const parent of chunkGroup.parentsIterable) queue.add(parent);
			}
			return true;
		};
		if (this.hasRuntime() !== otherChunk.hasRuntime()) {
			if (this.hasRuntime()) {
				return isAvailable(this, otherChunk);
			} else if (otherChunk.hasRuntime()) {
				return isAvailable(otherChunk, this);
			} else {
				return false;
			}
		}
		if (this.hasEntryModule() || otherChunk.hasEntryModule()) return false;
		return true;
	}

	addMultiplierAndOverhead(size, options) {
		const overhead =
			typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
		const multiplicator = this.canBeInitial()
			? options.entryChunkMultiplicator || 10
			: 1;

		return size * multiplicator + overhead;
	}

	modulesSize() {
		return this._modules.getFromUnorderedCache(getModulesSize);
	}

	size(options) {
		return this.addMultiplierAndOverhead(this.modulesSize(), options);
	}

	integratedSize(otherChunk, options) {
		// Chunk if it's possible to integrate this chunk
		if (!this.canBeIntegrated(otherChunk)) {
			return false;
		}

		let integratedModulesSize = this.modulesSize();
		// only count modules that do not exist in this chunk!
		for (const otherModule of otherChunk._modules) {
			if (!this._modules.has(otherModule)) {
				integratedModulesSize += otherModule.size();
			}
		}

		return this.addMultiplierAndOverhead(integratedModulesSize, options);
	}

	sortModules(sortByFn) {
		this._modules.sortWith(sortByFn || sortById);
	}

	sortItems(sortChunks) {
		this.sortModules();
	}

	getAllAsyncChunks() {
		const initialChunks = new Set();
		const queue = new Set(this.groupsIterable);
		const chunks = new Set();

		for (const chunkGroup of queue) {
			for (const chunk of chunkGroup.chunks) initialChunks.add(chunk);
		}

		for (const chunkGroup of queue) {
			for (const chunk of chunkGroup.chunks) {
				if (!initialChunks.has(chunk)) chunks.add(chunk);
			}
			for (const child of chunkGroup.childrenIterable) queue.add(child);
		}

		return chunks;
	}

	getChunkMaps(realHash) {
		const chunkHashMap = Object.create(null);
		const chunkNameMap = Object.create(null);

		for (const chunk of this.getAllAsyncChunks()) {
			chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
			if (chunk.name) chunkNameMap[chunk.id] = chunk.name;
		}

		return {
			hash: chunkHashMap,
			name: chunkNameMap
		};
	}

	getChunkModuleMaps(filterFn) {
		const chunkModuleIdMap = Object.create(null);
		const chunkModuleHashMap = Object.create(null);

		for (const chunk of this.getAllAsyncChunks()) {
			let array;
			for (const module of chunk.modulesIterable) {
				if (filterFn(module)) {
					if (array === undefined) {
						array = [];
						chunkModuleIdMap[chunk.id] = array;
					}
					array.push(module.id);
					chunkModuleHashMap[module.id] = module.renderedHash;
				}
			}
			if (array !== undefined) {
				array.sort();
			}
		}

		return {
			id: chunkModuleIdMap,
			hash: chunkModuleHashMap
		};
	}

	hasModuleInGraph(filterFn, filterChunkFn) {
		const queue = new Set(this.groupsIterable);
		const chunksProcessed = new Set();

		for (const chunkGroup of queue) {
			for (const chunk of chunkGroup.chunks) {
				if (!chunksProcessed.has(chunk)) {
					chunksProcessed.add(chunk);
					if (!filterChunkFn || filterChunkFn(chunk)) {
						for (const module of chunk.modulesIterable)
							if (filterFn(module)) return true;
					}
				}
			}
			for (const child of chunkGroup.childrenIterable) queue.add(child);
		}
		return false;
	}

	toString() {
		return `Chunk[${Array.from(this._modules).join()}]`;
	}
}

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "forEachModule", {
	configurable: false,
	value: util.deprecate(function(fn) {
		this._modules.forEach(fn);
	}, "Chunk.forEachModule: Use for(const module of chunk.modulesIterable) instead")
});

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "mapModules", {
	configurable: false,
	value: util.deprecate(function(fn) {
		return Array.from(this._modules, fn);
	}, "Chunk.mapModules: Use Array.from(chunk.modulesIterable, fn) instead")
});

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "chunks", {
	configurable: false,
	get() {
		throw new Error("Chunk.chunks: Use ChunkGroup.getChildren() instead");
	},
	set() {
		throw new Error("Chunk.chunks: Use ChunkGroup.add/removeChild() instead");
	}
});

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "parents", {
	configurable: false,
	get() {
		throw new Error("Chunk.parents: Use ChunkGroup.getParents() instead");
	},
	set() {
		throw new Error("Chunk.parents: Use ChunkGroup.add/removeParent() instead");
	}
});

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "blocks", {
	configurable: false,
	get() {
		throw new Error("Chunk.blocks: Use ChunkGroup.getBlocks() instead");
	},
	set() {
		throw new Error("Chunk.blocks: Use ChunkGroup.add/removeBlock() instead");
	}
});

// TODO remove in webpack 5
Object.defineProperty(Chunk.prototype, "entrypoints", {
	configurable: false,
	get() {
		throw new Error(
			"Chunk.entrypoints: Use Chunks.groupsIterable and filter by instanceof Entrypoint instead"
		);
	},
	set() {
		throw new Error("Chunk.entrypoints: Use Chunks.addGroup instead");
	}
});

module.exports = Chunk;


text:
board_runner_args(pyocd "--target=stm32wb55rgvx")
board_runner_args(stm32cubeprogrammer "--port=swd" "--reset=hw")

include(${ZEPHYR_BASE}/boards/common/openocd.board.cmake)
include(${ZEPHYR_BASE}/boards/common/pyocd.board.cmake)
include(${ZEPHYR_BASE}/boards/common/stm32cubeprogrammer.board.cmake)


text:
var React = require('react');
var BugActions = require("../bugactions");

var BugItem = React.createClass({displayName: "BugItem",
	render: function() {
		var bug = this.props.bug;
		var checkboxId = bug.id+"-checkbox";
		var className = 'normal';
	    if(bug.fixed) {
	      className = 'strike';
	    }
		return (
			React.createElement("li", null,
			React.createElement("input", {
				id: checkboxId,
				type: "checkbox",
				onChange: this._onChange}),
			React.createElement("label", {className: className}, bug.text),
			React.createElement("br", null),
			React.createElement("a", {href: ""}, "Show Comments")
			)
		);
	},
	_onChange: function(event) {
		if(event.target.checked) {
			BugActions.markAsComplete(this.props.bug.id);
		} else {
			BugActions.unmarkAsComplete(this.props.bug.id);
		}
	}
});
module.exports = BugItem;


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Y!LDA: src/commons/TopicLearner/Synchronizer.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Namespaces

Classes

Files

File List

File Members

src/commons/TopicLearner/Synchronizer.h
Go to the documentation of this file.

00001
00037 /*
00038  * Synchronizer.h
00039  *
00040  *
00041  *  Created on: 07-Jan-2011
00042  *
00043  */
00044
00045 #ifndef SYNCHRONIZER_H_
00046 #define SYNCHRONIZER_H_
00047
00048 #include "Synchronizer_Helper.h"
00049
00050 //!The synchronization strategy that
00051 //!uses the Synchronizer_Helper to perform the
00052 //!concrete synchronization steps.
00053 /**
00054  * It provides slots, so to say, for synchronization
00055  * and calls the Synchronizer_Helper to perform its
00056  * duties for that slot.
00057  *
00058  * This greatly reduces the burden on the model writer
00059  *
00060  * So whenever a model needs to be scaled by providing
00061  * a distributed inferencing solution, all the model writer
00062  * has to do is write a Synchronizer_Helper.
00063  *
00064  * This is a default synchronization strategy provided and
00065  * users can implement their own strategy by extending this
00066  *
00067  * The main aim is to run the inferencing locally while
00068  * keeping the model in sync globally through the use of
00069  * this Synchronizer and a Distributed Map
00070  */
00071 class Synchronizer {
00072 public:
00073     Synchronizer(Synchronizer_Helper&);
00074     virtual ~Synchronizer();
00075
00076     //!The synchronization strategy
00077     void synchronize();
00078
00079     //!Set that all iterations of the Execution_Strategy
00080     //!have been done
00081     void set_all_iters_done();
00082
00083     //!Check if the Execution_Strategy has finished
00084     bool is_all_iters_done();
00085
00086 private:
00087     Synchronizer_Helper& _sync_helper;
00088     bool _all_iters_done;
00089
00090 };
00091
00092 #endif /* SYNCHRONIZER_H_ */

<address style="text-align: right;">Generated on Tue Jul 19 11:45:24 2011 for Y!LDA by

 1.6.3 </address>


text:
@implementation UIAlertView (LBXAlertAction)

static char key;

- (void)showWithBlock:(void(^)(NSInteger buttonIndex))block
{
    if (block) {
        objc_removeAssociatedObjects(self);
        objc_setAssociatedObject(self, &key, block, OBJC_ASSOCIATION_COPY);
        self.delegate = self;
    }

    [self show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    void(^block)(NSInteger buttonIndex);
    block = objc_getAssociatedObject(self, &key);

    if (block)
        block(buttonIndex);
}

@end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>FSF.FarKeyToName</title>
<meta http-equiv="Content-Type" Content="text/html; charset=Windows-1251">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

FarKeyToName

main |
FarStandardFunctions

The <dfn>FSF.FarKeyToName</dfn> is used to convert an internal
FAR key code to a string.

BOOL WINAPI FarKeyToName(
  int Key,
  char *KeyText,
  int Size
);

Parameters

Key

Internal FAR key code to convert to a string.

KeyText

String that will receive the result of conversion.

Size

The size of converted string, not including a null character,
  that will be copied to KeyText, or 0 to use the whole length of converted string.

Return value

If conversion succeeds TRUE is returned, otherwise if the passed Key is not known to FAR, FALSE is returned.

Remarks

If you use 0 in Size, then KeyText must be at least 32 bytes long.


text:
package client

import (
	"context"
	"fmt"
	"strings"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/log/level"
	"github.com/improbable-eng/thanos/pkg/objstore"
	"github.com/improbable-eng/thanos/pkg/objstore/azure"
	"github.com/improbable-eng/thanos/pkg/objstore/cos"
	"github.com/improbable-eng/thanos/pkg/objstore/gcs"
	"github.com/improbable-eng/thanos/pkg/objstore/s3"
	"github.com/improbable-eng/thanos/pkg/objstore/swift"
	"github.com/pkg/errors"
	"github.com/prometheus/client_golang/prometheus"
	"gopkg.in/yaml.v2"
)

type ObjProvider string

const (
	GCS   ObjProvider = "GCS"
	S3    ObjProvider = "S3"
	AZURE ObjProvider = "AZURE"
	SWIFT ObjProvider = "SWIFT"
	COS   ObjProvider = "COS"
)

type BucketConfig struct {
	Type   ObjProvider `yaml:"type"`
	Config interface{} `yaml:"config"`
}

// NewBucket initializes and returns new object storage clients.
// NOTE: confContentYaml can contain secrets.
func NewBucket(logger log.Logger, confContentYaml []byte, reg prometheus.Registerer, component string) (objstore.Bucket, error) {
	level.Info(logger).Log("msg", "loading bucket configuration")
	bucketConf := &BucketConfig{}
	if err := yaml.UnmarshalStrict(confContentYaml, bucketConf); err != nil {
		return nil, errors.Wrap(err, "parsing config YAML file")
	}

	config, err := yaml.Marshal(bucketConf.Config)
	if err != nil {
		return nil, errors.Wrap(err, "marshal content of bucket configuration")
	}

	var bucket objstore.Bucket
	switch strings.ToUpper(string(bucketConf.Type)) {
	case string(GCS):
		bucket, err = gcs.NewBucket(context.Background(), logger, config, component)
	case string(S3):
		bucket, err = s3.NewBucket(logger, config, component)
	case string(AZURE):
		bucket, err = azure.NewBucket(logger, config, component)
	case string(SWIFT):
		bucket, err = swift.NewContainer(logger, config)
	case string(COS):
		bucket, err = cos.NewBucket(logger, config, component)
	default:
		return nil, errors.Errorf("bucket with type %s is not supported", bucketConf.Type)
	}
	if err != nil {
		return nil, errors.Wrap(err, fmt.Sprintf("create %s client", bucketConf.Type))
	}
	return objstore.BucketWithMetrics(bucket.Name(), bucket, reg), nil
}


text:
/**
 * @fileOverview String builtin operations
 */
define(['exports',
        'atum/builtin/string',
        'atum/operations/construct'],
function(exports,
        builtin_string,
        construct){
"use strict";

/* Operations
 ******************************************************************************/
/**
 * Create a new builtin string object
 *
 * @param primitiveValue Value stored in string object.
 */
var create = function(primitiveValue) {
    return construct.construct(builtin_string.String, [primitiveValue]);
};

/* Export
 ******************************************************************************/
exports.create = create;

});


text:
package rollback

import (
	"github.com/tj/cobra"

	"github.com/apex/apex/cmd/apex/root"
)

// alias.
var alias string

// version target.
var version string

// example output.
const example = `
    Rollback all functions to the previous version
    $ apex rollback

    Rollback canary alias for a function
    $ apex rollback foo --alias canary

    Rollback all functions starting with "auth"
    $ apex rollback auth*

    Rollback a function to the specified version
    $ apex rollback bar -v 3`

// Command config.
var Command = &cobra.Command{
	Use:     "rollback [<name>...]",
	Short:   "Rollback functions",
	Example: example,
	RunE:    run,
}

// Initialize.
func init() {
	root.Register(Command)

	f := Command.Flags()
	f.StringVarP(&alias, "alias", "a", "current", "Function alias")
	f.StringVarP(&version, "version", "v", "", "version to which rollback is done")
}

// Run command.
func run(c *cobra.Command, args []string) error {
	root.Project.Alias = alias

	if err := root.Project.LoadFunctions(args...); err != nil {
		return err
	}

	if version == "" {
		return root.Project.Rollback()
	}

	return root.Project.RollbackVersion(version)
}


text:
package first

import (
	"go/ast"

	"github.com/bunniesandbeatings/baduk/architecture"
	"github.com/davecgh/go-spew/spew"
)

type TypeSpecVisitor struct {
	Context
	TypeSpec *ast.TypeSpec
}

func NewTypeSpecVisitor(context Context, typeSpec *ast.TypeSpec) *TypeSpecVisitor {
	return &TypeSpecVisitor{
		context,
		typeSpec,
	}
}

func parseMethods(funcType *ast.FuncType) []architecture.Type {
	params := fieldListTypes(funcType.Params)
	returns := fieldListTypes(funcType.Results)

	result := []architecture.Type{"bunnies", "beatings"}
	for _, p := range params {
		result = append(result, p)
	}
	for _, r := range returns {
		result = append(result, r)
	}
	return result
}

func (visitor TypeSpecVisitor) Visit(node ast.Node) ast.Visitor {
	// TODO: Can types be private?

	switch t := node.(type) {
	case *ast.InterfaceType:
		methods := []*architecture.Method{}

		for i, field := range t.Methods.List {
			if len(field.Names) != 1 {
				panic(spew.Sprintf("Method %d of interface %s does not have one name: %#v", i, visitor.TypeSpec.Name.Name, field.Names))
			}

			var parmTypes, returnTypes []architecture.Type
			if t, ok := field.Type.(*ast.FuncType); ok {
				parmTypes = fieldListTypes(t.Params)
				returnTypes = fieldListTypes(t.Results)
			} else {
				panic(spew.Sprintf("Cannot determine type of interface field %#v", field))
			}

			method := &architecture.Method{
				Func: architecture.Func{
					Name:        field.Names[0].Name,
					Package:     visitor.Package.Name,
					Filename:    visitor.Filename,
					ParmTypes:   parmTypes,
					ReturnTypes: returnTypes,
				},
				ReceiverType: "",
			}
			methods = append(methods, method)
		}

		visitor.Package.AddInterface(visitor.TypeSpec.Name.Name, visitor.Filename, methods)
	case *ast.StructType:
		visitor.Package.AddStruct(visitor.TypeSpec.Name.Name, visitor.Filename)
	}
	return nil
}


text:
package io.cattle.platform.iaas.api.auth.integration.ldap;

import io.cattle.platform.api.auth.Identity;
import io.cattle.platform.core.constants.IdentityConstants;
import io.cattle.platform.iaas.api.auth.AbstractTokenUtil;
import io.cattle.platform.iaas.api.auth.integration.interfaces.IdentityProvider;
import io.cattle.platform.iaas.api.auth.integration.ldap.ad.LdapServiceContextPoolFactory;
import io.cattle.platform.iaas.api.auth.integration.ldap.interfaces.LDAPConstants;
import io.cattle.platform.pool.PoolConfig;
import io.github.ibuildthecloud.gdapi.exception.ClientVisibleException;
import io.github.ibuildthecloud.gdapi.util.ResponseCodes;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.AbandonedConfig;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.LdapName;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import static javax.naming.directory.SearchControls.*;

public abstract class LDAPIdentityProvider implements IdentityProvider{

    private static final Logger log = LoggerFactory.getLogger(LDAPIdentityProvider.class);

    @Override
    public List<Identity> searchIdentities(String name, boolean exactMatch) {
        if (!isConfigured()){
            notConfigured();
        }
        List<Identity> identities = new ArrayList<>();
        for (String scope : scopes()) {
            identities.addAll(searchIdentities(name, scope, exactMatch));
        }
        return identities;
    }

    @Override
    public List<Identity> searchIdentities(String name, String scope, boolean exactMatch) {
        if (!isConfigured()){
            notConfigured();
        }
        name = escapeLDAPSearchFilter(name);
        if (getConstantsConfig().getUserScope().equalsIgnoreCase(scope)) {
            return searchUser(name, exactMatch);
        } else if(getConstantsConfig().getGroupScope().equalsIgnoreCase(scope)) {
            return searchGroup(name, exactMatch);
        } else{
            throw new ClientVisibleException(ResponseCodes.BAD_REQUEST, "invalidScope", "Identity type is not valid for Ldap", null);
        }
    }

    @Override
    public Identity getIdentity(String distinguishedName, String scope) {
        if (!isConfigured()){
            notConfigured();
        }
        if (!getConstantsConfig().scopes().contains(scope)) {
            throw new ClientVisibleException(ResponseCodes.BAD_REQUEST, "invalidScope", "Identity type is not valid for Ldap", null);
        }
        try {
            return getObject(distinguishedName, scope);
        }
        catch (ServiceContextCreationException e){
            throw new ClientVisibleException(ResponseCodes.SERVICE_UNAVAILABLE, "LdapDown", "Could not create service context: " + e.getMessage(), null);
        } catch (ServiceContextRetrievalException e) {
            throw new ClientVisibleException(ResponseCodes.SERVICE_UNAVAILABLE, "LdapDown", "Could not retrieve service context: " + e.getMessage(), null);
        }
    }

    @Override
    public Identity transform(Identity identity) {
        if (getConstantsConfig().scopes().contains(identity.getExternalIdType())) {
            return getIdentity(identity.getExternalId(), identity.getExternalIdType());
        } else {
            throw new ClientVisibleException(ResponseCodes.BAD_REQUEST,
                    IdentityConstants.INVALID_TYPE, "Ldap does not provide: " + identity.getExternalIdType(), null);
        }
    }

    @Override
    public Identity untransform(Identity identity) {
        if (!getConstantsConfig().scopes().contains(identity.getExternalIdType())){
            throw new ClientVisibleException(ResponseCodes.BAD_REQUEST,
                    IdentityConstants.INVALID_TYPE, "Ldap does not provide: " + identity.getExternalIdType(), null);
        }
        return identity;
    }

    protected List<Identity> searchGroup(String name, boolean exactMatch) {
        String query;
        if (exactMatch) {
            query = "(&(" + getConstantsConfig().getGroupSearchField() + '=' + name + ")(" + getConstantsConfig().objectClass() + '='
                    + getConstantsConfig().getGroupObjectClass() + "))";
        } else {
            query = "(&(" + getConstantsConfig().getGroupSearchField() + "=*" + name + "*)(" + getConstantsConfig().objectClass() + '='
                    + getConstantsConfig().getGroupObjectClass() + "))";
        }
        log.trace("LDAPIdentityProvider searchGroup query: " + query);
        return resultsToIdentities(searchLdap(query, getConstantsConfig().getGroupScope()));
    }

    protected List<Identity> searchUser(String name, boolean exactMatch) {
        String query;
        if (exactMatch)
        {
            query = "(&(" + getConstantsConfig().getUserSearchField() + '=' + name + ")(" + getConstantsConfig().objectClass() + '='
                    + getConstantsConfig().getUserObjectClass() + "))";
        } else {
            query = "(&(" + getConstantsConfig().getUserSearchField() + "=*" + name + "*)(" + getConstantsConfig().objectClass() + '='
                    + getConstantsConfig().getUserObjectClass() + "))";
        }
        log.trace("LDAPIdentityProvider searchUser query: " + query);
        return resultsToIdentities(searchLdap(query, getConstantsConfig().getUserScope()));
    }

    protected List<Identity> resultsToIdentities(NamingEnumeration<SearchResult> results) {
        List<Identity> identities = new ArrayList<>();
        try {
            if (!results.hasMore()) {
                return identities;
            }
        } catch (NamingException e) {
            return identities;
        }
        try {
            while (results.hasMore()){
                SearchResult result = results.next();
                log.trace("LDAPIdentityProvider SearchResult: " + result);
                LdapName dn = new LdapName(result.getNameInNamespace());
                Identity identityObj = attributesToIdentity(dn);
                if (identityObj != null) {
                    identities.add(identityObj);
                }
            }
        } catch (NamingException e) {
            //Ldap Referrals are causing this.
            getLogger().debug("While iterating results from an ldap search.", e);
            return identities;
        }
        return identities;
    }

    protected Identity getObject(String distinguishedName, String scope) {
        LdapContext context = null;
        try {
            LdapName object = new LdapName(distinguishedName);
            context = getServiceContext();
            Attributes search;
            search = context.getAttributes(object);
            if (!isType(search, scope) && !hasPermission(search)){
                return null;
            }
            return attributesToIdentity(object);
        }
        catch (NamingException e) {
            getLogger().error("Failed to get object: {} : {}", distinguishedName, e.getExplanation());
            if(!LDAPUtils.isRecoverable(e)) {
                invalidateServiceContext(context);
                context = null;
            }
            return null;
        }
        finally {
            if (context != null) {
                returnServiceContext(context);
            }
        }
    }

    protected Identity attributesToIdentity(LdapName dn){
        LdapContext context = getServiceContext();
        try {
            Attributes search = context.getAttributes(dn);
            log.trace("Attributes for dn: " + dn + " to translate: " + search);
            String externalIdType;
            String accountName;
            String externalId = dn.toString();
            String login;
            boolean user = false;
            if (isType(search, getConstantsConfig().getUserObjectClass())){
                externalIdType = getConstantsConfig().getUserScope();
                if (search.get(getConstantsConfig().getUserNameField()) != null) {
                    accountName = (String) search.get(getConstantsConfig().getUserNameField()).get();
                } else {
                    accountName = externalId;
                }
                login = (String) search.get(getConstantsConfig().getUserLoginField()).get();
                user = true;
            } else if (isType(search, getConstantsConfig().getGroupObjectClass())) {
                externalIdType = getConstantsConfig().getGroupScope();
                if (search.get(getConstantsConfig().getGroupNameField()) != null) {
                    accountName = (String) search.get(getConstantsConfig().getGroupNameField()).get();
                } else {
                    accountName = externalId;
                }
                if (search.get(getConstantsConfig().getUserLoginField()) != null) {
                    login = (String) search.get(getConstantsConfig().getUserLoginField()).get();
                } else {
                    login = accountName;
                }
            } else {
                return null;
            }
            return new Identity(externalIdType, externalId, accountName, null, null, login, user);
        } catch (NamingException e) {
            getLogger().error("Failed to get attributes: {} : {}", dn, e.getExplanation());
            if(!LDAPUtils.isRecoverable(e)) {
                invalidateServiceContext(context);
                context = null;
            }
            return null;
        } finally {
            if (context != null) {
                returnServiceContext(context);
            }
        }
    }

    protected boolean isType(Attributes search, String type) {
        NamingEnumeration<?> objectClass;
        try {
            objectClass = search.get(getConstantsConfig().objectClass()).getAll();
            while (objectClass.hasMoreElements()) {
                Object object = objectClass.next();
                if ((object.toString()).equalsIgnoreCase(type)){
                    return true;
                }
            }
            return false;
        } catch (NamingException e) {
            getLogger().info("Failed to determine if object is type:" + type, e);
            return false;
        }
    }

    protected NamingEnumeration<SearchResult> searchLdap(String query, String scope) {
        SearchControls controls = new SearchControls();
        LdapContext context = null;
        controls.setSearchScope(SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> results;
        try {
            context = getServiceContext();
            if (getConstantsConfig().getGroupScope().equalsIgnoreCase(scope) && StringUtils.isNotBlank(getConstantsConfig().getGroupSearchDomain())) {
                results = context.search(getConstantsConfig().getGroupSearchDomain(), query, controls);
            } else {
                results = context.search(getConstantsConfig().getDomain(), query, controls);
            }
        } catch (NamingException e) {
            getLogger().error("When searching ldap from /identity Failed to search: " + query + " scope:" + getConstantsConfig().getDomain(), e);
            if(!LDAPUtils.isRecoverable(e)) {
                invalidateServiceContext(context);
                context = null;
            }
            throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, getConstantsConfig().getConfig(),
                    "Could not lookup Organizational Unit", null);
        } finally {
            if (context != null){
                returnServiceContext(context);
            }
        }
        return results;
    }

    protected boolean hasPermission(Attributes attributes){
        int permission;
        try {
            if (!isType(attributes, getConstantsConfig().getUserObjectClass())){
                return true;
            }
            if (StringUtils.isNotBlank(getConstantsConfig().getUserEnabledAttribute())) {
                permission = Integer.parseInt(attributes.get(getConstantsConfig().getUserEnabledAttribute()).get()
                        .toString());
            } else {
                return true;
            }
        } catch (NamingException e) {
            getLogger().error("Failed to get USER_ENABLED_ATTRIBUTE.", e);
            return false;
        }
        permission = permission & getConstantsConfig().getUserDisabledBitMask();
        return permission != getConstantsConfig().getUserDisabledBitMask();
    }

    protected LdapContext login(String username, String password) {
        if (StringUtils.isEmpty(password)) {
            throw new UserLoginFailureException("Failed to login ldap User : Invalid Credentials");
        }
        Hashtable<String, String> props = new Hashtable<>();
        props.put(Context.SECURITY_AUTHENTICATION, "simple");
        props.put(Context.SECURITY_PRINCIPAL, username);
        props.put(Context.SECURITY_CREDENTIALS, password);
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        LdapContext userContext;

        try {
            String url = "ldap://" + getConstantsConfig().getServer() + ':' + getConstantsConfig().getPort() + '/';
            props.put(Context.PROVIDER_URL, url);
            if (getConstantsConfig().getTls()) {
                props.put(Context.SECURITY_PROTOCOL, "ssl");
            }
            userContext = new InitialLdapContext(props, null);
            return userContext;
        } catch (NamingException e) {
            throw new UserLoginFailureException("Failed to login ldap User: " +  LDAPUtils.errorCodeToDescription(e), e, username);
        }
    }

    protected String escapeLDAPSearchFilter(String filter) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < filter.length(); i++) {
            char curChar = filter.charAt(i);
            switch (curChar) {
                case '\\':
                    sb.append("\\5c");
                    break;
                case '*':
                    sb.append("\\2a");
                    break;
                case '(':
                    sb.append("\\28");
                    break;
                case ')':
                    sb.append("\\29");
                    break;
                case '\u0000':
                    sb.append("\\00");
                    break;
                default:
                    sb.append(curChar);
            }
        }
        return sb.toString();
    }

    protected LdapContext getServiceContext() {
        try {
            return getContextPool().borrowObject();
        } catch (ServiceContextCreationException e) {
            throw e;
        } catch (Exception e) {
            getLogger().error("Failed to get service context for ldap.", e);
            throw new ServiceContextRetrievalException("Unable to borrow a service context from context pool.", e);
        }
    }

    protected void returnServiceContext(LdapContext context) {
        try {
            getContextPool().returnObject(context);
        } catch (Exception e) {
            getLogger().info("Failed to return service context for ldap.", e);
        }
    }

    protected void invalidateServiceContext(LdapContext context) {
        try {
            getContextPool().invalidateObject(context);
        } catch (Exception e) {
            getLogger().info("Failed to invalidate service context for ldap.", e);
        }
    }

    public void init() {
        if (getContextPool() == null) {
            GenericObjectPoolConfig config = new GenericObjectPoolConfig();
            PoolConfig.setConfig(config, "ldap.context.pool", "ldap.context.pool.", "global.pool.");
            config.setTestOnBorrow(true);
            LdapServiceContextPoolFactory serviceContextPoolFactory = new LdapServiceContextPoolFactory(getConstantsConfig());
            setContextPool(new GenericObjectPool<>(serviceContextPoolFactory, config));
            AbandonedConfig abandonedConfig = new AbandonedConfig();
            abandonedConfig.setUseUsageTracking(true);
            abandonedConfig.setRemoveAbandonedOnMaintenance(true);
            abandonedConfig.setRemoveAbandonedOnBorrow(true);
            abandonedConfig.setRemoveAbandonedTimeout(60);
            getContextPool().setAbandonedConfig(abandonedConfig);
        }
    }

    public void reset() {
        if (getContextPool() != null) {
            getContextPool().close();
            setContextPool(null);
        }
        init();
    }
    protected abstract void setContextPool(GenericObjectPool<LdapContext> ldapContextGenericObjectPool);

    protected abstract AbstractTokenUtil getTokenUtils();

    protected abstract GenericObjectPool<LdapContext> getContextPool();

    protected abstract LDAPConstants getConstantsConfig();

    protected abstract Logger getLogger();

    protected void notConfigured() {
        throw new ClientVisibleException(ResponseCodes.SERVICE_UNAVAILABLE,
                "NotConfigured", "Ldap is not configured", null);
    }

    public List<Identity> getIdentities(List<Map<String, String>> identitiesGiven) {
        if (identitiesGiven == null || identitiesGiven.isEmpty()){
            return new ArrayList<>();
        }

        List<Identity> identities = new ArrayList<>();
        for (Map<String, String> identity: identitiesGiven){
            String externalId = identity.get(IdentityConstants.EXTERNAL_ID);
            String externalIdType = identity.get(IdentityConstants.EXTERNAL_ID_TYPE);
            Identity gotIdentity = getIdentity(externalId, externalIdType);
            if (gotIdentity == null) {
                throw new ClientVisibleException(ResponseCodes.BAD_REQUEST, "InvalidIdentity", "Invalid Identity", null);
            }
            identities.add(gotIdentity);
        }
        return identities;
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><entities>
	<entity>
		<entity-name>be.vdab.entities.Land</entity-name>
		<entity-width>120</entity-width>
		<entity-height>166</entity-height>
		<entity-X-Coordinate>70</entity-X-Coordinate>
		<entity-Y-Coordinate>55</entity-Y-Coordinate>
		<primary-collapsed>false</primary-collapsed>
		<relation-collapsed>false</relation-collapsed>
		<basic-collapsed>false</basic-collapsed>
	</entity>

	<entity>
		<entity-name>be.vdab.entities.Soort</entity-name>
		<entity-width>120</entity-width>
		<entity-height>186</entity-height>
		<entity-X-Coordinate>345</entity-X-Coordinate>
		<entity-Y-Coordinate>128</entity-Y-Coordinate>
		<primary-collapsed>false</primary-collapsed>
		<relation-collapsed>false</relation-collapsed>
		<basic-collapsed>false</basic-collapsed>
	</entity>

	<entity>
		<entity-name>be.vdab.entities.Wijn</entity-name>
		<entity-width>120</entity-width>
		<entity-height>226</entity-height>
		<entity-X-Coordinate>78</entity-X-Coordinate>
		<entity-Y-Coordinate>279</entity-Y-Coordinate>
		<primary-collapsed>false</primary-collapsed>
		<relation-collapsed>false</relation-collapsed>
		<basic-collapsed>false</basic-collapsed>
	</entity>
</entities>


text:
package me.suwash.swagger.spec.manager.ws.infra;

import static me.suwash.swagger.spec.manager.infra.error.SpecMgrException.MSGCD_ERRORHANDLE;
import static me.suwash.swagger.spec.manager.infra.error.SpecMgrException.array;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerMapping;
import me.suwash.swagger.spec.manager.infra.config.CommitInfo;
import me.suwash.swagger.spec.manager.infra.error.SpecMgrException;
import me.suwash.swagger.spec.manager.infra.i18n.SpecMgrMessageSource;

@lombok.extern.slf4j.Slf4j
public abstract class BaseApiController {

  /**
   * 例外に合わせたレスポンスを返します。
   *
   * @param e 例外
   * @return 例外に合わせたレスポンス
   */
  @ExceptionHandler
  public Object handleException(final Exception e) {
    if (e instanceof HttpMessageNotReadableException
        || e instanceof MissingServletRequestParameterException) {
      final String message = e.getMessage().substring(0, e.getMessage().indexOf(':'));
      return new ResponseEntity<Object>(message, HttpStatus.BAD_REQUEST);
    }

    log.error(SpecMgrMessageSource.getInstance().getMessage(MSGCD_ERRORHANDLE,
        array(e.getStackTrace()[0].toString(), e.getMessage())), e);

    return new ResponseEntity<Object>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
  }

  protected CommitInfo commitInfo(final String user) {
    return commitInfo(user, null, null);
  }

  protected CommitInfo commitInfo(final String user, final String email) {
    return commitInfo(user, email, null);
  }

  protected CommitInfo commitInfo(final String user, final String email, final String message) {
    return new CommitInfo(urlDecode(user), urlDecode(email), urlDecode(message));
  }

  private String urlDecode(final String value) {
    if (StringUtils.isEmpty(value))
      return value;

    try {
      return URLDecoder.decode(value, "utf8");
    } catch (UnsupportedEncodingException e) {
      throw new SpecMgrException(MSGCD_ERRORHANDLE, array("URL Decode", e.getMessage()));
    }
  }

  /**
   * リクエストURIから、今回マッチしたパターンを取り除いた文字列を返します。
   *
   * @param request リクエスト
   * @return マッチしなかった、URIの部分文字列
   */
  protected String extractPathFromPattern(final HttpServletRequest request) {
    if (request == null)
      return null;
    String path =
        (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern =
        (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
  }
}


text:
layout: center
permalink: /404.html
---

# 404

Sorry, the page you're looking for doesn't exist.

  Home
  Contact


text:
using System;
using System.Collections.Generic;
using NUnit.Framework;

namespace NMoneys.Exchange.Tests
{

	[TestFixture]
	public class TabulatedExchangeRateProviderTester
	{
		[Test]
		public void Ctor_DefaultRateFactory_AddInstancesOfExchangeRate()
		{
			var subject = new TabulatedExchangeRateProvider();
			ExchangeRate added = subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1);

			Assert.That(added.GetType(), Is.SameAs(typeof(ExchangeRate)));
		}

		[Test]
		public void Ctor_CustomRateFactory_AddInstancesOfCustomExchangeRate()
		{
			var subject = new TabulatedExchangeRateProvider((from, to, rate) => new CustomExchangeRate(from, to, rate));
			ExchangeRate added = subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1);

			Assert.That(added.GetType(), Is.SameAs(typeof(CustomExchangeRate)));
		}

		class CustomExchangeRate : ExchangeRate
		{
			public CustomExchangeRate(CurrencyIsoCode from, CurrencyIsoCode to, decimal rate) : base(from, to, rate) { }
		}

		[Test]
		public void Add_AddsTheRate_WithTheData()
		{
			var subject = new TabulatedExchangeRateProvider();
			ExchangeRate added = subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			Assert.That(added.From, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(added.To, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(added.Rate, Is.EqualTo(1.5m));
		}

		[Test]
		public void Get_ExistingRate_RateReturned()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			ExchangeRate existing = subject.Get(CurrencyIsoCode.AED, CurrencyIsoCode.AFN);
			Assert.That(existing.From, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(existing.To, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(existing.Rate, Is.EqualTo(1.5m));
		}

		[Test]
		public void Get_NonExistingRate_Exception()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			Assert.That(() => subject.Get(CurrencyIsoCode.USD, CurrencyIsoCode.AFN), Throws.InstanceOf<KeyNotFoundException>());
		}

		[Test]
		public void Add_ExistingRates_AreOverwritten()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 2m);

			ExchangeRate overwritten = subject.Get(CurrencyIsoCode.AED, CurrencyIsoCode.AFN);
			Assert.That(overwritten.Rate, Is.EqualTo(2m));
		}

		[Test]
		public void Add_InverseRate_NotAdded()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			Assert.That(() => subject.Get(CurrencyIsoCode.AFN, CurrencyIsoCode.AED), Throws.InstanceOf<KeyNotFoundException>());
		}

		[Test]
		public void Add_IdentityRatesForBaseCurrency_NotAdded()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			Assert.That(() => subject.Get(CurrencyIsoCode.AED, CurrencyIsoCode.AED), Throws.InstanceOf<KeyNotFoundException>());
		}

		[Test]
		public void Add_IdentityRatesForQuoteCurrency_NotAdded()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			Assert.That(() => subject.Get(CurrencyIsoCode.AFN, CurrencyIsoCode.AFN), Throws.InstanceOf<KeyNotFoundException>());
		}

		[Test]
		public void TryGet_ExistingRate_RateReturned()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			ExchangeRate existing;
			Assert.That(subject.TryGet(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, out existing), Is.True);
			Assert.That(existing.From, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(existing.To, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(existing.Rate, Is.EqualTo(1.5m));
		}

		[Test]
		public void TryGet_NonExistingRate_NoException()
		{
			var subject = new TabulatedExchangeRateProvider();

			ExchangeRate existing = new ExchangeRate(CurrencyIsoCode.AED, CurrencyIsoCode.AED, 1);

			Assert.That(subject.TryGet(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, out existing), Is.False);
			Assert.That(existing, Is.Null);
		}

		[Test]
		public void MultiAdd_ExistingRates_AreOverwritten()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);
			subject.MultiAdd(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 2m);

			ExchangeRate overwritten = subject.Get(CurrencyIsoCode.AED, CurrencyIsoCode.AFN);
			Assert.That(overwritten.Rate, Is.EqualTo(2m));
		}

		[Test]
		public void MultiAdd_ExistingInverseRates_AreOverwritten()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.Add(CurrencyIsoCode.AFN, CurrencyIsoCode.AED, 1.5m);
			subject.MultiAdd(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 2m);

			ExchangeRate overwritten = subject.Get(CurrencyIsoCode.AFN, CurrencyIsoCode.AED);
			Assert.That(overwritten.Rate, Is.EqualTo(.5m));
		}

		[Test]
		public void MultiAdd_InverseRate_Added()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.MultiAdd(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			var inverse = subject.Get(CurrencyIsoCode.AFN, CurrencyIsoCode.AED);
			Assert.That(inverse.From, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(inverse.To, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(inverse.Rate, Is.EqualTo(0.66m).Within(0.0067m));
		}

		[Test]
		public void MultiAdd_IdentityRatesForBaseCurrency_Added()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.MultiAdd(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			var identity = subject.Get(CurrencyIsoCode.AED, CurrencyIsoCode.AED);
			Assert.That(identity.From, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(identity.To, Is.EqualTo(CurrencyIsoCode.AED));
			Assert.That(identity.Rate, Is.EqualTo(1m));
		}

		[Test]
		public void MultiAdd_IdentityRatesForQuoteCurrency_Added()
		{
			var subject = new TabulatedExchangeRateProvider();
			subject.MultiAdd(CurrencyIsoCode.AED, CurrencyIsoCode.AFN, 1.5m);

			var identity = subject.Get(CurrencyIsoCode.AFN, CurrencyIsoCode.AFN);
			Assert.That(identity.From, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(identity.To, Is.EqualTo(CurrencyIsoCode.AFN));
			Assert.That(identity.Rate, Is.EqualTo(1m));
		}
	}

	[TestFixture]
	public class TabulatedExchangeProviderTester_DirectBuild_DefaultConversionArithmetic
	{
		private TabulatedExchangeRateProvider _as20110519;

		[OneTimeSetUp]
		public void InitSubject()
		{
			_as20110519 = new TabulatedExchangeRateProvider();
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.USD, 1m);
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.EUR, 0.70155m);
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.GBP, 0.61860m);

			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.EUR, 1m);
			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.USD, 1.42542m);
			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.GBP, 0.88176m);

			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.GBP, 1m);
			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.EUR, 1.13409m);
			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.USD, 1.61656m);
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEUR))]
		public void Get_FromEUR_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);

			Assert.That(fromEuro.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(fromEuro.To, Is.EqualTo(to));
			Assert.That(fromEuro.Rate, Is.EqualTo(rate), "no error margin is needed");
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEURInverse))]
		public void Get_FromEURInverse_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);
			ExchangeRate inversed = fromEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(to));
			Assert.That(inversed.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.Rate, Is.EqualTo(rate)
				.Within(0.00001m), "within 5 decimals error as Invert() uses decimal arithmetic");
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEUR))]
		public void Get_ToEUR_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);

			Assert.That(toEuro.From, Is.EqualTo(from));
			Assert.That(toEuro.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(toEuro.Rate, Is.EqualTo(rate));
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEURInverse))]
		public void Get_ToEURInverse_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);
			ExchangeRate inversed = toEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.To, Is.EqualTo(from));
			Assert.That(inversed.Rate, Is.EqualTo(rate)
				.Within(0.00001m), "within 5 decimals error as Invert() used decimal arithmetic");
		}
	}

	[TestFixture]
	public class TabulatedExchangeProviderTester_SimplerBuild_DefaultConversionArithmetic
	{
		private TabulatedExchangeRateProvider _as20110519;

		[OneTimeSetUp]
		public void InitSubject()
		{
			_as20110519 = new TabulatedExchangeRateProvider();
			_as20110519.MultiAdd(CurrencyIsoCode.USD, CurrencyIsoCode.EUR, 0.70155m);
			_as20110519.MultiAdd(CurrencyIsoCode.USD, CurrencyIsoCode.GBP, 0.61860m);
			_as20110519.MultiAdd(CurrencyIsoCode.GBP, CurrencyIsoCode.EUR, 1.13409m);
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEUR))]
		public void Get_FromEUR_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);

			Assert.That(fromEuro.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(fromEuro.To, Is.EqualTo(to));
			Assert.That(fromEuro.Rate, Is.EqualTo(rate)
				.Within(0.00001m), "as it was built from USD, EUR direct rates have more decimals");
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEURInverse))]
		public void Get_FromEURInverse_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);
			ExchangeRate inversed = fromEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(to));
			Assert.That(inversed.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.Rate, Is.EqualTo(rate)
				.Within(0.00001m), "within 5 decimals due to precision of Invert()");
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEUR))]
		public void Get_ToEUR_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);

			Assert.That(toEuro.From, Is.EqualTo(from));
			Assert.That(toEuro.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(toEuro.Rate, Is.EqualTo(rate));
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEURInverse))]
		public void Get_ToEURInverse_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);
			ExchangeRate inversed = toEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.To, Is.EqualTo(from));
			Assert.That(inversed.Rate, Is.EqualTo(rate)
				.Within(0.00001m), "within 5 decimals due to precision of Invert()");
		}
	}

	[TestFixture]
	public class TabulatedExchangeProviderTester_DirectBuild_CustomConversionArithmetic
	{
		public class FiveDecimalsArithmetic : ExchangeRate
		{
			public FiveDecimalsArithmetic(CurrencyIsoCode from, CurrencyIsoCode to, decimal rate)
				: base(from, to, rate) { }

			public override ExchangeRate Invert()
			{
				return new FiveDecimalsArithmetic(To, From, Math.Round(1m / Rate, 5));
			}

			public override Money Apply(Money from)
			{
				Money applied = base.Apply(from);
				return applied.Round(5);
			}
		}

		private TabulatedExchangeRateProvider _as20110519;

		[OneTimeSetUp]
		public void InitSubject()
		{
			_as20110519 = new TabulatedExchangeRateProvider((from, to, rate) => new FiveDecimalsArithmetic(from, to, rate));
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.USD, 1m);
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.EUR, 0.70155m);
			_as20110519.Add(CurrencyIsoCode.USD, CurrencyIsoCode.GBP, 0.61860m);

			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.EUR, 1m);
			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.USD, 1.42542m);
			_as20110519.Add(CurrencyIsoCode.EUR, CurrencyIsoCode.GBP, 0.88176m);

			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.GBP, 1m);
			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.EUR, 1.13409m);
			_as20110519.Add(CurrencyIsoCode.GBP, CurrencyIsoCode.USD, 1.61656m);
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEUR))]
		public void Get_FromEUR_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);

			Assert.That(fromEuro.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(fromEuro.To, Is.EqualTo(to));
			Assert.That(fromEuro.Rate, Is.EqualTo(rate));
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.fromEURInverse))]
		public void Get_FromEURInverse_CorrectRate(CurrencyIsoCode to, decimal rate)
		{
			ExchangeRate fromEuro = _as20110519.Get(CurrencyIsoCode.EUR, to);
			ExchangeRate inversed = fromEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(to));
			Assert.That(inversed.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.Rate, Is.EqualTo(rate)
				.Within(0.00001),
				"for some reason, despite using 5-digits arithmetic 1.13409m is represented as 1.1341m so a error marging is needed");
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEUR))]
		public void Get_ToEUR_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);

			Assert.That(toEuro.From, Is.EqualTo(from));
			Assert.That(toEuro.To, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(toEuro.Rate, Is.EqualTo(rate));
		}

		[TestCaseSource(typeof(ComplexProviderData), nameof(ComplexProviderData.toEURInverse))]
		public void Get_ToEURInverse_CorrectRate(CurrencyIsoCode from, decimal rate)
		{
			ExchangeRate toEuro = _as20110519.Get(from, CurrencyIsoCode.EUR);
			ExchangeRate inversed = toEuro.Invert();

			Assert.That(inversed.From, Is.EqualTo(CurrencyIsoCode.EUR));
			Assert.That(inversed.To, Is.EqualTo(from));
			Assert.That(inversed.Rate, Is.EqualTo(rate));
		}
	}
}