text:
package com.facebook.buck.apple;

import com.facebook.buck.apple.AppleBuildRules.RecursiveDependenciesMode;
import com.facebook.buck.apple.platform_type.ApplePlatformType;
import com.facebook.buck.apple.toolchain.AppleCxxPlatform;
import com.facebook.buck.apple.toolchain.AppleDeveloperDirectoryForTestsProvider;
import com.facebook.buck.apple.toolchain.ApplePlatform;
import com.facebook.buck.apple.toolchain.CodeSignIdentityStore;
import com.facebook.buck.apple.toolchain.ProvisioningProfileStore;
import com.facebook.buck.apple.toolchain.UnresolvedAppleCxxPlatform;
import com.facebook.buck.core.build.buildable.context.BuildableContext;
import com.facebook.buck.core.build.context.BuildContext;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.cell.nameresolver.CellNameResolver;
import com.facebook.buck.core.description.arg.HasTestTimeout;
import com.facebook.buck.core.description.attr.ImplicitDepsInferringDescription;
import com.facebook.buck.core.description.impl.DescriptionCache;
import com.facebook.buck.core.description.metadata.MetadataProvidingDescription;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.exceptions.UserVerify;
import com.facebook.buck.core.filesystems.RelPath;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.Flavor;
import com.facebook.buck.core.model.FlavorDomain;
import com.facebook.buck.core.model.FlavorDomainException;
import com.facebook.buck.core.model.Flavored;
import com.facebook.buck.core.model.InternalFlavor;
import com.facebook.buck.core.model.TargetConfiguration;
import com.facebook.buck.core.model.UserFlavor;
import com.facebook.buck.core.model.impl.BuildTargetPaths;
import com.facebook.buck.core.model.targetgraph.TargetGraph;
import com.facebook.buck.core.model.targetgraph.TargetNode;
import com.facebook.buck.core.rules.ActionGraphBuilder;
import com.facebook.buck.core.rules.BuildRule;
import com.facebook.buck.core.rules.BuildRuleCreationContextWithTargetGraph;
import com.facebook.buck.core.rules.BuildRuleParams;
import com.facebook.buck.core.rules.DescriptionWithTargetGraph;
import com.facebook.buck.core.rules.impl.AbstractBuildRuleWithDeclaredAndExtraDeps;
import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath;
import com.facebook.buck.core.sourcepath.PathSourcePath;
import com.facebook.buck.core.sourcepath.SourcePath;
import com.facebook.buck.core.test.rule.HasTestRunner;
import com.facebook.buck.core.test.rule.coercer.TestRunnerSpecCoercer;
import com.facebook.buck.core.test.rule.impl.ExternalTestRunner;
import com.facebook.buck.core.toolchain.ToolchainProvider;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.core.util.immutables.RuleArg;
import com.facebook.buck.cxx.CxxCompilationDatabase;
import com.facebook.buck.cxx.CxxDescriptionEnhancer;
import com.facebook.buck.cxx.CxxFocusedDebugTargets;
import com.facebook.buck.cxx.CxxLibraryDescription;
import com.facebook.buck.cxx.CxxPreprocessables;
import com.facebook.buck.cxx.CxxPreprocessorInput;
import com.facebook.buck.cxx.CxxStrip;
import com.facebook.buck.cxx.config.CxxBuckConfig;
import com.facebook.buck.cxx.toolchain.CxxPlatform;
import com.facebook.buck.cxx.toolchain.CxxPlatformsProvider;
import com.facebook.buck.cxx.toolchain.HeaderVisibility;
import com.facebook.buck.cxx.toolchain.LinkerMapMode;
import com.facebook.buck.cxx.toolchain.StripStyle;
import com.facebook.buck.cxx.toolchain.UnresolvedCxxPlatform;
import com.facebook.buck.cxx.toolchain.linker.Linker;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroup;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkableGroups;
import com.facebook.buck.cxx.toolchain.nativelink.NativeLinkables;
import com.facebook.buck.downwardapi.config.DownwardApiConfig;
import com.facebook.buck.io.filesystem.BuildCellRelativePath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.macros.AbsoluteOutputMacroExpander;
import com.facebook.buck.rules.macros.LocationMacroExpander;
import com.facebook.buck.rules.macros.StringWithMacros;
import com.facebook.buck.rules.macros.StringWithMacrosConverter;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MakeCleanDirectoryStep;
import com.facebook.buck.swift.SwiftBuckConfig;
import com.facebook.buck.swift.SwiftLibraryDescription;
import com.facebook.buck.test.config.TestBuckConfig;
import com.facebook.buck.unarchive.UnzipStep;
import com.facebook.buck.util.stream.RichStream;
import com.facebook.buck.util.types.Either;
import com.facebook.buck.versions.Version;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.immutables.value.Value;

public class AppleTestDescription
    implements DescriptionWithTargetGraph<AppleTestDescriptionArg>,
        Flavored,
        ImplicitDepsInferringDescription<AppleTestDescription.AbstractAppleTestDescriptionArg>,
        MetadataProvidingDescription<AppleTestDescriptionArg>,
        AppleLibrarySwiftDelegate {

  /** Flavors for the additional generated build rules. */
  static final Flavor LIBRARY_FLAVOR = InternalFlavor.of("apple-test-library");

  static final Flavor BUNDLE_FLAVOR = InternalFlavor.of("apple-test-bundle");
  private static final Flavor UNZIP_XCTOOL_FLAVOR = InternalFlavor.of("unzip-xctool");
  public static final UserFlavor COMPILE_DEPS =
      UserFlavor.of(
          "compile-deps",
          "Produces a directory containing the resource dependencies and an aggregated static library created from the dependencies of the target");

  private static final ImmutableSet<Flavor> SUPPORTED_FLAVORS =
      ImmutableSet.of(
          LIBRARY_FLAVOR,
          BUNDLE_FLAVOR,
          COMPILE_DEPS,
          CxxFocusedDebugTargets.FOCUSED_DEBUG_TARGETS);

  /**
   * Auxiliary build modes which makes this description emit just the results of the underlying
   * library delegate.
   */
  private static final Set<Flavor> AUXILIARY_LIBRARY_FLAVORS =
      ImmutableSet.of(
          CxxCompilationDatabase.COMPILATION_DATABASE,
          CxxDescriptionEnhancer.HEADER_SYMLINK_TREE_FLAVOR,
          CxxDescriptionEnhancer.EXPORTED_HEADER_SYMLINK_TREE_FLAVOR);

  private final ToolchainProvider toolchainProvider;
  private final XCodeDescriptions xcodeDescriptions;
  private final AppleConfig appleConfig;
  private final CxxBuckConfig cxxBuckConfig;
  private final SwiftBuckConfig swiftBuckConfig;
  private final DownwardApiConfig downwardApiConfig;
  private final AppleLibraryDescription appleLibraryDescription;

  public AppleTestDescription(
      ToolchainProvider toolchainProvider,
      XCodeDescriptions xcodeDescriptions,
      AppleConfig appleConfig,
      CxxBuckConfig cxxBuckConfig,
      SwiftBuckConfig swiftBuckConfig,
      DownwardApiConfig downwardApiConfig,
      AppleLibraryDescription appleLibraryDescription) {
    this.toolchainProvider = toolchainProvider;
    this.xcodeDescriptions = xcodeDescriptions;
    this.appleConfig = appleConfig;
    this.cxxBuckConfig = cxxBuckConfig;
    this.swiftBuckConfig = swiftBuckConfig;
    this.downwardApiConfig = downwardApiConfig;
    this.appleLibraryDescription = appleLibraryDescription;
  }

  @Override
  public Class<AppleTestDescriptionArg> getConstructorArgType() {
    return AppleTestDescriptionArg.class;
  }

  @Override
  public Optional<ImmutableSet<FlavorDomain<?>>> flavorDomains(
      TargetConfiguration toolchainTargetConfiguration) {
    return appleLibraryDescription.flavorDomains(toolchainTargetConfiguration);
  }

  @Override
  public boolean hasFlavors(
      ImmutableSet<Flavor> flavors, TargetConfiguration toolchainTargetConfiguration) {
    return Sets.difference(flavors, SUPPORTED_FLAVORS).isEmpty()
        || appleLibraryDescription.hasFlavors(flavors, toolchainTargetConfiguration);
  }

  @Override
  public BuildRule createBuildRule(
      BuildRuleCreationContextWithTargetGraph context,
      BuildTarget buildTarget,
      BuildRuleParams params,
      AppleTestDescriptionArg args) {
    ActionGraphBuilder graphBuilder = context.getActionGraphBuilder();
    args.checkDuplicateSources(graphBuilder.getSourcePathResolver());
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    CxxPlatformsProvider cxxPlatformsProvider =
        getCxxPlatformsProvider(buildTarget.getTargetConfiguration());
    if (buildTarget.getFlavors().contains(COMPILE_DEPS)) {
      return createCompileDepsRule(
          cxxPlatformsProvider, buildTarget, graphBuilder, context, params, args);
    }

    if (!appleConfig.shouldUseSwiftDelegate()) {
      // Tests should serialize debugging options as they are the top level module for a link unit.
      AppleTestDescriptionArg.Builder argBuilder = AppleTestDescriptionArg.builder();
      argBuilder.from(args);
      argBuilder.addSwiftCompilerFlags(
          StringWithMacros.ofConstantString("-Xfrontend"),
          StringWithMacros.ofConstantString("-serialize-debugging-options"));

      Optional<BuildRule> buildRule =
          appleLibraryDescription.createSwiftBuildRule(
              buildTarget,
              projectFilesystem,
              graphBuilder,
              context.getCellPathResolver(),
              argBuilder.build(),
              Optional.of(this));

      if (buildRule.isPresent()) {
        return buildRule.get();
      }
    }

    if (args.getUiTestTargetApp().isPresent() && !args.getIsUiTest()) {
      throw new HumanReadableException(
          "Invalid configuration for %s with 'ui_test_target_app' specified, but 'is_ui_test' set to false or 'test_host_app' not specified",
          buildTarget);
    }

    AppleDebugFormat debugFormat =
        AppleDebugFormat.FLAVOR_DOMAIN
            .getValue(buildTarget)
            .orElse(appleConfig.getDefaultDebugInfoFormatForTests());
    if (buildTarget.getFlavors().contains(debugFormat.getFlavor())) {
      buildTarget = buildTarget.withoutFlavors(debugFormat.getFlavor());
    }

    boolean createBundle =
        Sets.intersection(buildTarget.getFlavors().getSet(), AUXILIARY_LIBRARY_FLAVORS).isEmpty();
    // Flavors pertaining to the library targets that are generated.
    Sets.SetView<Flavor> libraryFlavors =
        Sets.difference(buildTarget.getFlavors().getSet(), AUXILIARY_LIBRARY_FLAVORS);
    boolean addDefaultPlatform = libraryFlavors.isEmpty();
    ImmutableSet.Builder<Flavor> extraFlavorsBuilder = ImmutableSet.builder();
    if (createBundle) {
      extraFlavorsBuilder.add(LIBRARY_FLAVOR, CxxDescriptionEnhancer.MACH_O_BUNDLE_FLAVOR);
    }
    extraFlavorsBuilder.add(debugFormat.getFlavor());
    if (addDefaultPlatform) {
      Flavor defaultCxxFlavor =
          args.getDefaultPlatform()
              .orElse(cxxPlatformsProvider.getDefaultUnresolvedCxxPlatform().getFlavor());
      extraFlavorsBuilder.add(defaultCxxFlavor);
    }

    FlavorDomain<UnresolvedAppleCxxPlatform> appleCxxPlatformFlavorDomain =
        AppleDescriptions.getAppleCxxPlatformsFlavorDomain(
            toolchainProvider, buildTarget.getTargetConfiguration());

    Optional<MultiarchFileInfo> multiarchFileInfo =
        MultiarchFileInfos.create(appleCxxPlatformFlavorDomain, buildTarget);
    AppleCxxPlatform appleCxxPlatform;
    ImmutableList<CxxPlatform> cxxPlatforms;
    TargetConfiguration targetConfiguration = buildTarget.getTargetConfiguration();
    if (multiarchFileInfo.isPresent()) {
      FlavorDomain<UnresolvedCxxPlatform> cxxPlatformFlavorDomain =
          cxxPlatformsProvider.getUnresolvedCxxPlatforms();
      ImmutableList.Builder<CxxPlatform> cxxPlatformBuilder = ImmutableList.builder();
      for (BuildTarget thinTarget : multiarchFileInfo.get().getThinTargets()) {
        cxxPlatformBuilder.add(
            cxxPlatformFlavorDomain
                .getValue(thinTarget)
                .get()
                .resolve(graphBuilder, targetConfiguration));
      }
      cxxPlatforms = cxxPlatformBuilder.build();
      appleCxxPlatform =
          appleCxxPlatformFlavorDomain
              .getValue(multiarchFileInfo.get().getRepresentativePlatformFlavor())
              .resolve(graphBuilder);
    } else {
      CxxPlatform cxxPlatform =
          ApplePlatforms.getCxxPlatformForBuildTarget(
                  cxxPlatformsProvider, buildTarget, args.getDefaultPlatform())
              .resolve(graphBuilder, buildTarget.getTargetConfiguration());
      cxxPlatforms = ImmutableList.of(cxxPlatform);
      appleCxxPlatform =
          verifyAppleCxxPlatform(appleCxxPlatformFlavorDomain, cxxPlatform, buildTarget)
              .resolve(graphBuilder);
    }

    Optional<TestHostInfo> testHostWithTargetApp =
        args.getTestHostApp().isPresent()
            ? Optional.of(
                createTestHostInfo(
                    buildTarget,
                    args.getIsUiTest(),
                    graphBuilder,
                    args.getTestHostApp().get(),
                    args.getUiTestTargetApp(),
                    debugFormat,
                    libraryFlavors,
                    cxxPlatforms))
            : Optional.empty();

    BuildTarget libraryTarget =
        buildTarget
            .withAppendedFlavors(extraFlavorsBuilder.build())
            .withAppendedFlavors(debugFormat.getFlavor())
            .withAppendedFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor());
    BuildRule library =
        createTestLibraryRule(
            context,
            params,
            graphBuilder,
            args,
            testHostWithTargetApp.flatMap(TestHostInfo::getTestHostAppBinarySourcePath),
            testHostWithTargetApp.map(TestHostInfo::getBlacklist).orElse(ImmutableSet.of()),
            libraryTarget,
            RichStream.from(args.getTestHostApp()).toImmutableSortedSet(Ordering.natural()),
            appleCxxPlatform);

    boolean hasFocusedDebuggingFlavor =
        buildTarget.getFlavors().contains(CxxFocusedDebugTargets.FOCUSED_DEBUG_TARGETS);

    if (!createBundle
        || SwiftLibraryDescription.isSwiftTarget(libraryTarget)
        || hasFocusedDebuggingFlavor) {
      return library;
    }

    String platformName = appleCxxPlatform.getAppleSdk().getApplePlatform().getName();
    BuildTarget appleBundleBuildTarget =
        buildTarget.withAppendedFlavors(
            BUNDLE_FLAVOR,
            debugFormat.getFlavor(),
            LinkerMapMode.NO_LINKER_MAP.getFlavor(),
            AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR);
    AppleBundle bundle =
        (AppleBundle)
            graphBuilder.computeIfAbsent(
                appleBundleBuildTarget,
                ignored ->
                    AppleDescriptions.createAppleBundle(
                        xcodeDescriptions,
                        getCxxPlatformsProvider(targetConfiguration),
                        appleCxxPlatformFlavorDomain,
                        context.getTargetGraph(),
                        appleBundleBuildTarget,
                        projectFilesystem,
                        params.withDeclaredDeps(
                            ImmutableSortedSet.<BuildRule>naturalOrder()
                                .add(library)
                                .addAll(params.getDeclaredDeps().get())
                                .build()),
                        graphBuilder,
                        toolchainProvider.getByName(
                            CodeSignIdentityStore.DEFAULT_NAME,
                            targetConfiguration,
                            CodeSignIdentityStore.class),
                        toolchainProvider.getByName(
                            ProvisioningProfileStore.DEFAULT_NAME,
                            targetConfiguration,
                            ProvisioningProfileStore.class),
                        Optional.of(library.getBuildTarget()),
                        Optional.empty(),
                        args.getDefaultPlatform(),
                        args.getExtension(),
                        Optional.empty(),
                        args.getInfoPlist(),
                        args.getInfoPlistSubstitutions(),
                        args.getDeps(),
                        args.getTests(),
                        debugFormat,
                        appleConfig.getDsymutilExtraFlags(),
                        appleConfig.getVerifyDsym(),
                        appleConfig.getDwarfdumpFailsDsymVerification(),
                        appleConfig.useDryRunCodeSigning(),
                        appleConfig.cacheBundlesAndPackages(),
                        appleConfig.shouldVerifyBundleResources(),
                        appleConfig.assetCatalogValidation(),
                        args.getAssetCatalogsCompilationOptions(),
                        args.getCodesignFlags(),
                        args.getCodesignIdentity(),
                        Optional.empty(),
                        Optional.empty(),
                        appleConfig.getCodesignTimeout(),
                        swiftBuckConfig.getCopyStdlibToFrameworks(),
                        cxxBuckConfig.shouldCacheStrip(),
                        appleConfig.useEntitlementsWhenAdhocCodeSigning(),
                        Predicates.alwaysTrue(),
                        swiftBuckConfig.getSliceAppPackageSwiftRuntime(),
                        swiftBuckConfig.getSliceAppBundleSwiftRuntime(),
                        downwardApiConfig.isEnabledForApple(),
                        args.getTargetSdkVersion(),
                        appleConfig.getIncrementalBundlingEnabled(),
                        appleConfig.getCodeSignTypeOverride(),
                        appleConfig.getBundleInputBasedRulekeyEnabled(),
                        appleConfig.getIncrementalHashCacheEnabled(),
                        appleConfig.getEmbedXctestInTestBundles(),
                        appleConfig.getDoNotEmbedHostAppInTestBundle(),
                        testHostWithTargetApp));

    Optional<SourcePath> xctool =
        getXctool(projectFilesystem, params, targetConfiguration, graphBuilder);

    StringWithMacrosConverter macrosConverter =
        StringWithMacrosConverter.of(
            buildTarget,
            context.getCellPathResolver().getCellNameResolver(),
            graphBuilder,
            ImmutableList.of(LocationMacroExpander.INSTANCE, AbsoluteOutputMacroExpander.INSTANCE));

    if (args.getSpecs().isPresent()) {
      UserVerify.verify(
          args.getRunner().isPresent(),
          "runner should be specified for rules implementing test protocol");
      BuildRule runnerRule = graphBuilder.requireRule(args.getRunner().get());
      UserVerify.verify(
          runnerRule instanceof ExternalTestRunner,
          "runner should be an external_test_runner for apple_test");

      ExternalTestRunner runner = (ExternalTestRunner) runnerRule;

      return new AppleTestX(
          runner.getBinary(),
          TestRunnerSpecCoercer.coerce(args.getSpecs().get(), macrosConverter),
          xctool,
          appleConfig.getXctoolStutterTimeoutMs(),
          appleCxxPlatform.getXctest(),
          appleConfig.getXctestPlatformNames().contains(platformName),
          platformName,
          appleConfig.getXctoolDefaultDestinationSpecifier(),
          buildTarget,
          projectFilesystem,
          params.withDeclaredDeps(ImmutableSortedSet.of(bundle)).withoutExtraDeps(),
          bundle,
          testHostWithTargetApp.map(TestHostInfo::getTestHostApp),
          testHostWithTargetApp.flatMap(TestHostInfo::getUiTestTargetApp),
          args.getContacts(),
          args.getLabels(),
          toolchainProvider.getByNameIfPresent(
              AppleDeveloperDirectoryForTestsProvider.DEFAULT_NAME,
              targetConfiguration,
              AppleDeveloperDirectoryForTestsProvider.class),
          args.getIsUiTest(),
          args.getSnapshotReferenceImagesPath(),
          appleConfig.useIdb(),
          appleConfig.getIdbPath());
    }

    ImmutableMap<String, Arg> testEnv =
        ImmutableMap.copyOf(
            Maps.transformValues(
                args.getEnv().orElse(ImmutableMap.of()), macrosConverter::convert));

    return new AppleTest(
        xctool,
        appleConfig.getXctoolStutterTimeoutMs(),
        appleCxxPlatform.getXctest(),
        appleConfig.getXctestPlatformNames().contains(platformName),
        platformName,
        appleConfig.getXctoolDefaultDestinationSpecifier(),
        Optional.of(args.getDestinationSpecifier()),
        buildTarget,
        projectFilesystem,
        params.withDeclaredDeps(ImmutableSortedSet.of(bundle)).withoutExtraDeps(),
        bundle,
        testHostWithTargetApp.map(TestHostInfo::getTestHostApp),
        testHostWithTargetApp.flatMap(TestHostInfo::getUiTestTargetApp),
        args.getContacts(),
        args.getLabels(),
        args.getRunTestSeparately(),
        toolchainProvider.getByNameIfPresent(
            AppleDeveloperDirectoryForTestsProvider.DEFAULT_NAME,
            targetConfiguration,
            AppleDeveloperDirectoryForTestsProvider.class),
        appleConfig.getTestLogDirectoryEnvironmentVariable(),
        appleConfig.getTestLogLevelEnvironmentVariable(),
        appleConfig.getTestLogLevel(),
        args.getTestRuleTimeoutMs()
            .map(Optional::of)
            .orElse(
                appleConfig
                    .getDelegate()
                    .getView(TestBuckConfig.class)
                    .getDefaultTestRuleTimeoutMs()),
        args.getIsUiTest(),
        args.getSnapshotReferenceImagesPath(),
        Optional.of(testEnv),
        appleConfig.useIdb(),
        appleConfig.getIdbPath(),
        downwardApiConfig.isEnabledForApple());
  }

  private UnresolvedAppleCxxPlatform verifyAppleCxxPlatform(
      FlavorDomain<UnresolvedAppleCxxPlatform> appleCxxPlatformFlavorDomain,
      CxxPlatform cxxPlatform,
      BuildTarget buildTarget) {
    UnresolvedAppleCxxPlatform appleCxxPlatform;
    try {
      appleCxxPlatform = appleCxxPlatformFlavorDomain.getValue(cxxPlatform.getFlavor());
    } catch (FlavorDomainException e) {
      throw new HumanReadableException(
          e,
          "%s: Apple test requires an Apple platform, found '%s'",
          buildTarget,
          cxxPlatform.getFlavor().getName());
    }
    return appleCxxPlatform;
  }

  private boolean flavorIndicatesStaticLibrary(Flavor flavor) {
    boolean isCxxLibraryType = CxxLibraryDescription.LIBRARY_TYPE.contains(flavor);
    boolean isStaticLibrary = flavor == CxxLibraryDescription.Type.STATIC.getFlavor();
    return isCxxLibraryType && isStaticLibrary;
  }

  private boolean flavorIndicatesCorrectPlatform(Flavor flavor, CxxPlatform cxxPlatform) {
    boolean isApplePlatform = ApplePlatformType.of(flavor.getName()) != ApplePlatformType.UNKNOWN;
    boolean sameApplePlatform =
        ApplePlatform.of(flavor.getName()) == ApplePlatform.of(cxxPlatform.getFlavor().getName());
    return isApplePlatform && sameApplePlatform;
  }

  private boolean configSdkRootIndicatesCorrectPlatform(
      TargetNode<AppleLibraryDescriptionArg> targetNode, AppleTestDescriptionArg args) {
    if (targetNode.getConstructorArg().getConfigs() == null
        || targetNode.getConstructorArg().getConfigs().get("Debug") == null
        || targetNode.getConstructorArg().getConfigs().get("Debug").get("SDKROOT") == null
        || args.getConfigs() == null
        || args.getConfigs().get("Debug") == null
        || args.getConfigs().get("Debug").get("SDKROOT") == null) {
      return true;
    }
    return ApplePlatform.of(targetNode.getConstructorArg().getConfigs().get("Debug").get("SDKROOT"))
        == ApplePlatform.of(args.getConfigs().get("Debug").get("SDKROOT"));
  }

  private BuildRule createCompileDepsRule(
      CxxPlatformsProvider cxxPlatformsProvider,
      BuildTarget buildTarget,
      ActionGraphBuilder graphBuilder,
      BuildRuleCreationContextWithTargetGraph context,
      BuildRuleParams params,
      AppleTestDescriptionArg args) {
    CxxPlatform cxxPlatform =
        ApplePlatforms.getCxxPlatformForBuildTarget(
                cxxPlatformsProvider, buildTarget, args.getDefaultPlatform())
            .resolve(graphBuilder, buildTarget.getTargetConfiguration());
    FlavorDomain<UnresolvedAppleCxxPlatform> appleCxxPlatformFlavorDomain =
        AppleDescriptions.getAppleCxxPlatformsFlavorDomain(
            toolchainProvider, buildTarget.getTargetConfiguration());
    AppleCxxPlatform appleCxxPlatform =
        verifyAppleCxxPlatform(appleCxxPlatformFlavorDomain, cxxPlatform, buildTarget)
            .resolve(graphBuilder);
    TargetGraph targetGraph = context.getTargetGraph();
    AppleBundleResources collectedResources =
        AppleResources.collectResourceDirsAndFiles(
            xcodeDescriptions,
            targetGraph,
            graphBuilder,
            Optional.empty(),
            targetGraph.get(buildTarget),
            appleCxxPlatform,
            AppleBuildRules.RecursiveDependenciesMode.COPYING,
            Predicates.alwaysTrue());

    ImmutableSortedSet<BuildRule> transitiveStaticLibraryDependencies =
        collectTransitiveStaticLibraries(
            targetGraph, buildTarget, cxxPlatform, args, graphBuilder, context, params);
    ImmutableList<SourcePath> depBuildRuleSourcePaths =
        transitiveStaticLibraryDependencies.stream()
            .map(BuildRule::getSourcePathToOutput)
            .filter(Objects::nonNull)
            .collect(ImmutableList.toImmutableList());
    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

    Path outputPath =
        BuildTargetPaths.getGenPath(projectFilesystem.getBuckPaths(), buildTarget, "%s")
            .resolve(AppleTestDescription.COMPILE_DEPS.getName());

    BuildTarget processResourcesTarget =
        buildTarget
            .withoutFlavors(SUPPORTED_FLAVORS)
            .withAppendedFlavors(AppleProcessResources.FLAVOR);
    AppleProcessResources processResources =
        (AppleProcessResources)
            graphBuilder.computeIfAbsent(
                processResourcesTarget,
                target ->
                    new AppleProcessResources(
                        target,
                        projectFilesystem,
                        graphBuilder,
                        collectedResources.getResourceFiles(),
                        collectedResources.getResourceVariantFiles(),
                        collectedResources.getNamedResourceVariantFiles(),
                        ImmutableList.of(),
                        false,
                        appleCxxPlatform.getIbtool(),
                        false,
                        buildTarget,
                        Optional.empty(),
                        downwardApiConfig.isEnabledForApple(),
                        appleCxxPlatform.getAppleSdk().getApplePlatform(),
                        AppleBundleDestinations.platformDestinations(
                            appleCxxPlatform.getAppleSdk().getApplePlatform()),
                        appleConfig.getIncrementalBundlingEnabled()));

    return new AppleTestAggregatedDependencies(
        buildTarget,
        projectFilesystem,
        graphBuilder,
        outputPath,
        collectedResources,
        appleCxxPlatform,
        depBuildRuleSourcePaths,
        downwardApiConfig.isEnabledForApple(),
        processResources.getSourcePathToOutput());
  }

  private ImmutableSortedSet<BuildRule> collectTransitiveStaticLibraries(
      TargetGraph targetGraph,
      BuildTarget buildTarget,
      CxxPlatform cxxPlatform,
      AppleTestDescriptionArg args,
      ActionGraphBuilder graphBuilder,
      BuildRuleCreationContextWithTargetGraph context,
      BuildRuleParams params) {
    ImmutableSet<TargetNode<AppleLibraryDescriptionArg>>
        transitiveStaticLibraryDependencyTargetNodes =
            AppleBuildRules.collectTransitiveBuildRuleTargets(
                xcodeDescriptions,
                targetGraph,
                Optional.empty(),
                ImmutableSet.of(AppleLibraryDescription.class),
                ImmutableList.of(targetGraph.get(buildTarget)),
                RecursiveDependenciesMode.BUILDING);
    return transitiveStaticLibraryDependencyTargetNodes.stream()
        .filter(
            t ->
                t.getBuildTarget().getFlavors().getSet().stream()
                        .reduce(
                            true,
                            (result, next) ->
                                result
                                    && flavorIndicatesStaticLibrary(next)
                                    && flavorIndicatesCorrectPlatform(next, cxxPlatform),
                            (result1, result2) -> result1 && result2)
                    && configSdkRootIndicatesCorrectPlatform(t, args))
        .map(
            t ->
                graphBuilder.computeIfAbsent(
                    t.getBuildTarget()
                        .withoutFlavors()
                        .withAppendedFlavors(
                            CxxLibraryDescription.Type.STATIC.getFlavor(), cxxPlatform.getFlavor()),
                    t2 ->
                        appleLibraryDescription.createBuildRule(
                            context, t2, params, t.getConstructorArg())))
        .collect(ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder()));
  }

  private Optional<SourcePath> getXctool(
      ProjectFilesystem projectFilesystem,
      BuildRuleParams params,
      TargetConfiguration targetConfiguration,
      ActionGraphBuilder graphBuilder) {
    // If xctool is specified as a build target in the buck config, it's wrapping ZIP file which
    // we need to unpack to get at the actual binary.  Otherwise, if it's specified as a path, we
    // can use that directly.
    if (appleConfig.getXctoolZipTarget(targetConfiguration).isPresent()) {
      BuildRule xctoolZipBuildRule =
          graphBuilder.getRule(appleConfig.getXctoolZipTarget(targetConfiguration).get());

      // Since the content is unzipped in a directory that might differ for each cell the tests are
      // from, we append a flavor that depends on the root path of the projectFilesystem
      // in order to get a different rule for each cell the tests are from.
      String relativeRootPathString =
          xctoolZipBuildRule
              .getProjectFilesystem()
              .relativize(projectFilesystem.getRootPath())
              .toString();
      Hasher hasher = Hashing.sha1().newHasher();
      hasher.putBytes(relativeRootPathString.getBytes(StandardCharsets.UTF_8));
      String sha1Hash = hasher.hash().toString();

      BuildTarget unzipXctoolTarget =
          xctoolZipBuildRule
              .getBuildTarget()
              .withAppendedFlavors(UNZIP_XCTOOL_FLAVOR)
              .withAppendedFlavors(InternalFlavor.of(sha1Hash));
      RelPath outputDirectory =
          BuildTargetPaths.getGenPath(
              xctoolZipBuildRule.getProjectFilesystem().getBuckPaths(),
              unzipXctoolTarget,
              "%s/unzipped");
      graphBuilder.computeIfAbsent(
          unzipXctoolTarget,
          ignored -> {
            BuildRuleParams unzipXctoolParams =
                params
                    .withDeclaredDeps(ImmutableSortedSet.of(xctoolZipBuildRule))
                    .withoutExtraDeps();
            return new AbstractBuildRuleWithDeclaredAndExtraDeps(
                unzipXctoolTarget, xctoolZipBuildRule.getProjectFilesystem(), unzipXctoolParams) {
              @Override
              public ImmutableList<Step> getBuildSteps(
                  BuildContext context, BuildableContext buildableContext) {
                buildableContext.recordArtifact(outputDirectory.getPath());
                return new ImmutableList.Builder<Step>()
                    .addAll(
                        MakeCleanDirectoryStep.of(
                            BuildCellRelativePath.fromCellRelativePath(
                                context.getBuildCellRootPath(),
                                getProjectFilesystem(),
                                outputDirectory)))
                    .add(
                        new UnzipStep(
                            getProjectFilesystem(),
                            context
                                .getSourcePathResolver()
                                .getAbsolutePath(
                                    Objects.requireNonNull(
                                        xctoolZipBuildRule.getSourcePathToOutput()))
                                .getPath(),
                            outputDirectory.getPath(),
                            Optional.empty()))
                    .build();
              }

              @Override
              public SourcePath getSourcePathToOutput() {
                return ExplicitBuildTargetSourcePath.of(getBuildTarget(), outputDirectory);
              }
            };
          });
      return Optional.of(
          ExplicitBuildTargetSourcePath.of(
              unzipXctoolTarget, outputDirectory.resolve("bin/xctool")));
    } else if (appleConfig.getXctoolPath().isPresent()) {
      return Optional.of(PathSourcePath.of(projectFilesystem, appleConfig.getXctoolPath().get()));
    } else {
      return Optional.empty();
    }
  }

  private BuildRule createTestLibraryRule(
      BuildRuleCreationContextWithTargetGraph context,
      BuildRuleParams params,
      ActionGraphBuilder graphBuilder,
      AppleTestDescriptionArg args,
      Optional<SourcePath> testHostAppBinarySourcePath,
      ImmutableSet<BuildTarget> blacklist,
      BuildTarget libraryTarget,
      ImmutableSortedSet<BuildTarget> extraCxxDeps,
      AppleCxxPlatform appleCxxPlatform) {
    BuildTarget existingLibraryTarget =
        libraryTarget
            .withAppendedFlavors(AppleDebuggableBinary.RULE_FLAVOR, CxxStrip.RULE_FLAVOR)
            .withAppendedFlavors(StripStyle.NON_GLOBAL_SYMBOLS.getFlavor());
    Optional<BuildRule> existingLibrary = graphBuilder.getRuleOptional(existingLibraryTarget);
    BuildRule library;
    if (existingLibrary.isPresent()) {
      library = existingLibrary.get();
    } else {
      library =
          appleLibraryDescription.createLibraryBuildRule(
              context,
              libraryTarget,
              params,
              graphBuilder,
              appendTestArgs(args, appleCxxPlatform),
              // For now, instead of building all deps as dylibs and fixing up their install_names,
              // we'll just link them statically.
              Optional.of(Linker.LinkableDepType.STATIC),
              testHostAppBinarySourcePath,
              blacklist,
              extraCxxDeps,
              CxxLibraryDescription.TransitiveCxxPreprocessorInputFunction.fromDeps());
      graphBuilder.computeIfAbsent(library.getBuildTarget(), ignored -> library);
    }
    return library;
  }

  private AppleTestDescriptionArg appendTestArgs(
      AppleTestDescriptionArg args, AppleCxxPlatform appleCxxPlatform) {
    AppleTestDescriptionArg.Builder builder = AppleTestDescriptionArg.builder().from(args);

    if (appleConfig.getEmbedXctestInTestBundles()) {
      AppleBundleDestinations destination =
          AppleBundleDestinations.platformDestinations(
              appleCxxPlatform.getAppleSdk().getApplePlatform());
      Path pathToFrameworks =
          destination.getExecutablesPath().relativize(destination.getFrameworksPath());
      String linkerArg = "-Wl,-rpath,@executable_path/" + pathToFrameworks.toString();
      builder.addLinkerFlags(StringWithMacros.ofConstantString(linkerArg));
    }

    if (swiftBuckConfig.getAddXctestImportPaths()) {
      // When importing XCTest in Swift, we will need to add the linker search paths to
      // find libXCTestSupport.dylib and XCTest.framework.
      builder.addLinkerFlags(
          StringWithMacros.ofConstantString("-L$PLATFORM_DIR/Developer/usr/lib"),
          StringWithMacros.ofConstantString("-F$PLATFORM_DIR/Developer/Library/Frameworks"));
    }

    return builder.build();
  }

  @Override
  public void findDepsForTargetFromConstructorArgs(
      BuildTarget buildTarget,
      CellNameResolver cellRoots,
      AbstractAppleTestDescriptionArg constructorArg,
      ImmutableCollection.Builder<BuildTarget> extraDepsBuilder,
      ImmutableCollection.Builder<BuildTarget> targetGraphOnlyDepsBuilder) {
    // TODO(beng, coneko): This should technically only be a runtime dependency;
    // doing this adds it to the extra deps in BuildRuleParams passed to
    // the bundle and test rule.
    Optional<BuildTarget> xctoolZipTarget =
        appleConfig.getXctoolZipTarget(buildTarget.getTargetConfiguration());
    if (xctoolZipTarget.isPresent()) {
      extraDepsBuilder.add(xctoolZipTarget.get());
    }
    extraDepsBuilder.addAll(
        appleConfig.getCodesignProvider().getParseTimeDeps(buildTarget.getTargetConfiguration()));

    CxxPlatformsProvider cxxPlatformsProvider =
        getCxxPlatformsProvider(buildTarget.getTargetConfiguration());
    ImmutableList<UnresolvedCxxPlatform> cxxPlatforms =
        cxxPlatformsProvider.getUnresolvedCxxPlatforms().getValues(buildTarget);

    if (cxxPlatforms.isEmpty()) {
      extraDepsBuilder.addAll(
          cxxPlatformsProvider
              .getDefaultUnresolvedCxxPlatform()
              .getParseTimeDeps(buildTarget.getTargetConfiguration()));
    } else {
      cxxPlatforms.forEach(
          platform ->
              extraDepsBuilder.addAll(
                  platform.getParseTimeDeps(buildTarget.getTargetConfiguration())));
    }
    AppleDescriptions.findToolchainDeps(buildTarget, targetGraphOnlyDepsBuilder, toolchainProvider);
  }

  private AppleBundle getBuildRuleForTestHostAppTarget(
      BuildTarget buildTarget,
      ActionGraphBuilder graphBuilder,
      BuildTarget testHostBuildTarget,
      AppleDebugFormat debugFormat,
      Iterable<Flavor> additionalFlavors,
      String testHostKeyName) {
    BuildRule rule =
        graphBuilder.requireRule(
            testHostBuildTarget.withAppendedFlavors(
                ImmutableSet.<Flavor>builder()
                    .addAll(additionalFlavors)
                    .add(debugFormat.getFlavor(), StripStyle.NON_GLOBAL_SYMBOLS.getFlavor())
                    .build()));

    if (!(rule instanceof AppleBundle)) {
      throw new HumanReadableException(
          "Apple test rule '%s' has %s '%s' not of type '%s'.",
          buildTarget,
          testHostKeyName,
          testHostBuildTarget,
          DescriptionCache.getRuleType(AppleBundleDescription.class));
    }
    return (AppleBundle) rule;
  }

  @VisibleForTesting
  TestHostInfo createTestHostInfo(
      BuildTarget buildTarget,
      boolean isUITestTestHostInfo,
      ActionGraphBuilder graphBuilder,
      BuildTarget testHostAppBuildTarget,
      Optional<BuildTarget> uiTestTargetAppBuildTarget,
      AppleDebugFormat debugFormat,
      Iterable<Flavor> additionalFlavors,
      ImmutableList<CxxPlatform> cxxPlatforms) {

    AppleBundle testHostWithTargetApp =
        getBuildRuleForTestHostAppTarget(
            buildTarget,
            graphBuilder,
            testHostAppBuildTarget,
            debugFormat,
            additionalFlavors,
            "test_host_app");

    SourcePath testHostAppBinarySourcePath =
        testHostWithTargetApp.getBinaryBuildRule().getSourcePathToOutput();

    ImmutableMap<BuildTarget, NativeLinkableGroup> roots =
        NativeLinkableGroups.getNativeLinkableRoots(
            testHostWithTargetApp.getBinaryBuildRule().getBuildDeps(),
            r ->
                !(r instanceof NativeLinkableGroup)
                    ? Optional.of(r.getBuildDeps())
                    : Optional.empty());

    // Union the blacklist of all the platforms. This should give a superset for each particular
    // platform, which should be acceptable as items in the blacklist thare are unmatched are simply
    // ignored.
    ImmutableSet.Builder<BuildTarget> blacklistBuilder = ImmutableSet.builder();
    for (CxxPlatform platform : cxxPlatforms) {
      ImmutableSet<BuildTarget> blacklistables =
          NativeLinkables.getTransitiveNativeLinkables(
                  graphBuilder,
                  Iterables.transform(
                      roots.values(), g -> g.getNativeLinkable(platform, graphBuilder)))
              .stream()
              .filter(x -> !x.shouldBeLinkedInAppleTestAndHost())
              .map(x -> x.getBuildTarget())
              .collect(ImmutableSet.toImmutableSet());
      blacklistBuilder.addAll(blacklistables);
    }

    if (!uiTestTargetAppBuildTarget.isPresent()) {
      // Check for legacy UITest setup
      if (isUITestTestHostInfo) {
        return ImmutableTestHostInfo.ofImpl(
            testHostWithTargetApp,
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableSet.of());
      }
      return ImmutableTestHostInfo.ofImpl(
          testHostWithTargetApp,
          Optional.empty(),
          Optional.of(testHostAppBinarySourcePath),
          Optional.empty(),
          blacklistBuilder.build());
    }
    AppleBundle uiTestTargetApp =
        getBuildRuleForTestHostAppTarget(
            buildTarget,
            graphBuilder,
            uiTestTargetAppBuildTarget.get(),
            debugFormat,
            additionalFlavors,
            "ui_test_target_app");
    SourcePath uiTestTargetAppBinarySourcePath =
        uiTestTargetApp.getBinaryBuildRule().getSourcePathToOutput();

    return ImmutableTestHostInfo.ofImpl(
        testHostWithTargetApp,
        Optional.of(uiTestTargetApp),
        Optional.of(testHostAppBinarySourcePath),
        Optional.of(uiTestTargetAppBinarySourcePath),
        blacklistBuilder.build());
  }

  @Override
  public <U> Optional<U> createMetadata(
      BuildTarget buildTarget,
      ActionGraphBuilder graphBuilder,
      CellPathResolver cellRoots,
      AppleTestDescriptionArg args,
      Optional<ImmutableMap<BuildTarget, Version>> selectedVersions,
      Class<U> metadataClass) {
    return appleLibraryDescription.createMetadataForLibrary(
        buildTarget, graphBuilder, cellRoots, args, metadataClass);
  }

  private CxxPlatformsProvider getCxxPlatformsProvider(
      TargetConfiguration toolchainTargetConfiguration) {
    return toolchainProvider.getByName(
        CxxPlatformsProvider.DEFAULT_NAME,
        toolchainTargetConfiguration,
        CxxPlatformsProvider.class);
  }

  @BuckStyleValue
  interface TestHostInfo {
    AppleBundle getTestHostApp();

    Optional<AppleBundle> getUiTestTargetApp();

    /**
     * Location of the test host binary that can be passed as the "bundle loader" option when
     * linking the test library.
     */
    Optional<SourcePath> getTestHostAppBinarySourcePath();

    /**
     * Location of the ui test target binary that can be passed test target application of UITest
     */
    Optional<SourcePath> getUiTestTargetAppBinarySourcePath();

    /** Libraries included in test host that should not be linked into the test library. */
    ImmutableSet<BuildTarget> getBlacklist();
  }

  @RuleArg
  interface AbstractAppleTestDescriptionArg
      extends AppleNativeTargetDescriptionArg,
          HasAppleBundleFields,
          HasAppleCodesignFields,
          HasEntitlementsFile,
          HasTestTimeout,
          HasTestRunner {
    @Value.Default
    default boolean getRunTestSeparately() {
      return false;
    }

    @Value.Default
    default boolean getIsUiTest() {
      return false;
    }

    // Application used to host test bundle process
    Optional<BuildTarget> getTestHostApp();

    // Application used as XCUITest application target.
    Optional<BuildTarget> getUiTestTargetApp();

    // for use with FBSnapshotTestcase, injects the path as FB_REFERENCE_IMAGE_DIR
    Optional<Either<SourcePath, String>> getSnapshotReferenceImagesPath();

    // Bundle related fields.
    ImmutableMap<String, String> getDestinationSpecifier();

    // Environment variables to set during the test run
    Optional<ImmutableMap<String, StringWithMacros>> getEnv();

    @Override
    default Either<AppleBundleExtension, String> getExtension() {
      return Either.ofLeft(AppleBundleExtension.XCTEST);
    }

    @Override
    default Optional<String> getProductName() {
      return Optional.empty();
    }
  }

  // AppleLibrarySwiftDelegate

  @Override
  public ImmutableSet<CxxPreprocessorInput> getPreprocessorInputForSwift(
      BuildTarget buildTarget,
      ActionGraphBuilder graphBuilder,
      CxxPlatform cxxPlatform,
      CxxLibraryDescription.CommonArg args) {

    ImmutableSet<BuildRule> deps = args.getCxxDeps().get(graphBuilder, cxxPlatform);
    BuildTarget baseTarget = buildTarget.withFlavors();
    Optional<CxxPreprocessorInput> publicInput =
        CxxLibraryDescription.queryMetadataCxxPreprocessorInput(
            graphBuilder, baseTarget, cxxPlatform, HeaderVisibility.PUBLIC);
    Collection<CxxPreprocessorInput> depsInputs =
        CxxPreprocessables.getTransitiveCxxPreprocessorInputFromDeps(
            cxxPlatform, graphBuilder, deps);

    ImmutableSet.Builder<CxxPreprocessorInput> inputsBuilder = ImmutableSet.builder();
    inputsBuilder.addAll(depsInputs);
    publicInput.ifPresent(i -> inputsBuilder.add(i));

    return inputsBuilder.build();
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>io.trygvis.usb</groupId>
    <artifactId>javax-usb-libusb1</artifactId>
    <version>1.0.1-1-SNAPSHOT</version>
  </parent>
  <artifactId>usbtools</artifactId>
  <name>Javalibusb1 :: Misc USB tools</name>
  <packaging>nar</packaging>
  <dependencies>
    <dependency>
      <groupId>io.trygvis.usb</groupId>
      <artifactId>javalibusb1</artifactId>
      <version>${project.version}</version>
      <type>nar</type>
    </dependency>
    <dependency>
      <groupId>io.trygvis.usb</groupId>
      <artifactId>javax.usb-extra</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.4</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
      <plugin>
        <groupId>io.trygvis.usb</groupId>
        <artifactId>maven-nar-plugin</artifactId>
        <executions>
          <execution>
            <id>default-nar-unpack</id>
            <!--
            <configuration>
              <classifiers>
                <classifier>i386-Linux-gpp-jni</classifier>
                <classifier>i386-MacOSX-gpp-jni</classifier>
                <classifier>x86_64-MacOSX-gpp-jni</classifier>
              </classifiers>
            </configuration>
            -->
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <phase>integration-test</phase>
            <goals>
              <goal>single</goal>
              <goal>directory-single</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/all.xml</descriptor>
            <!--
            <descriptor>src/main/assembly/i386-MacOSX-gpp.xml</descriptor>
            <descriptor>src/main/assembly/x86_64-MacOSX-gpp.xml</descriptor>
            -->
          </descriptors>
          <tarLongFileMode>gnu</tarLongFileMode>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>appassembler-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>assemble</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <includeConfigurationDirectoryInClasspath>true</includeConfigurationDirectoryInClasspath>
          <configurationDirectory>lib</configurationDirectory>
          <programs>
            <program>
              <name>lsusb</name>
              <mainClass>io.trygvis.usb.tools.lsusb</mainClass>
            </program>
            <program>
              <name>fx2programmer</name>
              <mainClass>io.trygvis.usb.tools.Fx2Programmer</mainClass>
            </program>
            <program>
              <name>usbecho</name>
              <mainClass>io.trygvis.usb.tools.UsbEcho</mainClass>
            </program>
            <program>
              <name>usb-read</name>
              <mainClass>io.trygvis.usb.tools.UsbRead</mainClass>
            </program>
            <program>
              <name>usb-write</name>
              <mainClass>io.trygvis.usb.tools.UsbWrite</mainClass>
            </program>
            <program>
              <name>ztex-memtest</name>
              <mainClass>io.trygvis.usb.tools.ztex.MemTest</mainClass>
            </program>
            <program>
              <name>ztex-load-bitstream</name>
              <mainClass>io.trygvis.usb.tools.ztex.ZtexLoadBitStream</mainClass>
            </program>
          </programs>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <properties>
    <localRepository>${user.home}/.m2/repository</localRepository>
  </properties>
</project>

redpajama_set_name: RedPajamaGithub


text:
import path from 'path';
import assert from 'assert';

let script = require(__filename.replace(/_test\.js$/, '_solution.js'));

describe('examples', () => {

  it('example 1', () => {
    assert.equal(script.run(')'), 1);
  });

  it('example 2', () => {
    assert.equal(script.run('()())'), 5);
  });

});


text:
package org.apache.bcel.classfile;

import org.apache.bcel.Constants;
import java.io.*;

/**
 * This class represents a constant pool reference to an interface method.
 *
 * @version $Id: ConstantInterfaceMethodref.java,v 1.2 2006/08/22 15:33:21 andos Exp $
 * @author  M. Dahm
 */
public final class ConstantInterfaceMethodref extends ConstantCP {
  /**
	 *
	 */
	private static final long serialVersionUID = -8018348729623521795L;

/**
   * Initialize from another object.
   */
  public ConstantInterfaceMethodref(ConstantInterfaceMethodref c) {
    super(Constants.CONSTANT_InterfaceMethodref, c.getClassIndex(), c.getNameAndTypeIndex());
  }

  /**
   * Initialize instance from file data.
   *
   * @param file input stream
   * @throws IOException
   */
  ConstantInterfaceMethodref(DataInputStream file) throws IOException
  {
    super(Constants.CONSTANT_InterfaceMethodref, file);
  }

  /**
   * @param class_index Reference to the class containing the method
   * @param name_and_type_index and the method signature
   */
  public ConstantInterfaceMethodref(int class_index,
				    int name_and_type_index) {
    super(Constants.CONSTANT_InterfaceMethodref, class_index, name_and_type_index);
  }

  /**
   * Called by objects that are traversing the nodes of the tree implicitely
   * defined by the contents of a Java class. I.e., the hierarchy of methods,
   * fields, attributes, etc. spawns a tree of objects.
   *
   * @param v Visitor object
   */
  public void accept(Visitor v) {
    v.visitConstantInterfaceMethodref(this);
  }
}


text:
package ca.pgx.common.db.connection

import net.liftweb.common._
import net.liftweb.mongodb._
import net.liftweb.util.Props
import com.mongodb.ServerAddress
import com.mongodb.MongoException
import com.mongodb.WriteConcern
import net.liftweb.http.Factory
import com.mongodb.MongoClient

/**
 * Defines default MongoDB connection for Record based entity classes and Rogue DSL.
 * All DB classes that don't override 'mongoIdentifier' will use this connection.
 */
object MongoConfig extends Factory with Loggable {

  val defaultHostname = Props.get("mongo.host", "127.0.0.1")
  val defaultPort = Props.getInt("mongo.port", 27017)
  val defaultDbName = Props.get("mongo.dbname", "eventhub")

  /**
   * Defines default Mongo connection provider based on provided settings and falls back to Props defaults.
   * Call this method multiple times if default connection needs to be redefined.
   * This is a first method to call before ANY DB operations.
   */
  def init(hostname: String = defaultHostname, port: Int = defaultPort, dbName: String = defaultDbName) {
    val dbConnection = getConnection(hostname, port)
    MongoDB.defineDb(DefaultMongoIdentifier, dbConnection, dbName)
  }

  def getConnection(hostname: String = defaultHostname, port: Int = defaultPort): MongoClient = {
    val server = new ServerAddress(hostname, port)
    val dbConnection = new MongoClient(server)
    dbConnection setWriteConcern(WriteConcern.ACKNOWLEDGED)
    dbConnection
  }

  /**
   * Checks if there is connectivity to MongoDB server by
   * checking default DB connection and calling getLastError.
   */
  def isConnected = {
    val db = MongoDB.getDb(identifier.vend)
    if (db.isEmpty)
      false
    else
      try {
        db.get.getCollectionNames()
        true
      } catch {
        case t: MongoException => false
      }
  }

  //  def getDb = {
  //    MongoDB.getDb(DefaultMongoIdentifier)
  //  }

  val identifier = new FactoryMaker[MongoIdentifier](DefaultMongoIdentifier) {}

}


text:
package org.killbill.billing.payment.core;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.killbill.billing.util.config.PaymentConfig;
import org.killbill.commons.concurrent.Executors;
import org.killbill.commons.concurrent.WithProfilingThreadPoolExecutor;

public class PaymentExecutors {

    private static final long TIMEOUT_EXECUTOR_SEC = 3L;

    private static final int DEFAULT_MIN_PLUGIN_THREADS = 5;

    private static final String PLUGIN_THREAD_PREFIX = "Plugin-th-";
    private static final String PAYMENT_PLUGIN_TH_GROUP_NAME = "pay-plugin-grp";

    public static final String JANITOR_EXECUTOR_NAMED = "JanitorExecutor";
    public static final String PLUGIN_EXECUTOR_NAMED = "PluginExecutor";

    private final PaymentConfig paymentConfig;

    private volatile ExecutorService pluginExecutorService;
    private volatile ScheduledExecutorService janitorExecutorService;

    @Inject
    public PaymentExecutors(PaymentConfig paymentConfig) {
        this.paymentConfig = paymentConfig;

    }

    public void initialize() {
        this.pluginExecutorService = createPluginExecutorService();
        this.janitorExecutorService = createJanitorExecutorService();
    }

    public void stop() throws InterruptedException {
        pluginExecutorService.shutdownNow();
        janitorExecutorService.shutdownNow();

        pluginExecutorService.awaitTermination(TIMEOUT_EXECUTOR_SEC, TimeUnit.SECONDS);
        pluginExecutorService = null;

        janitorExecutorService.awaitTermination(TIMEOUT_EXECUTOR_SEC, TimeUnit.SECONDS);
        janitorExecutorService = null;
    }

    public ExecutorService getPluginExecutorService() {
        return pluginExecutorService;
    }

    public ScheduledExecutorService getJanitorExecutorService() {
        return janitorExecutorService;
    }

    private ExecutorService createPluginExecutorService() {
        final int minThreadNb = DEFAULT_MIN_PLUGIN_THREADS < paymentConfig.getPaymentPluginThreadNb() ? DEFAULT_MIN_PLUGIN_THREADS : paymentConfig.getPaymentPluginThreadNb();
        return new WithProfilingThreadPoolExecutor(minThreadNb,
                                                   paymentConfig.getPaymentPluginThreadNb(),
                                                   10,
                                                   TimeUnit.MINUTES,
                                                   new LinkedBlockingQueue<Runnable>(),
                                                   new ThreadFactory() {

                                                       @Override
                                                       public Thread newThread(final Runnable r) {
                                                           final Thread th = new Thread(new ThreadGroup(PAYMENT_PLUGIN_TH_GROUP_NAME), r);
                                                           th.setName(PLUGIN_THREAD_PREFIX + th.getId());
                                                           return th;
                                                       }
                                                   });

    }

    private ScheduledExecutorService createJanitorExecutorService() {
        return Executors.newSingleThreadScheduledExecutor("PaymentJanitor");
    }
}


text:
<?xml version="1.0" ?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements.  See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
 The ASF licenses this file to You under the Apache License, Version 2.0
 (the "License"); you may not use this file except in compliance with
 the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<!-- Test schema file for phrase suggestions -->

<schema name="test" version="1.0">
  <fieldType name="string" class="solr.StrField" omitNorms="true" positionIncrementGap="0"/>

  <!-- basic text field -->
  <fieldType name="text" class="solr.TextField">
    <analyzer>
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
  </fieldType>

  <fieldType name="phrase_suggest" class="solr.TextField">
    <analyzer>
      <tokenizer class="solr.KeywordTokenizerFactory"/>
      <filter class="solr.PatternReplaceFilterFactory"
              pattern="([^\p{L}\p{M}\p{N}\p{Cs}]*[\p{L}\p{M}\p{N}\p{Cs}\_]+:)|([^\p{L}\p{M}\p{N}\p{Cs}])+"
              replacement=" " replace="all"/>
      <filter class="solr.LowerCaseFilterFactory"/>
      <filter class="solr.TrimFilterFactory"/>
    </analyzer>
  </fieldType>

  <fieldType name="ja_suggest" class="solr.TextField">
    <analyzer>
      <tokenizer class="solr.JapaneseTokenizerFactory" mode="normal"/>
      <filter class="solr.CJKWidthFilterFactory"/>
      <filter class="solr.JapaneseReadingFormFilterFactory" useRomaji="true"/>
    </analyzer>
  </fieldType>

  <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="false"/>
  <field name="text" type="text" indexed="true" stored="false"/>
  <field name="stext" type="text" indexed="true" stored="true"/>

  <uniqueKey>id</uniqueKey>
</schema>


text:
ZEROMQ_VER=3.2.2

sudo apt-get -y install gcc g++
wget http://download.zeromq.org/zeromq-${ZEROMQ_VER}.tar.gz
tar xzvf zeromq-${ZEROMQ_VER}.tar.gz
cd zeromq-${ZEROMQ_VER}
./configure
make
sudo make install
sudo ldconfig


text:
package com.microsoft.azure.batch.protocol.models;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * How the Batch service should respond if a task exits with a particular exit
 * code.
 */
public class ExitCodeMapping {
    /**
     * A process exit code.
     */
    @JsonProperty(required = true)
    private int code;

    /**
     * How the Batch service should respond if the task exits with this exit
     * code.
     */
    @JsonProperty(required = true)
    private ExitOptions exitOptions;

    /**
     * Get the code value.
     *
     * @return the code value
     */
    public int code() {
        return this.code;
    }

    /**
     * Set the code value.
     *
     * @param code the code value to set
     * @return the ExitCodeMapping object itself.
     */
    public ExitCodeMapping withCode(int code) {
        this.code = code;
        return this;
    }

    /**
     * Get the exitOptions value.
     *
     * @return the exitOptions value
     */
    public ExitOptions exitOptions() {
        return this.exitOptions;
    }

    /**
     * Set the exitOptions value.
     *
     * @param exitOptions the exitOptions value to set
     * @return the ExitCodeMapping object itself.
     */
    public ExitCodeMapping withExitOptions(ExitOptions exitOptions) {
        this.exitOptions = exitOptions;
        return this;
    }

}


text:
/**
 * ezti - Easy Titanium
 * Developed by Ricardo Alcocer - ralcocer@appcelerator.com
 *
 * This module is a wrapper around Alloy.
 * It is designed to provide an abstraction layer for graphic artists, web developers and
 * light JavaScript coders, making it easier for them to work with Titanium and Alloy
 *
 */
var Alloy = require('alloy');

// open a window
exports.openWin=function(win){
	var w=Alloy.createController(win).getView();
	w.open();
}

// close a window
exports.closeWin=function(win){
	win.close();
}

// show alert box
exports.alert=function(title,message){
	Titanium.UI.createAlertDialog({
		title : title,
		message : message,
		buttonNames : ['OK']
	}).show();
}

// gets a view from disk and adds it to the specified parent
exports.addView=function(parent,view){
	//Ti.API.info(JSON.stringify(parent.children));
	var v=Alloy.createController(view).getView();
	parent.add(v);
}

// removes the view from it's parent
exports.removeView=function(parent,view){
	parent.remove(view);
}

// hides an object..does not removes it, so careful
exports.hideMe=function(whoami){
	whoami.visible="false"
}

// opens window from table row
// assumes that the row has a "eztiwin" property holding the name of the controller's XML file
exports.openWinFromRow=function(row){
	this.openWin(row.eztiwin);
}


text:
<?php

namespace PDepend\Source\AST;

use PDepend\Source\Builder\BuilderContext;
use PDepend\Source\Tokenizer\Token;
use PDepend\Util\Cache\Driver\MemoryCacheDriver;

/**
 * Test case for the code interface class.
 *
 * @copyright 2008-2013 Manuel Pichler. All rights reserved.
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @covers \PDepend\Source\AST\AbstractASTClassOrInterface
 * @covers \PDepend\Source\AST\AbstractASTType
 * @covers \PDepend\Source\AST\ASTInterface
 * @covers \PDepend\Source\Language\PHP\AbstractPHPParser
 * @group unittest
 */
class ASTInterfaceTest extends AbstractASTArtifactTest
{
    /**
     * Tests the behavior of {@link \PDepend\Source\AST\ASTMethod::getFirstChildOfType()}.
     *
     * @return void
     */
    public function testGetFirstChildOfTypeReturnsTheExpectedFirstMatch()
    {
        $node1 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node1->expects($this->once())
            ->method('getFirstChildOfType')
            ->will($this->returnValue(null));

        $node2 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node2->expects($this->never())
            ->method('getFirstChildOfType')
            ->will($this->returnValue(null));

        $interface = $this->createItem();
        $interface->addChild($node1);
        $interface->addChild($node2);

        $child = $interface->getFirstChildOfType(get_class($node2));
        $this->assertSame($node2, $child);
    }

    /**
     * Tests the behavior of {@link \PDepend\Source\AST\ASTMethod::getFirstChildOfType()}.
     *
     * @return void
     */
    public function testGetFirstChildOfTypeReturnsTheExpectedNestedMatch()
    {
        $node1 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node1->expects($this->never())
            ->method('getFirstChildOfType');

        $node2 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node2->expects($this->once())
            ->method('getFirstChildOfType')
            ->will($this->returnValue(null));

        $node3 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node3->expects($this->once())
            ->method('getFirstChildOfType')
            ->will($this->returnValue($node1));

        $interface = $this->createItem();
        $interface->addChild($node2);
        $interface->addChild($node3);

        $child = $interface->getFirstChildOfType(get_class($node1));
        $this->assertSame($node1, $child);
    }

    /**
     * Tests the behavior of {@link \PDepend\Source\AST\ASTMethod::getFirstChildOfType()}.
     *
     * @return void
     */
    public function testGetFirstChildOfTypeReturnsTheExpectedNull()
    {
        $node1 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node1->expects($this->once())
            ->method('getFirstChildOfType')
            ->will($this->returnValue(null));

        $node2 = $this->getMock(
            ASTNode::CLAZZ,
            array(),
            array(),
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $node2->expects($this->once())
            ->method('getFirstChildOfType')
            ->will($this->returnValue(null));

        $interface = $this->createItem();
        $interface->addChild($node1);
        $interface->addChild($node2);

        $child = $interface->getFirstChildOfType(
            'Mock_' . __FUNCTION__ . '_' . md5(microtime())
        );
        $this->assertNull($child);
    }

    /**
     * Tests the result of the getInterfaces() method.
     *
     * @return void
     */
    public function testGetInterfacesZeroInheritance()
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();

        $interface = $package->getInterfaces()
            ->current();

        $this->assertSame(0, $interface->getInterfaces()->count());
    }

    /**
     * Tests the result of the getInterfaces() method.
     *
     * @return void
     */
    public function testGetInterfacesOneLevelInheritance()
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();

        $interface = $package->getInterfaces()
            ->current();

        $this->assertSame(1, $interface->getInterfaces()->count());
    }

    /**
     * Tests the result of the getInterfaces() method.
     *
     * @return void
     */
    public function testGetInterfacesTwoLevelInheritance()
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();

        $interface = $package->getInterfaces()
            ->current();

        $this->assertSame(4, $interface->getInterfaces()->count());
    }

    /**
     * Tests the result of the getInterfaces() method.
     *
     * @return void
     */
    public function testGetInterfacesComplexInheritance()
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();

        $interface = $package->getInterfaces()
            ->current();

        $this->assertSame(5, $interface->getInterfaces()->count());
    }

    /**
     * Tests that {@link \PDepend\Source\AST\ASTInterface::isSubtypeOf()}
     * returns false for an input class.
     *
     * @return void
     */
    public function testIsSubtypeOfReturnsFalseForNonParents()
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();

        $interfaces = $package->getInterfaces();
        $interface  = $interfaces->current();

        $interfaces->next();
        $this->assertFalse($interface->isSubtypeOf($interfaces->current()));
    }

    /**
     * Checks the {@link \PDepend\Source\AST\ASTInterface::isSubtypeOf()}
     * method.
     *
     * @return void
     */
    public function testIsSubtypeOnInheritanceHierarchy()
    {
        $this->_testIsSubtypeOnInheritanceHierarchy(
            array(
                'A' => true,
                'B' => false,
                'C' => false,
                'D' => false,
                'E' => false,
                'F' => true
            )
        );
    }

    /**
     * Checks the {@link \PDepend\Source\AST\ASTInterface::isSubtypeOf()} method.
     *
     * @return void
     */
    public function testIsSubtypeOnInheritanceHierarchy1()
    {
        $this->_testIsSubtypeOnInheritanceHierarchy(
            array(
                'A' => true,
                'B' => true,
                'C' => true,
                'D' => true,
                'E' => true,
                'F' => true
            )
        );
    }

    /**
     * Checks the {@link \PDepend\Source\AST\ASTInterface::isSubtypeOf()} method.
     *
     * @return void
     */
    public function testIsSubtypeOnInheritanceHierarchy2()
    {
        $this->_testIsSubtypeOnInheritanceHierarchy(
            array(
                'B' => false,
                'C' => false,
                'A' => true,
                'D' => true,
                'E' => true,
                'F' => false
            )
        );
    }

    /**
     * Checks the {@link \PDepend\Source\AST\ASTInterface::isSubtypeOf()} method.
     *
     * @return void
     */
    public function testIsSubtypeOnInheritanceHierarchy3()
    {
        $this->_testIsSubtypeOnInheritanceHierarchy(
            array(
                'B' => false,
                'C' => false,
                'D' => false,
                'A' => true,
                'E' => false,
                'F' => false
            )
        );
    }

    /**
     * _testIsSubtypeOnInheritanceHierarchy
     *
     * @param array(string=>boolean) $expected Expected result.
     *
     * @return void
     */
    private function _testIsSubtypeOnInheritanceHierarchy(array $expected)
    {
        $packages = self::parseCodeResourceForTest();
        $package  = $packages->current();
        $current  = $package->getInterfaces()->current();

        $actual = array();
        foreach ($package->getInterfaces() as $interface) {
            $actual[$interface->getName()] = $current->isSubtypeOf($interface);
        }

        ksort($expected);
        ksort($actual);

        $this->assertEquals($expected, $actual);
    }

    /**
     * testGetFirstChildOfTypeFindsASTNodeInMethodDeclaration
     *
     * @return void
     */
    public function testGetFirstChildOfTypeFindsASTNodeInMethodDeclaration()
    {
        $packages = self::parseCodeResourceForTest();

        $class = $packages->current()
            ->getInterfaces()
            ->current();

        $this->assertInstanceOf(
            \PDepend\Source\AST\ASTFormalParameter::CLAZZ,
            $class->getFirstChildOfType(\PDepend\Source\AST\ASTFormalParameter::CLAZZ)
        );
    }

    /**
     * testGetFirstChildOfTypeFindsASTNodeInMethodDeclaration
     *
     * @return void
     */
    public function testFindChildrenOfTypeFindsASTNodeInMethodDeclarations()
    {
        $class = self::parseCodeResourceForTest()
            ->current()
            ->getInterfaces()
            ->current();

        $parameters = $class->findChildrenOfType(
            \PDepend\Source\AST\ASTFormalParameter::CLAZZ
        );
        $this->assertEquals(4, count($parameters));
    }

    /**
     * Tests that the interface implementation overwrites the
     * setParentClassReference() method and throws an exception.
     *
     * @return void
     * @expectedException BadMethodCallException
     */
    public function testInterfaceThrowsExpectedExceptionOnSetParentClassReference()
    {
        $interface = $this->createItem();
        $interface->setParentClassReference(
            $this->getMock(
                '\\PDepend\\Source\\AST\\ASTClassReference',
                array(),
                array(),
                '',
                false
            )
        );
    }

    /**
     * Tests the returned modifiers of an interface.
     *
     * @return void
     */
    public function testInterfaceReturnsExpectedModifiers()
    {
        $interface = $this->createItem();
        $this->assertSame(
            State::IS_IMPLICIT_ABSTRACT,
            $interface->getModifiers()
        );
    }

    /**
     * testUnserializedInterfaceStillIsParentOfChildMethods
     *
     * @return void
     */
    public function testUnserializedInterfaceStillIsParentOfChildMethods()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertSame($copy, $copy->getMethods()->current()->getParent());
    }

    /**
     * testUnserializedInterfaceAndChildMethodsStillReferenceTheSameFile
     *
     * @return void
     */
    public function testUnserializedInterfaceAndChildMethodsStillReferenceTheSameFile()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertSame(
            $copy->getCompilationUnit(),
            $copy->getMethods()->current()->getCompilationUnit()
        );
    }

    /**
     * testUnserializedInterfaceStillReferencesSameParentInterface
     *
     * @return void
     */
    public function testUnserializedInterfaceStillReferencesSameParentInterface()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertSame(
            $orig->getInterfaces()->current(),
            $copy->getInterfaces()->current()
        );
    }

    /**
     * testUnserializedInterfaceIsReturnedByMethodAsReturnClass
     *
     * @return void
     */
    public function testUnserializedInterfaceIsReturnedByMethodAsReturnClass()
    {
        $orig   = $this->getFirstInterfaceForTestCase();
        $method = $orig->getMethods()->current();

        $copy = unserialize(serialize($orig));

        $this->assertSame(
            $method->getReturnClass(),
            $copy
        );
    }

    /**
     * testUnserializedInterfaceStillReferencesSamePackage
     *
     * @return void
     */
    public function testUnserializedInterfaceStillReferencesSamePackage()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertSame(
            $orig->getPackage(),
            $copy->getPackage()
        );
    }

    /**
     * testUnserializedInterfaceRegistersToPackage
     *
     * @return void
     */
    public function testUnserializedInterfaceRegistersToPackage()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertSame($copy, $orig->getPackage()->getInterfaces()->current());
    }

    /**
     * testUnserializedInterfaceNotAddsDublicateClassToPackage
     *
     * @return void
     */
    public function testUnserializedInterfaceNotAddsDublicateClassToPackage()
    {
        $orig = $this->getFirstInterfaceForTestCase();
        $copy = unserialize(serialize($orig));

        $this->assertEquals(1, $orig->getPackage()->getInterfaces()->count());
    }

    /**
     * testGetTokensDelegatesCallToCacheRestore
     *
     * @return void
     */
    public function testGetTokensDelegatesCallToCacheRestore()
    {
        $cache = $this->createCacheFixture();
        $cache->expects($this->once())
            ->method('type')
            ->with(self::equalTo('tokens'))
            ->will($this->returnValue($cache));
        $cache->expects($this->once())
            ->method('restore');

        $interface = $this->createItem();
        $interface->setCache($cache)
            ->getTokens();
    }

    /**
     * testSetTokensDelegatesCallToCacheStore
     *
     * @return void
     */
    public function testSetTokensDelegatesCallToCacheStore()
    {
        $tokens = array(new Token(1, 'a', 23, 42, 13, 17));

        $cache = $this->createCacheFixture();
        $cache->expects($this->once())
            ->method('type')
            ->with(self::equalTo('tokens'))
            ->will($this->returnValue($cache));
        $cache->expects($this->once())
            ->method('store')
            ->with(self::equalTo(null), self::equalTo($tokens));

        $interface = $this->createItem();
        $interface->setCache($cache)
            ->setTokens($tokens);
    }

    /**
     * testGetStartLineReturnsZeroByDefault
     *
     * @return void
     */
    public function testGetStartLineReturnsZeroByDefault()
    {
        $interface = $this->createItem();
        $this->assertSame(0, $interface->getStartLine());
    }

    /**
     * testGetStartLineReturnsStartLineOfFirstToken
     *
     * @return void
     */
    public function testGetStartLineReturnsStartLineOfFirstToken()
    {
        $cache = $this->createCacheFixture();
        $cache->expects($this->once())
            ->method('type')
            ->will($this->returnValue($cache));

        $interface = $this->createItem();
        $interface->setCache($cache)
            ->setTokens(
                array(
                    new Token(1, 'a', 23, 42, 0, 0),
                    new Token(2, 'b', 17, 32, 0, 0),
                )
            );

        $this->assertEquals(23, $interface->getStartLine());
    }

    /**
     * testGetEndLineReturnsZeroByDefault
     *
     * @return void
     */
    public function testGetEndLineReturnsZeroByDefault()
    {
        $interface = $this->createItem();
        $this->assertSame(0, $interface->getEndLine());
    }

    /**
     * testGetParentClassReferenceReturnsNullByDefault
     *
     * @return void
     */
    public function testGetParentClassReferenceReturnsNullByDefault()
    {
        $class = $this->createItem();
        $this->assertNull($class->getParentClassReference());
    }

    /**
     * testGetParentClassesReturnsEmptyArrayByDefault
     *
     * @return void
     */
    public function testGetParentClassesReturnsEmptyArrayByDefault()
    {
        $interface = $this->createItem();
        $this->assertSame(array(), $interface->getParentClasses());
    }

    /**
     * testGetParentClassesReturnsEmptyArray
     *
     * @return void
     */
    public function testGetParentClassesReturnsEmptyArray()
    {
        $interface = $this->parseCodeResourceForTest()
            ->current()
            ->getInterfaces()
            ->current();

        $this->assertSame(array(), $interface->getParentClasses());
    }

    /**
     * testGetInterfaceReferencesReturnsEmptyArrayByDefault
     *
     * @return void
     */
    public function testGetInterfaceReferencesReturnsEmptyArrayByDefault()
    {
        $interface = $this->createItem();
        $this->assertSame(array(), $interface->getInterfaceReferences());
    }

    /**
     * testGetInterfaceReferencesReturnsExpectedNumberOfInterfaces
     *
     * @return void
     */
    public function testGetInterfaceReferencesReturnsExpectedNumberOfInterfaces()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertEquals(3, count($interface->getInterfaceReferences()));
    }

    /**
     * testGetAllChildrenReturnsAnEmptyArrayByDefault
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetAllChildrenReturnsAnEmptyArrayByDefault()
    {
        $interface = $this->createItem();
        $this->assertSame(array(), $interface->getChildren());
    }

    /**
     * testGetAllChildrenReturnsArrayWithExpectedNumberOfNodes
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetAllChildrenReturnsArrayWithExpectedNumberOfNodes()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertSame(2, count($interface->getChildren()));
    }

    /**
     * testGetDependenciesReturnsEmptyResultByDefault
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetDependenciesReturnsEmptyResultByDefault()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertEquals(0, count($interface->getDependencies()));
    }

    /**
     * testGetDependenciesContainsExtendedInterface
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetDependenciesContainsExtendedInterface()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertEquals(1, count($interface->getDependencies()));
    }

    /**
     * testGetDependenciesContainsExtendedInterfaces
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetDependenciesContainsExtendedInterfaces()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertEquals(3, count($interface->getDependencies()));
    }

    /**
     * testGetEndLineReturnsEndLineOfLastToken
     *
     * @return void
     */
    public function testGetEndLineReturnsEndLineOfLastToken()
    {
        $cache = $this->createCacheFixture();
        $cache->expects($this->once())
            ->method('type')
            ->will($this->returnValue($cache));

        $interface = $this->createItem();
        $interface->setCache($cache)
            ->setTokens(
                array(
                    new Token(1, 'a', 23, 42, 0, 0),
                    new Token(2, 'b', 17, 32, 0, 0),
                )
            );

        $this->assertEquals(32, $interface->getEndLine());
    }

    /**
     * testIsAbstractReturnsAlwaysTrue
     *
     * @return void
     */
    public function testIsAbstractReturnsAlwaysTrue()
    {
        $interface = $this->createItem();
        $this->assertTrue($interface->isAbstract());
    }

    /**
     * testIsUserDefinedReturnsFalseByDefault
     *
     * @return void
     */
    public function testIsUserDefinedReturnsFalseByDefault()
    {
        $interface = $this->createItem();
        $this->assertFalse($interface->isUserDefined());
    }

    /**
     * testIsUserDefinedReturnsTrueAfterSetUserDefinedCall
     *
     * @return void
     */
    public function testIsUserDefinedReturnsTrueAfterSetUserDefinedCall()
    {
        $interface = $this->createItem();
        $interface->setUserDefined();

        $this->assertTrue($interface->isUserDefined());
    }

    /**
     * testGetConstantsReturnsExpectedInterfaceConstants
     *
     * @return void
     * @since 1.0.0
     */
    public function testGetConstantsReturnsExpectedInterfaceConstants()
    {
        $interface = $this->getFirstInterfaceForTestCase();
        $this->assertEquals(array('FOO' => 42, 'BAR' => 23), $interface->getConstants());
    }

    /**
     * testIsCachedReturnsFalseByDefault
     *
     * @return void
     */
    public function testIsCachedReturnsFalseByDefault()
    {
        $interface = $this->createItem();
        $this->assertFalse($interface->isCached());
    }

    /**
     * testIsCachedReturnsFalseWhenObjectGetsSerialized
     *
     * @return void
     */
    public function testIsCachedReturnsFalseWhenObjectGetsSerialized()
    {
        $interface = $this->createItem();
        serialize($interface);

        $this->assertFalse($interface->isCached());
    }

    /**
     * testMagicSleepMethodReturnsExpectedSetOfPropertyNames
     *
     * @return void
     */
    public function testMagicSleepMethodReturnsExpectedSetOfPropertyNames()
    {
        $interface = $this->createItem();
        $interface->setPackage(new ASTNamespace(__FUNCTION__));

        $this->assertEquals(
            array(
                'constants',
                'interfaceReferences',
                'parentClassReference',
                'cache',
                'context',
                'docComment',
                'endLine',
                'modifiers',
                'name',
                'nodes',
                'packageName',
                'startLine',
                'userDefined',
                'uuid'
            ),
            $interface->__sleep()
        );
    }

    /**
     * testMagicWakeupSetsSourceFileOnChildMethods
     *
     * @return void
     */
    public function testMagicWakeupSetsSourceFileOnChildMethods()
    {
        $interface = $this->createItem();
        $method    = new ASTMethod(__FUNCTION__);
        $interface->addMethod($method);

        $interface->__wakeup();

        $this->assertSame($interface->getCompilationUnit(), $method->getCompilationUnit());
    }

    /**
     * testMagicWakeupCallsRegisterInterfaceOnBuilderContext
     *
     * @return void
     */
    public function testMagicWakeupCallsRegisterInterfaceOnBuilderContext()
    {
        $interface = $this->createItem();

        $context = $this->getMock(BuilderContext::CLAZZ);
        $context->expects($this->once())
            ->method('registerInterface')
            ->with(self::isInstanceOf(ASTInterface::CLAZZ));

        $interface->setContext($context)->__wakeup();
    }

    /**
     * testAcceptInvokesVisitInterfaceOnGivenVisitor
     *
     * @return void
     */
    public function testAcceptInvokesVisitInterfaceOnGivenVisitor()
    {
        $visitor = $this->getMock('\\PDepend\\Source\\ASTVisitor\\ASTVisitor');
        $visitor->expects($this->once())
            ->method('visitInterface')
            ->with(self::isInstanceOf(ASTInterface::CLAZZ));

        $interface = $this->createItem();
        $interface->accept($visitor);
    }

    /**
     * Creates an abstract item instance.
     *
     * @return \PDepend\Source\AST\ASTInterface
     */
    protected function createItem()
    {
        $interface = new ASTInterface(__CLASS__);
        $interface->setCompilationUnit(new ASTCompilationUnit(__FILE__));
        $interface->setCache(new MemoryCacheDriver());
        $interface->setContext($this->getMock(BuilderContext::CLAZZ));

        return $interface;
    }
}


text:
class SnipetCategory < ActiveRecord::Base
  has_many :snippet_categorizations , :dependent => :destroy
  has_many :snippets, :through => :snippet_categorizations
end


text:
> 对使用bootstrap的alert提醒框用腻的同学可以使用 toastr,很轻量,[地址](https://github.com/RryLee/laravel-reminder)

# laravel-reminder

Inspired by [laracasts flash](https://github.com/laracasts/flash)

### Install

Using Composer

    composer require rry/reminder

Add the service provider to `config/app.php`

    Rry\Reminder\ReminderServiceProvider::class,

Optionally include the Facade in config/app.php if you'd like.

    'Reminder'  => Rry\Reminder\ReminderFacade::class,

> You can use reminder() function available.

### Dependencies

jQuery [toast](https://github.com/CodeSeven/toastr), you need to add css and js to your html.

### Basic

You should add `{!! Reminder::message() !!}` to your html.

Then.

    Reminder::info('foo', 'bar', []);

    Reminder::success('foo', 'bar', []);

    Reminder::warning('foo', 'bar', []);

    Reminder::error('foo', 'bar', []);

    reminder()->info('foo', 'bar', []);

---

### demo

```php
<?php

Route::get('/', function () {
    Reminder::success('Hi! this is Reminder', 'Hello', ["positionClass" => "toast-bottom-right"]);

    return view('welcome');
});
```

```html
<!DOCTYPE html>
<html>
    <head>
        <title>Laravel</title>
        <link rel="stylesheet" href="http://cdn.bootcss.com/toastr.js/latest/css/toastr.min.css">
    </head>
    <body>
        <div class="container">
            <div class="content">
                <div class="title">Laravel 5</div>
            </div>
        </div>

        <script src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
        <script src="http://cdn.bootcss.com/toastr.js/latest/js/toastr.min.js"></script>
        {!! reminder()->message() !!}
    </body>
</html>
```

<img src="http://ww3.sinaimg.cn/mw690/baa3278fgw1ey7ky56nbgj20n60fuaav.jpg" alt="" class="img-responsive">

### Options

You can set custom options for Reminder. Run:

```php
php artisan vendor:publish
```

to publish the config file for reminder.

You can see [toastr's documentation](http://codeseven.github.io/toastr/demo.html) to custom your need.

### MIT


text:
package org.apache.tez.dag.app.dag.event;

/**
 * Event types handled by TaskAttempt.
 */
public enum TaskAttemptEventType {

//Producer:Task, Speculator
  TA_SCHEDULE,

//Producer: TaskAttemptListener
  TA_STARTED_REMOTELY,
  TA_STATUS_UPDATE,
  TA_DIAGNOSTICS_UPDATE,
  TA_OUTPUT_CONSUMABLE,  // TODO History event to indicate this ?
  TA_COMMIT_PENDING,
  TA_DONE,
  TA_FAILED,
  TA_TIMED_OUT,

//Producer: Client
  TA_FAIL_REQUEST,

//Producer: Client, Scheduler, On speculation.
  TA_KILL_REQUEST,

//Producer: Container / Scheduler.
  // Container may be running and is in the process of shutting down.
  TA_CONTAINER_TERMINATING,

  // Container has shut down.
  // In reality, the RM considers the container to be complete. Container has
  // shutdown except for once case - likely when the RM decides to kill the
  // container. TODO: Document the case.
  TA_CONTAINER_TERMINATED,

  // Container has either been preempted or will be preempted
  TA_CONTAINER_PREEMPTED,

  // The node running the task attempt failed.
  TA_NODE_FAILED,

  // Producer: consumer destination vertex
  TA_OUTPUT_FAILED,

  // Recovery
  TA_RECOVER,

}


text:
class Browser;
class Profile;

namespace aura {
class Window;
}

namespace chrome {

// This is the implementation of MultiUserWindowManager for single user mode.
class MultiUserWindowManagerStub : public MultiUserWindowManager {
 public:
  MultiUserWindowManagerStub() {}
  virtual ~MultiUserWindowManagerStub() {}

  // MultiUserWindowManager overrides:
  virtual void SetWindowOwner(
      aura::Window* window, const std::string& user_id) OVERRIDE;
  virtual const std::string& GetWindowOwner(aura::Window* window) OVERRIDE;
  virtual void ShowWindowForUser(
      aura::Window* window, const std::string& user_id) OVERRIDE;
  virtual bool AreWindowsSharedAmongUsers() OVERRIDE;
  virtual bool IsWindowOnDesktopOfUser(aura::Window* window,
                                       const std::string& user_id) OVERRIDE;
  virtual const std::string& GetUserPresentingWindow(
      aura::Window* window) OVERRIDE;
  virtual void AddUser(Profile* profile) OVERRIDE;

 private:
  DISALLOW_COPY_AND_ASSIGN(MultiUserWindowManagerStub);
};

}  // namespace chrome

#endif  // CHROME_BROWSER_UI_ASH_MULTI_USER_MULTI_USER_WINDOW_MANAGER_STUB_H_


text:
/*
Tests for the API Backends v1 wrapper.
*/
// Tinytest.add(
//   "Admin API v1 - API Backends - getBackend",
//   function (test) {
//     //var response = apiUmbrellaWeb.adminApi.v1.apiUsers.getUsers();
//     //console.log(response.statusCode);
//     test.fail();
//   },
//   "Could not get all API Backends."
// );

Tinytest.add(
  "Admin API v1 - API Backends - getBackends",
  function (test) {
    var config = {
      apiKey: Meteor.settings.apiUmbrella.apiKey,
      authToken: Meteor.settings.apiUmbrella.authToken,
      baseUrl: Meteor.settings.apiUmbrella.baseUrl
    };
    var apiUmbrellaWeb = new ApiUmbrellaWeb(config);
    var response = apiUmbrellaWeb.adminApi.v1.apiBackends.getApiBackends();
    if (response.statusCode !== 200) {
      test.fail();
    }
  },
  "Could not get individual API Backend."
);


text:
<?php

namespace MamuzBlogFeedTest;

use MamuzBlogFeed\Module;

class ModuleTest extends \PHPUnit_Framework_TestCase
{
    /** @var Module */
    protected $fixture;

    protected function setUp()
    {
        $this->fixture = new Module;
    }

    public function testImplementingFeatures()
    {
        $this->assertInstanceOf('Zend\ModuleManager\Feature\BootstrapListenerInterface', $this->fixture);
        $this->assertInstanceOf('Zend\ModuleManager\Feature\ConfigProviderInterface', $this->fixture);
        $this->assertInstanceOf('Zend\ModuleManager\Feature\InitProviderInterface', $this->fixture);
    }

    public function testConfigRetrieval()
    {
        $this->assertNotEmpty($this->fixture->getConfig());
    }

    public function testLoadingModules()
    {
        $moduleManager = \Mockery::mock('Zend\ModuleManager\ModuleManagerInterface');
        $moduleManager->shouldReceive('loadModule')->with('MamuzBlog');

        $this->fixture->init($moduleManager);
    }
}


text:
using UnityEngine;
using System.Collections;

public class bricks : MonoBehaviour {

	private bool stopped;
	private float speed = 0.03F;

	public GameObject blockPrefab;

	// Use this for initialization
	public void Start () {
		//populate with bricks
		int yOff = 10;
		for (int x = -10; x <= 10; x++) {
			for(int y = 0; y < 3; y++) {
				GameObject block = Instantiate (blockPrefab, new Vector3(x, y + yOff, 0), Quaternion.identity) as GameObject;
				block.transform.parent = transform;
				Rigidbody rb = block.rigidbody;
				rb.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
			}
		}
		stopped = false;
	}

	// Update is called once per frame
	public void Update () {
		if (!stopped) {
			Vector3 pos = transform.position;
			float y = pos.y - speed;
			transform.position = new Vector3 (pos.x, y, 0);
		}
	}

	public void OnCollisionEnter(Collision c) {
		GameObject o = c.gameObject;
		Debug.Log ("IN" + o.name);
		if (o.name == "piece floor") {
			stopped = true;
		} else if (o.name == "blockPrefab(Clone)") {
			o.transform.parent = transform;
		}
	}

	public void OnCollisionExit(Collision c) {
		GameObject o = c.gameObject;
		Debug.Log ("OUT" + o.name);
		if (o.name == "piece floor") {
			stopped = false;
		}
	}
}