text:
//===------- ModuleInterfaceSupport.cpp - swiftinterface files ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/ModuleInterfaceSupport.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/Validation.h"
#include "clang/Basic/Module.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/StringSaver.h"

using namespace swift;

version::Version swift::InterfaceFormatVersion({1, 0});

/// Diagnose any scoped imports in \p imports, i.e. those with a non-empty
/// access path. These are not yet supported by module interfaces, since the
/// information about the declaration kind is not preserved through the binary
/// serialization that happens as an intermediate step in non-whole-module
/// builds.
///
/// These come from declarations like `import class FooKit.MainFooController`.
static void diagnoseScopedImports(DiagnosticEngine &diags,
                                  ArrayRef<ImportedModule> imports){
  for (const ImportedModule &importPair : imports) {
    if (importPair.accessPath.empty())
      continue;
    diags.diagnose(importPair.accessPath.front().Loc,
                   diag::module_interface_scoped_import_unsupported);
  }
}

/// Prints to \p out a comment containing a format version number, tool version
/// string as well as any relevant command-line flags in \p Opts used to
/// construct \p M.
static void printToolVersionAndFlagsComment(raw_ostream &out,
                                            ModuleInterfaceOptions const &Opts,
                                            ModuleDecl *M) {
  auto &Ctx = M->getASTContext();
  auto ToolsVersion =
      getSwiftInterfaceCompilerVersionForCurrentCompiler(Ctx);
  out << "// " SWIFT_INTERFACE_FORMAT_VERSION_KEY ": "
      << InterfaceFormatVersion << "\n";
  out << "// " SWIFT_COMPILER_VERSION_KEY ": "
      << ToolsVersion << "\n";
  out << "// " SWIFT_MODULE_FLAGS_KEY ": "
      << Opts.Flags << "\n";
}

std::string
swift::getSwiftInterfaceCompilerVersionForCurrentCompiler(ASTContext &ctx) {
  return swift::version::getSwiftFullVersion(
             ctx.LangOpts.EffectiveLanguageVersion);
}

llvm::Regex swift::getSwiftInterfaceFormatVersionRegex() {
  return llvm::Regex("^// " SWIFT_INTERFACE_FORMAT_VERSION_KEY
                     ": ([0-9\\.]+)$", llvm::Regex::Newline);
}

llvm::Regex swift::getSwiftInterfaceModuleFlagsRegex() {
  return llvm::Regex("^// " SWIFT_MODULE_FLAGS_KEY ":(.*)$",
                     llvm::Regex::Newline);
}

llvm::Regex swift::getSwiftInterfaceCompilerVersionRegex() {
  return llvm::Regex("^// " SWIFT_COMPILER_VERSION_KEY
                     ": (.+)$", llvm::Regex::Newline);
}

/// Prints the imported modules in \p M to \p out in the form of \c import
/// source declarations.
static void printImports(raw_ostream &out,
                         ModuleInterfaceOptions const &Opts,
                         ModuleDecl *M) {
  // FIXME: This is very similar to what's in Serializer::writeInputBlock, but
  // it's not obvious what higher-level optimization would be factored out here.
  ModuleDecl::ImportFilter allImportFilter = {
      ModuleDecl::ImportFilterKind::Exported,
      ModuleDecl::ImportFilterKind::Default,
      ModuleDecl::ImportFilterKind::SPIAccessControl};

  // With -experimental-spi-imports:
  // When printing the private swiftinterface file, print implementation-only
  // imports only if they are also SPI. First, list all implementation-only
  // imports and filter them later.
  llvm::SmallSet<ImportedModule, 4, ImportedModule::Order> ioiImportSet;
  if (Opts.PrintSPIs && Opts.ExperimentalSPIImports) {
    allImportFilter |= ModuleDecl::ImportFilterKind::ImplementationOnly;

    SmallVector<ImportedModule, 4> ioiImport;
    M->getImportedModules(ioiImport,
                          ModuleDecl::ImportFilterKind::ImplementationOnly);
    ioiImportSet.insert(ioiImport.begin(), ioiImport.end());
  }

  SmallVector<ImportedModule, 8> allImports;
  M->getImportedModules(allImports, allImportFilter);
  ImportedModule::removeDuplicates(allImports);
  diagnoseScopedImports(M->getASTContext().Diags, allImports);

  // Collect the public imports as a subset so that we can mark them with
  // '@_exported'.
  SmallVector<ImportedModule, 8> publicImports;
  M->getImportedModules(publicImports, ModuleDecl::ImportFilterKind::Exported);
  llvm::SmallSet<ImportedModule, 8, ImportedModule::Order> publicImportSet;

  publicImportSet.insert(publicImports.begin(), publicImports.end());

  for (auto import : allImports) {
    auto importedModule = import.importedModule;
    if (importedModule->isOnoneSupportModule() ||
        importedModule->isBuiltinModule()) {
      continue;
    }

    llvm::SmallSetVector<Identifier, 4> spis;
    M->lookupImportedSPIGroups(importedModule, spis);

    // Only print implementation-only imports which have an SPI import.
    if (ioiImportSet.count(import)) {
      if (spis.empty())
        continue;
      out << "@_implementationOnly ";
    }

    if (publicImportSet.count(import))
      out << "@_exported ";

    // SPI attribute on imports
    if (Opts.PrintSPIs) {
      for (auto spiName : spis)
        out << "@_spi(" << spiName << ") ";
    }

    out << "import ";
    importedModule->getReverseFullModuleName().printForward(out);

    // Write the access path we should be honoring but aren't.
    // (See diagnoseScopedImports above.)
    if (!import.accessPath.empty()) {
      out << "/*";
      for (const auto &accessPathElem : import.accessPath)
        out << "." << accessPathElem.Item;
      out << "*/";
    }

    out << "\n";
  }
}

// FIXME: Copied from ASTPrinter.cpp...
static bool isPublicOrUsableFromInline(const ValueDecl *VD) {
  AccessScope scope =
      VD->getFormalAccessScope(/*useDC*/nullptr,
                               /*treatUsableFromInlineAsPublic*/true);
  return scope.isPublic();
}

static bool isPublicOrUsableFromInline(Type ty) {
  // Note the double negative here: we're looking for any referenced decls that
  // are *not* public-or-usableFromInline.
  return !ty.findIf([](Type typePart) -> bool {
    // FIXME: If we have an internal typealias for a non-internal type, we ought
    // to be able to print it by desugaring.
    if (auto *aliasTy = dyn_cast<TypeAliasType>(typePart.getPointer()))
      return !isPublicOrUsableFromInline(aliasTy->getDecl());
    if (auto *nominal = typePart->getAnyNominal())
      return !isPublicOrUsableFromInline(nominal);
    return false;
  });
}

namespace {
/// Collects protocols that are conformed to by a particular nominal. Since
/// ASTPrinter will only print the public ones, the non-public ones get left by
/// the wayside. This is a problem when a non-public protocol inherits from a
/// public protocol; the generated module interface still needs to make that
/// dependency public.
///
/// The solution implemented here is to generate synthetic extensions that
/// declare the extra conformances. This isn't perfect (it loses the sugared
/// spelling of the protocol type, as well as the locality in the file), but it
/// does work.
class InheritedProtocolCollector {
  static const StringLiteral DummyProtocolName;

  using AvailableAttrList = TinyPtrVector<const AvailableAttr *>;
  using ProtocolAndAvailability =
    std::pair<ProtocolDecl *, AvailableAttrList>;

  /// Protocols that will be included by the ASTPrinter without any extra work.
  SmallVector<ProtocolDecl *, 8> IncludedProtocols;
  /// Protocols that will not be printed by the ASTPrinter, along with the
  /// availability they were declared with.
  SmallVector<ProtocolAndAvailability, 8> ExtraProtocols;
  /// Protocols that can be printed, but whose conformances are constrained with
  /// something that \e can't be printed.
  SmallVector<const ProtocolType *, 8> ConditionalConformanceProtocols;

  /// Helper to extract the `@available` attributes on a decl.
  static AvailableAttrList
  getAvailabilityAttrs(const Decl *D, Optional<AvailableAttrList> &cache) {
    if (cache.hasValue())
      return cache.getValue();

    cache.emplace();
    while (D) {
      for (auto *nextAttr : D->getAttrs().getAttributes<AvailableAttr>()) {
        // FIXME: This is just approximating the effects of nested availability
        // attributes for the same platform; formally they'd need to be merged.
        bool alreadyHasMoreSpecificAttrForThisPlatform =
            llvm::any_of(*cache, [nextAttr](const AvailableAttr *existingAttr) {
          return existingAttr->Platform == nextAttr->Platform;
        });
        if (alreadyHasMoreSpecificAttrForThisPlatform)
          continue;
        cache->push_back(nextAttr);
      }
      D = D->getDeclContext()->getAsDecl();
    }

    return cache.getValue();
  }

  /// For each type in \p directlyInherited, classify the protocols it refers to
  /// as included for printing or not, and record them in the appropriate
  /// vectors.
  void recordProtocols(ArrayRef<TypeLoc> directlyInherited, const Decl *D) {
    Optional<AvailableAttrList> availableAttrs;

    for (TypeLoc inherited : directlyInherited) {
      Type inheritedTy = inherited.getType();
      if (!inheritedTy || !inheritedTy->isExistentialType())
        continue;

      bool canPrintNormally = isPublicOrUsableFromInline(inheritedTy);
      ExistentialLayout layout = inheritedTy->getExistentialLayout();
      for (ProtocolType *protoTy : layout.getProtocols()) {
        if (canPrintNormally)
          IncludedProtocols.push_back(protoTy->getDecl());
        else
          ExtraProtocols.push_back({protoTy->getDecl(),
                                    getAvailabilityAttrs(D, availableAttrs)});
      }
      // FIXME: This ignores layout constraints, but currently we don't support
      // any of those besides 'AnyObject'.
    }

    // Check for synthesized protocols, like Hashable on enums.
    if (auto *nominal = dyn_cast<NominalTypeDecl>(D)) {
      SmallVector<ProtocolConformance *, 4> localConformances =
          nominal->getLocalConformances(ConformanceLookupKind::NonInherited);

      for (auto *conf : localConformances) {
        if (conf->getSourceKind() != ConformanceEntryKind::Synthesized)
          continue;
        ExtraProtocols.push_back({conf->getProtocol(),
                                  getAvailabilityAttrs(D, availableAttrs)});
      }
    }
  }

  /// For each type directly inherited by \p extension, record any protocols
  /// that we would have printed in ConditionalConformanceProtocols.
  void recordConditionalConformances(const ExtensionDecl *extension) {
    for (TypeLoc inherited : extension->getInherited()) {
      Type inheritedTy = inherited.getType();
      if (!inheritedTy || !inheritedTy->isExistentialType())
        continue;

      ExistentialLayout layout = inheritedTy->getExistentialLayout();
      for (ProtocolType *protoTy : layout.getProtocols()) {
        if (!isPublicOrUsableFromInline(protoTy))
          continue;
        ConditionalConformanceProtocols.push_back(protoTy);
      }
      // FIXME: This ignores layout constraints, but currently we don't support
      // any of those besides 'AnyObject'.
    }
  }

public:
  using PerTypeMap = llvm::MapVector<const NominalTypeDecl *,
                                     InheritedProtocolCollector>;

  /// Given that we're about to print \p D, record its protocols in \p map.
  ///
  /// \sa recordProtocols
  static void collectProtocols(PerTypeMap &map, const Decl *D) {
    ArrayRef<TypeLoc> directlyInherited;
    const NominalTypeDecl *nominal;
    const IterableDeclContext *memberContext;

    auto shouldInclude = [](const ExtensionDecl *extension) {
      if (extension->isConstrainedExtension()) {
        // Conditional conformances never apply to inherited protocols, nor
        // can they provide unconditional conformances that might be used in
        // other extensions.
        return false;
      }
      return true;
    };
    if ((nominal = dyn_cast<NominalTypeDecl>(D))) {
      directlyInherited = nominal->getInherited();
      memberContext = nominal;

    } else if (auto *extension = dyn_cast<ExtensionDecl>(D)) {
      if (!shouldInclude(extension)) {
        return;
      }
      nominal = extension->getExtendedNominal();
      directlyInherited = extension->getInherited();
      memberContext = extension;
    } else {
      return;
    }

    if (!isPublicOrUsableFromInline(nominal))
      return;

    map[nominal].recordProtocols(directlyInherited, D);
    // Collect protocols inherited from super classes
    if (auto *CD = dyn_cast<ClassDecl>(D)) {
      for (auto *SD = CD->getSuperclassDecl(); SD;
           SD = SD->getSuperclassDecl()) {
        map[nominal].recordProtocols(SD->getInherited(), SD);
        for (auto *Ext: SD->getExtensions()) {
          if (shouldInclude(Ext)) {
            map[nominal].recordProtocols(Ext->getInherited(), Ext);
          }
        }
      }
    }

    // Recurse to find any nested types.
    for (const Decl *member : memberContext->getMembers())
      collectProtocols(map, member);
  }

  /// If \p D is an extension providing conditional conformances, record those
  /// in \p map.
  ///
  /// \sa recordConditionalConformances
  static void collectSkippedConditionalConformances(
                                            PerTypeMap &map,
                                            const Decl *D,
                                            const PrintOptions &printOptions) {
    auto *extension = dyn_cast<ExtensionDecl>(D);
    if (!extension || !extension->isConstrainedExtension())
      return;

    // Skip SPI extensions in the public interface.
    if (!printOptions.PrintSPIs && extension->isSPI())
      return;

    const NominalTypeDecl *nominal = extension->getExtendedNominal();
    if (!isPublicOrUsableFromInline(nominal))
      return;

    map[nominal].recordConditionalConformances(extension);
    // No recursion here because extensions are never nested.
  }

  /// Returns true if the conformance of \p nominal to \p proto is declared in
  /// module \p M.
  static bool conformanceDeclaredInModule(ModuleDecl *M,
                                          const NominalTypeDecl *nominal,
                                          ProtocolDecl *proto) {
    SmallVector<ProtocolConformance *, 4> conformances;
    nominal->lookupConformance(M, proto, conformances);
    return llvm::all_of(conformances,
                        [M](const ProtocolConformance *conformance) -> bool {
      return M == conformance->getDeclContext()->getParentModule();
    });
  }

  /// If there were any public protocols that need to be printed (i.e. they
  /// weren't conformed to explicitly or inherited by another printed protocol),
  /// do so now by printing a dummy extension on \p nominal to \p out.
  void
  printSynthesizedExtensionIfNeeded(raw_ostream &out,
                                    const PrintOptions &printOptions,
                                    ModuleDecl *M,
                                    const NominalTypeDecl *nominal) const {
    if (ExtraProtocols.empty())
      return;

    if (!printOptions.shouldPrint(nominal))
      return;

    SmallPtrSet<ProtocolDecl *, 16> handledProtocols;

    // First record all protocols that have already been handled.
    for (ProtocolDecl *proto : IncludedProtocols) {
      proto->walkInheritedProtocols(
          [&handledProtocols](ProtocolDecl *inherited) -> TypeWalker::Action {
        handledProtocols.insert(inherited);
        return TypeWalker::Action::Continue;
      });
    }

    // Then walk the remaining ones, and see what we need to print.
    // Note: We could do this in one pass, but the logic is easier to
    // understand if we build up the list and then print it, even if it takes
    // a bit more memory.
    // FIXME: This will pick the availability attributes from the first sight
    // of a protocol rather than the maximally available case.
    SmallVector<ProtocolAndAvailability, 16> protocolsToPrint;
    for (const auto &protoAndAvailability : ExtraProtocols) {
      protoAndAvailability.first->walkInheritedProtocols(
          [&](ProtocolDecl *inherited) -> TypeWalker::Action {
        if (!handledProtocols.insert(inherited).second)
          return TypeWalker::Action::SkipChildren;

        if (isPublicOrUsableFromInline(inherited) &&
            conformanceDeclaredInModule(M, nominal, inherited)) {
          protocolsToPrint.push_back({inherited, protoAndAvailability.second});
          return TypeWalker::Action::SkipChildren;
        }

        return TypeWalker::Action::Continue;
      });
    }
    if (protocolsToPrint.empty())
      return;

    for (const auto &protoAndAvailability : protocolsToPrint) {
      StreamPrinter printer(out);
      // FIXME: Shouldn't this be an implicit conversion?
      TinyPtrVector<const DeclAttribute *> attrs;
      attrs.insert(attrs.end(), protoAndAvailability.second.begin(),
                   protoAndAvailability.second.end());
      DeclAttributes::print(printer, printOptions, attrs);

      printer << "extension ";
      nominal->getDeclaredType().print(printer, printOptions);
      printer << " : ";

      ProtocolDecl *proto = protoAndAvailability.first;
      proto->getDeclaredInterfaceType()->print(printer, printOptions);

      printer << " {}\n";
    }
  }

  /// If there were any conditional conformances that couldn't be printed,
  /// make a dummy extension that conforms to all of them, constrained by a
  /// fake protocol.
  bool printInaccessibleConformanceExtensionIfNeeded(
      raw_ostream &out, const PrintOptions &printOptions,
      const NominalTypeDecl *nominal) const {
    if (ConditionalConformanceProtocols.empty())
      return false;
    assert(nominal->isGenericContext());

    if (printOptions.PrintSPIs)
      out << "@_spi(" << DummyProtocolName << ")\n";
    out << "@available(*, unavailable)\nextension ";
    nominal->getDeclaredType().print(out, printOptions);
    out << " : ";
    llvm::interleave(
        ConditionalConformanceProtocols,
        [&out, &printOptions](const ProtocolType *protoTy) {
          protoTy->print(out, printOptions);
        },
        [&out] { out << ", "; });
    out << " where "
        << nominal->getGenericSignature()->getGenericParams().front()->getName()
        << " : " << DummyProtocolName << " {}\n";
    return true;
  }

  /// Print a fake protocol declaration for use by
  /// #printInaccessibleConformanceExtensionIfNeeded.
  static void printDummyProtocolDeclaration(raw_ostream &out) {
    out << "\n@usableFromInline\ninternal protocol " << DummyProtocolName
        << " {}\n";
  }
};

const StringLiteral InheritedProtocolCollector::DummyProtocolName =
    "_ConstraintThatIsNotPartOfTheAPIOfThisLibrary";
} // end anonymous namespace

bool swift::emitSwiftInterface(raw_ostream &out,
                               ModuleInterfaceOptions const &Opts,
                               ModuleDecl *M) {
  assert(M);

  printToolVersionAndFlagsComment(out, Opts, M);
  printImports(out, Opts, M);

  const PrintOptions printOptions = PrintOptions::printSwiftInterfaceFile(
      M, Opts.PreserveTypesAsWritten, Opts.PrintFullConvention, Opts.PrintSPIs);
  InheritedProtocolCollector::PerTypeMap inheritedProtocolMap;

  SmallVector<Decl *, 16> topLevelDecls;
  M->getTopLevelDecls(topLevelDecls);
  for (const Decl *D : topLevelDecls) {
    InheritedProtocolCollector::collectProtocols(inheritedProtocolMap, D);

    if (!D->shouldPrintInContext(printOptions) ||
        !printOptions.shouldPrint(D)) {

      InheritedProtocolCollector::collectSkippedConditionalConformances(
          inheritedProtocolMap, D, printOptions);
      continue;
    }

    D->print(out, printOptions);
    out << "\n";
  }

  // Print dummy extensions for any protocols that were indirectly conformed to.
  bool needDummyProtocolDeclaration = false;
  for (const auto &nominalAndCollector : inheritedProtocolMap) {
    const NominalTypeDecl *nominal = nominalAndCollector.first;
    const InheritedProtocolCollector &collector = nominalAndCollector.second;
    collector.printSynthesizedExtensionIfNeeded(out, printOptions, M, nominal);
    needDummyProtocolDeclaration |=
        collector.printInaccessibleConformanceExtensionIfNeeded(out,
                                                                printOptions,
                                                                nominal);
  }
  if (needDummyProtocolDeclaration)
    InheritedProtocolCollector::printDummyProtocolDeclaration(out);

  if (Opts.DebugPrintInvalidSyntax)
    out << "#__debug_emit_invalid_swiftinterface_syntax__\n";

  return false;
}


text:
namespace SimpleContacts.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<SimpleContacts.Data.SimpleContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }

        protected override void Seed(SimpleContacts.Data.SimpleContext context)
        {
            Seeder.Seed(context);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.xpece.android.graphics.drawable;

import android.content.res.Resources;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;

/**
 * Created by Eugen on 26.11.2016.
 */

class DrawableInternal {

    /**
     * Scales a floating-point pixel value from the source density to the
     * target density.
     *
     * @param pixels the pixel value for use in source density
     * @param sourceDensity the source density
     * @param targetDensity the target density
     * @return the scaled pixel value for use in target density
     */
    public static float scaleFromDensity(float pixels, int sourceDensity, int targetDensity) {
        return pixels * targetDensity / sourceDensity;
    }

    /**
     * Scales a pixel value from the source density to the target density,
     * optionally handling the resulting pixel value as a size rather than an
     * offset.
     *

     * A size conversion involves rounding the base value and ensuring that
     * a non-zero base value is at least one pixel in size.
     *

     * An offset conversion involves simply truncating the base value to an
     * integer.
     *
     * @param pixels the pixel value for use in source density
     * @param sourceDensity the source density
     * @param targetDensity the target density
     * @param isSize {@code true} to handle the resulting scaled value as a
     *               size, or {@code false} to handle it as an offset
     * @return the scaled pixel value for use in target density
     */
    static int scaleFromDensity(
        int pixels, int sourceDensity, int targetDensity, boolean isSize) {
        if (pixels == 0 || sourceDensity == targetDensity) {
            return pixels;
        }

        final float result = pixels * targetDensity / (float) sourceDensity;
        if (!isSize) {
            return (int) result;
        }

        final int rounded = Math.round(result);
        if (rounded != 0) {
            return rounded;
        } else if (pixels > 0) {
            return 1;
        } else {
            return -1;
        }
    }

    static int resolveDensity(@Nullable Resources r, int parentDensity) {
        final int densityDpi = r == null ? parentDensity : r.getDisplayMetrics().densityDpi;
        return densityDpi == 0 ? DisplayMetrics.DENSITY_DEFAULT : densityDpi;
    }

}


text:
/**
 * Inner utilities for logging.
 * **gIn.logger**.
 */

/* globals gT: true */
/* globals gIn: true */

/*
 Inner utils for logging.
 */
let isVerbose = false;

let logFile = '';

// TODO: bad design.
let fd: number;

export function setLogFile(newLogFile: string) {
  logFile = newLogFile;
}

export function getLogFile() {
  return logFile;
}

import * as fs from 'fs';
import * as nodeUtils from '../../utils/nodejs-utils';
import { TestInfo } from '../test-info';

function logToFile(msg: string) {
  // TODO: check how diff work for unicode.
  fs.appendFileSync(logFile, msg, { encoding: gT.engineConsts.logEncoding });
}

// function logToFileLn(msg) {
//   return logToFile(`${msg}\n`);
// }

/**
 * Logs to file and writes to console (if console output is enabled).
 * @param msg
 * @param noConsole
 */
export function log(msg: string, dontWriteToFile?: boolean) {
  // We use append here, to don't lost some strings if something will break the test engine.
  gIn.cLogger.logIfEnabled(msg);
  if (!dontWriteToFile) {
    logToFile(msg);
  }
}

export function logln(msg: string) {
  log(`${msg}\n`);
}

export function logResourcesUsage(prefix = '') {
  if (gT.config.resUsagePrintAtErrors) {
    logln(prefix + nodeUtils.getResourcesUsage(true));
  }
}

export function logBold(msg: string) {
  gIn.cLogger.logBold(msg);
  logToFile(msg);
}

export function fail(msg: string) {
  gIn.cLogger.failIfEnabled(msg);
  logToFile(msg);
}

export function pass(msg: string) {
  gIn.cLogger.passIfEnabled(msg);
  logToFile(msg);
}

/**
 * Report about some error.
 * @param msg
 */
export function error(msg: string) {
  const msgNew = gIn.loggerCfg.errPrefix + msg;
  gIn.cLogger.errIfEnabled(msgNew);
  logToFile(msgNew);
}

export function errorln(msg: string) {
  return error(`${msg}\n`);
}

/**
 * Report about some exception.
 * @param msg
 * @param e
 */
export function exception(msg: string, e: Error) {
  const msgNew = gIn.loggerCfg.excPrefix + msg;
  gIn.cLogger.errIfEnabled(`${msgNew} ${gIn.textUtils.excToStr(e)}\n`);
  logToFile(`${msgNew} ${gIn.textUtils.excToStr(e, !gT.cLParams.stackToLog)}\n`);
}

/**
 * Logs a message.
 * @param msg - A message to be logged.
 * @param {Boolean}[enable]. If true log is enabled, othwerwise log is disabled.
 */
export function logIfEnabled(msg: string, enable?: boolean) {
  let dontWriteToFile = false;
  if (!enable && gT.cLParams.forceLogActions) {
    dontWriteToFile = true;
  }
  if (gT.cLParams.forceLogActions || enable) {
    log(msg, dontWriteToFile);
  }
}

/**
 * Logs a message.
 * @param msg - A message to be logged.
 * @param {Boolean} [enable = gIn.loggerCfg.defLLLogAction] - If false - log is disabled,
 * otherwise - log is enabled.
 */
export function logIfNotDisabled(msg: string, enable?: boolean) {
  if (enable === undefined) {
    enable = gIn.loggerCfg.getDefLLLogAction();
  }
  let dontWriteToFile = false;
  if (!enable && gT.cLParams.forceLogActions) {
    dontWriteToFile = true;
  }
  if (gT.cLParams.forceLogActions || enable) {
    log(msg, dontWriteToFile);
  }
}

function writeStrToFile(str: string, fd: number /* , diffed, isDif*/) {
  fs.writeSync(fd, str, null, gT.engineConsts.logEncoding);
}

function writeStrToStdout(str: string, diffed?: boolean, isDif?: boolean) {
  // str = str.replace(/\s+$/g, '');
  // str += '\n';
  if (diffed) {
    gIn.cLogger.err(str);
  } else if (isDif) {
    gIn.cLogger.msgDifStr(str);
  } else {
    gIn.cLogger.msg(str);
  }
}

function writeToSuiteLog({
  str,
  diffed,
  isDif,
  fd,
}: {
  str: string;
  diffed?: boolean;
  isDif?: boolean;
  fd?: number;
}) {
  if (typeof fd !== 'undefined') {
    return writeStrToFile(str, fd);
  }
  writeStrToStdout(str, diffed, isDif);
}

export function testSummary() {
  log('=================\n');
  log(`Pass: ${gIn.tInfo.getPassed()}, Fail: ${gIn.tInfo.getFailed()}\n`);
}

function saveDirInfoToSuiteLog({
  dirInfo,
  indent,
  verbose,
  noTime,
  noTestDifs,
  fd,
}: {
  dirInfo: TestInfo;
  indent: string;
  verbose?: boolean;
  noTime?: boolean;
  noTestDifs?: boolean;
  fd?: number;
}) {
  gIn.tracer.msg3(`${dirInfo.path}, dirInfo.run: ${dirInfo.run}`);
  if (!dirInfo.run && !gT.suiteConfig.emptyDirToSuiteLog) {
    return;
  }
  writeToSuiteLog({ str: indent, fd });
  writeToSuiteLog({
    str: gIn.tInfo.testInfoToString({
      curInfo: dirInfo,
      isDir: true,
      verbose,
      noTime,
    }),
    diffed: Boolean(dirInfo.diffed),
    fd,
  });
  indent = gIn.loggerCfg.indentation + indent;

  // If directory is empty there will be empty array.
  // Absense of 'children' property says that it is test and not directory,
  // we should not allow to use this function for not directory.
  const len = dirInfo.children!.length;
  for (let i = 0; i < len; i++) {
    const curInfo = dirInfo.children![i];
    if (curInfo.diffed || verbose) {
      if (curInfo.children) {
        saveDirInfoToSuiteLog({
          dirInfo: curInfo,
          indent,
          verbose,
          noTime,
          noTestDifs,
          fd,
        });
      } else {
        writeToSuiteLog({ str: indent, fd });
        writeToSuiteLog({
          str: gIn.tInfo.testInfoToString({
            curInfo,
            isDir: false,
            verbose,
            noTime,
          }),
          diffed: Boolean(curInfo.diffed),
          fd,
        });
        if (curInfo.diffed && gT.cLParams.difsToSlog && !isVerbose && !noTestDifs) {
          const difPath = gIn.textUtils.jsToDif(curInfo.path);
          const dif = fs.readFileSync(difPath, gT.engineConsts.logEncoding);
          writeToSuiteLog({ str: `${indent}============== DIF ============== \n`, fd });
          const diffStrs = dif.split('\n');
          diffStrs.forEach(str => {
            writeToSuiteLog({ str: indent, fd });
            writeToSuiteLog({ str: `${str}\n`, diffed: false, isDif: true, fd });
          });
          writeToSuiteLog({ str: `${indent}========== END OF DIF  ========== \n`, fd });
        }
      }
    }
  }
}

function saveSuiteLogPart({
  verbose,
  dirInfo,
  noTime,
  noTestDifs,
  fd,
}: {
  verbose: boolean;
  dirInfo: TestInfo;
  noTime?: boolean;
  noTestDifs?: boolean;
  fd?: number;
}) {
  isVerbose = verbose;
  const title = verbose ? 'Verbose' : 'Short';
  const decor = '====================';
  writeToSuiteLog({ str: `${decor}    ${title} Log BEGIN:    ${decor}\n`, fd });
  saveDirInfoToSuiteLog({
    dirInfo,
    indent: '',
    verbose,
    noTime,
    noTestDifs,
    fd,
  });
  writeToSuiteLog({ str: `${decor}    ${title} Log END.    ${decor}\n`, fd });
}

/**
 * Saves suite log.
 * @param dirInfo
 * @param log
 * @parem noTime
 * @returns {string} - Verbose info for the root test directory.
 */
export function saveSuiteLog({
  dirInfo,
  log,
  noTime,
  noTestDifs,
}: {
  dirInfo: TestInfo;
  log: string;
  noTime?: boolean;
  noTestDifs?: boolean;
}) {
  fd = fs.openSync(log, 'w');
  saveSuiteLogPart({
    verbose: false,
    dirInfo,
    noTime,
    noTestDifs,
    fd,
  });
  fs.writeSync(fd, '\n', null, gT.engineConsts.logEncoding);
  saveSuiteLogPart({
    verbose: true,
    dirInfo,
    noTime,
    noTestDifs,
    fd,
  });
  fs.closeSync(fd);
  return gIn.tInfo.testInfoToString({
    curInfo: dirInfo,
    isDir: true,
    verbose: true,
    noTime,
    noTitle: true,
    noEol: true,
  });
}

/* Prints expected tests results to stdout and unexpected to stderr */
export function printSuiteLog(dirInfo: any, noTestDifs?: boolean) {
  saveSuiteLogPart({ verbose: false, dirInfo, noTime: false, noTestDifs });
  writeToSuiteLog({ str: '\n' });
  saveSuiteLogPart({ verbose: true, dirInfo, noTime: false, noTestDifs });
}


text:
package jaredbgreat.climaticbiome.generation.biome.biomes;

import jaredbgreat.climaticbiome.biomes.ModBiomes;
import jaredbgreat.climaticbiome.compat.userdef.DefReader;
import jaredbgreat.climaticbiome.configuration.ClimaticWorldSettings;
import jaredbgreat.climaticbiome.configuration.ConfigHandler;
import jaredbgreat.climaticbiome.generation.biome.BiomeClimateTable;
import jaredbgreat.climaticbiome.generation.biome.BiomeList;
import jaredbgreat.climaticbiome.generation.biome.IBiomeSpecifier;
import jaredbgreat.climaticbiome.generation.biome.LeafBiome;
import jaredbgreat.climaticbiome.generation.mapgenerator.ChunkTile;

public class GetOcean implements IBiomeSpecifier {
	private ClimaticWorldSettings  settings;
	private static GetOcean oceans;
	private int nearEdge, farEdge;
	private GetOcean(ClimaticWorldSettings settings) {
		super();
		this.settings = settings;
		nearEdge = 5 + settings.regionSize.whole;
		farEdge  = (256 * settings.regionSize.whole) - 6 - settings.regionSize.whole;
		init();
	}
	BiomeList frozen;
	BiomeList cold;
	BiomeList cool;
	BiomeList warm;
	BiomeList hot;
	BiomeList dfrozen;
	BiomeList dcold;
	BiomeList dcool;
	BiomeList dwarm;
	BiomeList dhot;
	IBiomeSpecifier islands1; // Main land biomes
	IBiomeSpecifier islands2; // Special island-only biomes
	IBiomeSpecifier beaches;

	long coasts;
	long fcoasts;

	boolean makeCoasts;

	public void init() {
		coasts  = ModBiomes.coast.getIdForBiome(ModBiomes.coast);
		fcoasts = ModBiomes.frozenCoast.getIdForBiome(ModBiomes.frozenCoast);
		makeCoasts = settings.hasCoasts;
		// Shallows
		frozen = new BiomeList();
		cold   = new BiomeList();
		cool   = new BiomeList();
		warm   = new BiomeList();
		hot    = new BiomeList();
		//Deeps
		dfrozen = new BiomeList();
		dcold   = new BiomeList();
		dcool   = new BiomeList();
		dwarm   = new BiomeList();
		dhot    = new BiomeList();
		// Islands
		islands1 = BiomeClimateTable.getLandTable();
		islands2 = GetIslands.getIslands();
		// Beaches
		beaches = GetBeach.getBeach();
		// Add biomes
		DefReader.readBiomeData(frozen,  "OceanFrozen.cfg");
		DefReader.readBiomeData(cold,    "OceanCold.cfg");
		DefReader.readBiomeData(cool,    "OceanCool.cfg");
		DefReader.readBiomeData(warm,    "OceanWarm.cfg");
		DefReader.readBiomeData(hot,     "OceanHot.cfg");
		DefReader.readBiomeData(dfrozen, "DeepOceanFrozen.cfg");
		DefReader.readBiomeData(dcold,   "DeepOceanCold.cfg");
		DefReader.readBiomeData(dcool,   "DeepOceanCool.cfg");
		DefReader.readBiomeData(dwarm,   "DeepOceanWarm.cfg");
		DefReader.readBiomeData(dhot,    "DeepOceanHot.cfg");
		if(warm.isEmpty()) {
			warm.addItem(new LeafBiome(0));
		}
		if(hot.isEmpty()) {
			hot.addItem(new LeafBiome(0));
		}
		if(dwarm.isEmpty()) {
			dwarm.addItem(new LeafBiome(24));
		}
		if(dhot.isEmpty()) {
			dhot.addItem(new LeafBiome(24));
		}
		if(cool.isEmpty()) {
			cool.addItem(new LeafBiome(0));
		}
		if(dcool.isEmpty()) {
			dcool.addItem(new LeafBiome(24));
		}
		if(frozen.isEmpty()) {
			frozen.addItem(new LeafBiome(10));
		}
		if(dfrozen.isEmpty()) {
			dfrozen.addItem(new LeafBiome(10));
		}
		// MUST BE LAST, ALWAYS!!!
		fixOceans();
	}

	@Override
	public long getBiome(ChunkTile tile) {
		tile.setVanilla();
		int temp = tile.getTemp();
		int seed = tile.getBiomeSeed();
		int iceNoise = tile.getNoise();
		if(makeCoasts && tile.isBeach() && !tile.isRiver() && !swampy(tile)) {
			tile.setSteep();
	        if(((iceNoise / 2) - temp) > -1) {
	        	return fcoasts;
	        }
			return coasts;
		}
		tile.nextBiomeSeed();
        if(settings.addIslands && (((seed % 5) == 0)
        					   && notNearEdge(tile))) {
    		int noise = tile.getNoise();
    		if((seed % 31) == 0) {
    				if((tile.getTemp() > 9) && (tile.getTemp() < 19)
    						                && (tile.getWet() > 3)) {
    					if(noise < 5) {
    						return 14;
    					}
    					if(noise < 7) {
    						return 15;
    					}
    				}
    				return 0;
    			} else if(settings.addIslands && ((seed & 1) == 0)) {
    				if(noise > (4 + (seed % 3))) {
    					return islands1.getBiome(tile.nextBiomeSeed());
    				}
    			} else if(settings.addIslands) {
    				if(noise > (seed % 3)) {
    					return islands2.getBiome(tile.nextBiomeSeed());
    				}
    			}
    			return getForIsland(tile);
    		} else if((tile.getHeight()) < 0.2) {
    			return getDeepOcean(tile, temp, iceNoise);
    		}
    	return getShallowOcean(tile, temp, iceNoise);
    }

	public long getDeepOcean(ChunkTile tile, int temp, int iceNoise) {
        if(((iceNoise / 2) - temp) > -1) {
        	return dfrozen.getBiome(tile);
        }
    	if(temp < 7) {
    		return dcold.getBiome(tile);
    	}
    	if(temp < 13) {
    		return dcool.getBiome(tile);
    	}
    	if(temp < 19) {
    		return dwarm.getBiome(tile);
    	}
    	return dhot.getBiome(tile);
	}

	public long getShallowOcean(ChunkTile tile, int temp, int iceNoise) {
        if(((iceNoise / 2) - temp) > -1) {
        	return frozen.getBiome(tile);
        }
    	if(temp < 7) {
    		return cold.getBiome(tile);
    	}
    	if(temp < 13) {
    		return cool.getBiome(tile);
    	}
    	if(temp < 19) {
    		return warm.getBiome(tile);
    	}
    	return hot.getBiome(tile);
	}

	public static GetOcean getOcean(ClimaticWorldSettings settings) {
		if(oceans == null) {
			oceans = new GetOcean(settings);
		}
		return oceans;
	}

	public static GetOcean getOceanForIslands() {
		return oceans;
	}

	/**
	 * This fixes possible problems with ocean,
	 * specifically, makes sure there are no
	 * oceans types empty.  This way mods can
	 * add temperature specific oceans, while
	 * not relying on them.
	 */
	private void fixOceans() {
		if(warm.isEmpty()) {
			warm = cool;
		}
		if(hot.isEmpty()) {
			hot = warm;
		}
		if(cold.isEmpty()) {
			cold = cool;
		}
		if(frozen.isEmpty()) {
			// Should never be true, but just in case.
			frozen = cold;
		}
		if(dcool.isEmpty()) {
			// Should never be true, but just in case.
			dcool = cool;
		}
		if(dwarm.isEmpty()) {
			dwarm = dcool;
		}
		if(dhot.isEmpty()) {
			dhot = dwarm;
		}
		if(dcold.isEmpty()) {
			dcold = dcool;
		}
		if(dfrozen.isEmpty()) {
			// Should never be true, but just in case.
			dfrozen = dcold;
		}
	}

	/**
	 * This will get the oceans surrounding islands.
	 *
	 * @param tile
	 * @return
	 */
	public long getForIsland(ChunkTile tile) {
		//tile.nextBiomeSeed();
		return getShallowOcean(tile, tile.getTemp(), tile.getNoise());
		//return coasts;
	}

	private boolean notNearEdge(ChunkTile tile) {
		int x = tile.getX();
		int z = tile.getZ();
		return ((x > nearEdge) && (x < farEdge)) && ((z > nearEdge) && (z < farEdge));
	}

	@Override
	public boolean isEmpty() {
		return false;
	}

	private boolean swampy(ChunkTile tile) {
		return ((tile.getTemp() > 7)
				&& ((tile.getWet() - tile.getVal() - tile.getHeight()) > 0));
	}

}


text:
package uk.co.odum.matchers;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

import static javax.validation.Validation.buildDefaultValidatorFactory;

public class JSR303ViolationsMatcher<T> extends TypeSafeMatcher<T> {

    private Validator validator;
    private Set<ConstraintViolation<T>> violations;
    private String interpolatedMessage;
    private boolean matchWithViolations;

    public JSR303ViolationsMatcher(String interpolatedMessage, boolean matchWithViolations) {
        validator = buildDefaultValidatorFactory().getValidator();
        this.interpolatedMessage = interpolatedMessage;
        this.matchWithViolations = matchWithViolations;
    }

    @Override
    protected boolean matchesSafely(T item) {
        violations = validator.validate(item);
        if (interpolatedMessage != null) {
            return violationsContainsMessage(interpolatedMessage);
        }
        else {
            return matchWithViolations ? violations.size() > 0 : violations.size() == 0;
        }
    }

    private boolean violationsContainsMessage(String message) {
        boolean contains = false;
        for (ConstraintViolation v : violations) {
            if (v.getMessage().equals(message)) {
                contains = true;
                break;
            }
        }
        return contains;
    }

    @Override
    public void describeTo(Description description) {
        if (interpolatedMessage != null) {
            description.appendValue(interpolatedMessage);
        }
        else {
            description.appendText("jsr303 validation violations");
        }
    }

    @Override
    protected void describeMismatchSafely(T item, Description mismatchDescription) {
        mismatchDescription.appendText("was ").appendValue(violations);
    }

    @Factory
    public static JSR303ViolationsMatcher hasViolations() {
        return new JSR303ViolationsMatcher(null, true);
    }

    @Factory
    public static JSR303ViolationsMatcher hasViolation(String interpolatedMessage) {
        return new JSR303ViolationsMatcher(interpolatedMessage, true);
    }

    @Factory
    public static JSR303ViolationsMatcher hasNoViolations() {
        return new JSR303ViolationsMatcher(null, false);
    }
}


text:
#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "modules/webaudio/MediaStreamAudioDestinationNode.h"

#include "modules/webaudio/AudioContext.h"
#include "modules/webaudio/AudioNodeInput.h"
#include "platform/UUID.h"
#include "platform/mediastream/MediaStreamCenter.h"
#include "public/platform/WebRTCPeerConnectionHandler.h"
#include "wtf/Locker.h"

namespace blink {

MediaStreamAudioDestinationNode* MediaStreamAudioDestinationNode::create(AudioContext* context, size_t numberOfChannels)
{
    return new MediaStreamAudioDestinationNode(context, numberOfChannels);
}

MediaStreamAudioDestinationNode::MediaStreamAudioDestinationNode(AudioContext* context, size_t numberOfChannels)
    : AudioBasicInspectorNode(NodeTypeMediaStreamAudioDestination, context, context->sampleRate(), numberOfChannels)
    , m_mixBus(AudioBus::create(numberOfChannels, ProcessingSizeInFrames))
{
    m_source = MediaStreamSource::create("WebAudio-" + createCanonicalUUIDString(), MediaStreamSource::TypeAudio, "MediaStreamAudioDestinationNode", false, true, MediaStreamSource::ReadyStateLive, true);
    MediaStreamSourceVector audioSources;
    audioSources.append(m_source);
    MediaStreamSourceVector videoSources;
    m_stream = MediaStream::create(context->executionContext(), MediaStreamDescriptor::create(audioSources, videoSources));
    MediaStreamCenter::instance().didCreateMediaStreamAndTracks(m_stream->descriptor());

    m_source->setAudioFormat(numberOfChannels, context->sampleRate());

    initialize();
}

MediaStreamAudioDestinationNode::~MediaStreamAudioDestinationNode()
{
    ASSERT(!isInitialized());
}

void MediaStreamAudioDestinationNode::dispose()
{
    uninitialize();
    AudioBasicInspectorNode::dispose();
}

DEFINE_TRACE(MediaStreamAudioDestinationNode)
{
    visitor->trace(m_stream);
    AudioBasicInspectorNode::trace(visitor);
}

void MediaStreamAudioDestinationNode::process(size_t numberOfFrames)
{
    m_mixBus->copyFrom(*input(0)->bus());
    m_source->consumeAudio(m_mixBus.get(), numberOfFrames);
}

} // namespace blink

#endif // ENABLE(WEB_AUDIO)


text:
/**
 * @author Dmitry A. Durnev
 */
package org.apache.harmony.awt.wtk;

import com.google.code.appengine.awt.Point;

/**
 * The interface provides access to platform dependent functionality
 * for classes com.google.code.appengine.awt.PointerInfo & com.google.code.appengine.awt.MouseInfo.
 */
public interface NativeMouseInfo {

    /**
     * Returns the Point that represents
     * the coordinates of the pointer on the screen.
     */
    Point getLocation();

    /**
     * Returns the number of buttons on the mouse.
     * If no mouse is installed returns -1.
     */
    int getNumberOfButtons();
}


text:
namespace SFA.DAS.EmployerFinance.Queries.GetContent
{
    public class GetContentResponse
    {
        public string Content { get; set; }
        public bool HasFailed { get; set; }
    }
}


text:
hubot-plusplus-plus
===================

[![Build Status](https://travis-ci.org/ThomasGaubert/hubot-plusplus-plus.svg?branch=master)](https://travis-ci.org/ThomasGaubert/hubot-plusplus-plus)

Give (or take away) points from people and things, all from the comfort of your
personal Hubot.

Forked from [the original hubot-plusplus](https://github.com/ajacksified/hubot-plusplus).

API
---

* `thing++` - add a point to `thing`
* `++` - add a point to the most previously voted-on thing
* `thing++ for stuff` - keep track of why you gave thing points
* `thing--` - remove a point from `thing`
* `--` - remove a point from the most previously voted-on thing
* `thing-- for stuff` - keep track of why you removed thing points
* `hubot erase thing` - erase thing from scoreboard (permanently deletes thing from memory)
* `hubot erase thing for reason` erase given reason from thing's score board (does not deduct from total score)
* `hubot top 10` - show the top 10, with a graph of points
* `hubot score thing` - check the score for and reasons for `thing`

Uses Hubot brain. Also exposes the following events, should you wish to hook
into it to do things like print out funny gifs for point streaks:

```coffeescript
robot.emit "plus-one", {
  name: 'Jack'
  direction: '++' # (or --)
  room: 'chatRoomAlpha'
  reason: 'being awesome'
}
```

## Installation

Run the following command

    $ npm install hubot-plusplus-plus

Then to make sure the dependencies are installed:

    $ npm install

To enable the script, add a `hubot-plusplus` entry to the `external-scripts.json`
file (you may need to create this file).

    ["hubot-plusplus-plus"]


text:
.class Landroid/media/AudioService$2;
.super Ljava/lang/Object;
.source "AudioService.java"

# interfaces
.implements Landroid/bluetooth/BluetoothProfile$ServiceListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/AudioService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Landroid/media/AudioService;

# direct methods
.method constructor <init>(Landroid/media/AudioService;)V
    .locals 0
    .parameter

    .prologue
    .line 2704
    iput-object p1, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onServiceConnected(ILandroid/bluetooth/BluetoothProfile;)V
    .locals 13
    .parameter "profile"
    .parameter "proxy"

    .prologue
    const/4 v1, 0x0

    .line 2708
    packed-switch p1, :pswitch_data_0

    .line 2763
    .end local p2
    :cond_0
    :goto_0
    return-void

    .restart local p2
    :pswitch_0
    move-object v8, p2

    .line 2710
    check-cast v8, Landroid/bluetooth/BluetoothA2dp;

    .line 2711
    .local v8, a2dp:Landroid/bluetooth/BluetoothA2dp;
    invoke-virtual {v8}, Landroid/bluetooth/BluetoothA2dp;->getConnectedDevices()Ljava/util/List;

    move-result-object v10

    .line 2712
    .local v10, deviceList:Ljava/util/List;,"Ljava/util/List<Landroid/bluetooth/BluetoothDevice;>;"
    invoke-interface {v10}, Ljava/util/List;->size()I

    move-result v0

    if-lez v0, :cond_0

    .line 2713
    invoke-interface {v10, v1}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v9

    check-cast v9, Landroid/bluetooth/BluetoothDevice;

    .line 2714
    .local v9, btDevice:Landroid/bluetooth/BluetoothDevice;
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    invoke-virtual {v8, v9}, Landroid/bluetooth/BluetoothA2dp;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I

    move-result v1

    #calls: Landroid/media/AudioService;->handleA2dpConnectionStateChange(Landroid/bluetooth/BluetoothDevice;I)V
    invoke-static {v0, v9, v1}, Landroid/media/AudioService;->access$3100(Landroid/media/AudioService;Landroid/bluetooth/BluetoothDevice;I)V

    goto :goto_0

    .line 2719
    .end local v8           #a2dp:Landroid/bluetooth/BluetoothA2dp;
    .end local v9           #btDevice:Landroid/bluetooth/BluetoothDevice;
    .end local v10           #deviceList:Ljava/util/List;,"Ljava/util/List<Landroid/bluetooth/BluetoothDevice;>;"
    :pswitch_1
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoClients:Ljava/util/ArrayList;
    invoke-static {v0}, Landroid/media/AudioService;->access$2400(Landroid/media/AudioService;)Ljava/util/ArrayList;

    move-result-object v12

    monitor-enter v12

    .line 2721
    :try_start_0
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mAudioHandler:Landroid/media/AudioService$AudioHandler;
    invoke-static {v0}, Landroid/media/AudioService;->access$100(Landroid/media/AudioService;)Landroid/media/AudioService$AudioHandler;

    move-result-object v0

    const/16 v1, 0xc

    invoke-virtual {v0, v1}, Landroid/media/AudioService$AudioHandler;->removeMessages(I)V

    .line 2722
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    check-cast p2, Landroid/bluetooth/BluetoothHeadset;

    .end local p2
    #setter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0, p2}, Landroid/media/AudioService;->access$2802(Landroid/media/AudioService;Landroid/bluetooth/BluetoothHeadset;)Landroid/bluetooth/BluetoothHeadset;

    .line 2723
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0}, Landroid/media/AudioService;->access$2800(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothHeadset;

    move-result-object v0

    invoke-virtual {v0}, Landroid/bluetooth/BluetoothHeadset;->getConnectedDevices()Ljava/util/List;

    move-result-object v10

    .line 2724
    .restart local v10       #deviceList:Ljava/util/List;,"Ljava/util/List<Landroid/bluetooth/BluetoothDevice;>;"
    invoke-interface {v10}, Ljava/util/List;->size()I

    move-result v0

    if-lez v0, :cond_4

    .line 2725
    iget-object v1, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    const/4 v0, 0x0

    invoke-interface {v10, v0}, Ljava/util/List;->get(I)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/bluetooth/BluetoothDevice;

    #setter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v1, v0}, Landroid/media/AudioService;->access$2902(Landroid/media/AudioService;Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothDevice;

    .line 2730
    :goto_1
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #calls: Landroid/media/AudioService;->checkScoAudioState()V
    invoke-static {v0}, Landroid/media/AudioService;->access$2500(Landroid/media/AudioService;)V

    .line 2732
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoAudioState:I
    invoke-static {v0}, Landroid/media/AudioService;->access$2700(Landroid/media/AudioService;)I

    move-result v0

    const/4 v1, 0x1

    if-eq v0, v1, :cond_1

    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoAudioState:I
    invoke-static {v0}, Landroid/media/AudioService;->access$2700(Landroid/media/AudioService;)I

    move-result v0

    const/4 v1, 0x5

    if-eq v0, v1, :cond_1

    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoAudioState:I
    invoke-static {v0}, Landroid/media/AudioService;->access$2700(Landroid/media/AudioService;)I

    move-result v0

    const/4 v1, 0x4

    if-ne v0, v1, :cond_3

    .line 2735
    :cond_1
    const/4 v11, 0x0

    .line 2736
    .local v11, status:Z
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v0}, Landroid/media/AudioService;->access$2900(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothDevice;

    move-result-object v0

    if-eqz v0, :cond_2

    .line 2737
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoAudioState:I
    invoke-static {v0}, Landroid/media/AudioService;->access$2700(Landroid/media/AudioService;)I

    move-result v0

    packed-switch v0, :pswitch_data_1

    .line 2752
    :cond_2
    :goto_2
    :pswitch_2
    if-nez v11, :cond_3

    .line 2753
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mAudioHandler:Landroid/media/AudioService$AudioHandler;
    invoke-static {v0}, Landroid/media/AudioService;->access$100(Landroid/media/AudioService;)Landroid/media/AudioService$AudioHandler;

    move-result-object v0

    const/16 v1, 0xc

    const/4 v2, 0x0

    const/4 v3, 0x0

    const/4 v4, 0x0

    const/4 v5, 0x0

    const/4 v6, 0x0

    const/4 v7, 0x0

    #calls: Landroid/media/AudioService;->sendMsg(Landroid/os/Handler;IIIIILjava/lang/Object;I)V
    invoke-static/range {v0 .. v7}, Landroid/media/AudioService;->access$200(Landroid/os/Handler;IIIIILjava/lang/Object;I)V

    .line 2757
    .end local v11           #status:Z
    :cond_3
    monitor-exit v12

    goto/16 :goto_0

    .end local v10           #deviceList:Ljava/util/List;,"Ljava/util/List<Landroid/bluetooth/BluetoothDevice;>;"
    :catchall_0
    move-exception v0

    monitor-exit v12
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0

    .line 2727
    .restart local v10       #deviceList:Ljava/util/List;,"Ljava/util/List<Landroid/bluetooth/BluetoothDevice;>;"
    :cond_4
    :try_start_1
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    const/4 v1, 0x0

    #setter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v0, v1}, Landroid/media/AudioService;->access$2902(Landroid/media/AudioService;Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothDevice;

    goto :goto_1

    .line 2739
    .restart local v11       #status:Z
    :pswitch_3
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    const/4 v1, 0x3

    #setter for: Landroid/media/AudioService;->mScoAudioState:I
    invoke-static {v0, v1}, Landroid/media/AudioService;->access$2702(Landroid/media/AudioService;I)I

    .line 2740
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0}, Landroid/media/AudioService;->access$2800(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothHeadset;

    move-result-object v0

    iget-object v1, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v1}, Landroid/media/AudioService;->access$2900(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothDevice;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/bluetooth/BluetoothHeadset;->startScoUsingVirtualVoiceCall(Landroid/bluetooth/BluetoothDevice;)Z

    move-result v11

    .line 2742
    goto :goto_2

    .line 2744
    :pswitch_4
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0}, Landroid/media/AudioService;->access$2800(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothHeadset;

    move-result-object v0

    iget-object v1, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v1}, Landroid/media/AudioService;->access$2900(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothDevice;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/bluetooth/BluetoothHeadset;->stopScoUsingVirtualVoiceCall(Landroid/bluetooth/BluetoothDevice;)Z

    move-result v11

    .line 2746
    goto :goto_2

    .line 2748
    :pswitch_5
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0}, Landroid/media/AudioService;->access$2800(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothHeadset;

    move-result-object v0

    iget-object v1, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mBluetoothHeadsetDevice:Landroid/bluetooth/BluetoothDevice;
    invoke-static {v1}, Landroid/media/AudioService;->access$2900(Landroid/media/AudioService;)Landroid/bluetooth/BluetoothDevice;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/bluetooth/BluetoothHeadset;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    move-result v11

    goto :goto_2

    .line 2708
    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_1
        :pswitch_0
    .end packed-switch

    .line 2737
    :pswitch_data_1
    .packed-switch 0x1
        :pswitch_3
        :pswitch_2
        :pswitch_2
        :pswitch_5
        :pswitch_4
    .end packed-switch
.end method

.method public onServiceDisconnected(I)V
    .locals 4
    .parameter "profile"

    .prologue
    .line 2765
    packed-switch p1, :pswitch_data_0

    .line 2784
    :goto_0
    return-void

    .line 2767
    :pswitch_0
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mConnectedDevices:Ljava/util/HashMap;
    invoke-static {v0}, Landroid/media/AudioService;->access$3200(Landroid/media/AudioService;)Ljava/util/HashMap;

    move-result-object v1

    monitor-enter v1

    .line 2768
    :try_start_0
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mConnectedDevices:Ljava/util/HashMap;
    invoke-static {v0}, Landroid/media/AudioService;->access$3200(Landroid/media/AudioService;)Ljava/util/HashMap;

    move-result-object v0

    const/16 v2, 0x80

    invoke-static {v2}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v2

    invoke-virtual {v0, v2}, Ljava/util/HashMap;->containsKey(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 2769
    iget-object v2, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mConnectedDevices:Ljava/util/HashMap;
    invoke-static {v0}, Landroid/media/AudioService;->access$3200(Landroid/media/AudioService;)Ljava/util/HashMap;

    move-result-object v0

    const/16 v3, 0x80

    invoke-static {v3}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v3

    invoke-virtual {v0, v3}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/String;

    #calls: Landroid/media/AudioService;->makeA2dpDeviceUnavailableNow(Ljava/lang/String;)V
    invoke-static {v2, v0}, Landroid/media/AudioService;->access$3300(Landroid/media/AudioService;Ljava/lang/String;)V

    .line 2772
    :cond_0
    monitor-exit v1

    goto :goto_0

    :catchall_0
    move-exception v0

    monitor-exit v1
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0

    .line 2776
    :pswitch_1
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    #getter for: Landroid/media/AudioService;->mScoClients:Ljava/util/ArrayList;
    invoke-static {v0}, Landroid/media/AudioService;->access$2400(Landroid/media/AudioService;)Ljava/util/ArrayList;

    move-result-object v1

    monitor-enter v1

    .line 2777
    :try_start_1
    iget-object v0, p0, Landroid/media/AudioService$2;->this$0:Landroid/media/AudioService;

    const/4 v2, 0x0

    #setter for: Landroid/media/AudioService;->mBluetoothHeadset:Landroid/bluetooth/BluetoothHeadset;
    invoke-static {v0, v2}, Landroid/media/AudioService;->access$2802(Landroid/media/AudioService;Landroid/bluetooth/BluetoothHeadset;)Landroid/bluetooth/BluetoothHeadset;

    .line 2778
    monitor-exit v1

    goto :goto_0

    :catchall_1
    move-exception v0

    monitor-exit v1
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    throw v0

    .line 2765
    nop

    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_1
        :pswitch_0
    .end packed-switch
.end method


text:
#include "config.h"
#include "core/animation/animatable/AnimatableStrokeDasharrayList.h"

#include "core/animation/animatable/AnimatableLength.h"

namespace blink {

AnimatableStrokeDasharrayList::AnimatableStrokeDasharrayList(PassRefPtr<SVGDashArray> passLengths, float zoom)
{
    RefPtr<SVGDashArray> lengths = passLengths;
    for (const Length& dashLength : lengths->vector())
        m_values.append(AnimatableLength::create(dashLength, zoom));
}

PassRefPtr<SVGDashArray> AnimatableStrokeDasharrayList::toSVGDashArray(float zoom) const
{
    RefPtr<SVGDashArray> lengths = SVGDashArray::create();
    for (const auto& dashLength : m_values)
        lengths->append(toAnimatableLength(dashLength.get())->length(zoom, ValueRangeNonNegative));
    return lengths.release();
}

bool AnimatableStrokeDasharrayList::usesDefaultInterpolationWith(const AnimatableValue* value) const
{
    WillBeHeapVector<RefPtrWillBeMember<AnimatableValue>> from = m_values;
    WillBeHeapVector<RefPtrWillBeMember<AnimatableValue>> to = toAnimatableStrokeDasharrayList(value)->m_values;
    return !from.isEmpty() && !to.isEmpty() && AnimatableRepeatable::usesDefaultInterpolationWith(value);
}

PassRefPtrWillBeRawPtr<AnimatableValue> AnimatableStrokeDasharrayList::interpolateTo(const AnimatableValue* value, double fraction) const
{
    if (usesDefaultInterpolationWith(value))
        return defaultInterpolateTo(this, value, fraction);

    WillBeHeapVector<RefPtrWillBeMember<AnimatableValue>> from = m_values;
    WillBeHeapVector<RefPtrWillBeMember<AnimatableValue>> to = toAnimatableStrokeDasharrayList(value)->m_values;

    // The spec states that if the sum of all values is zero, this should be
    // treated like a value of 'none', which means that a solid line is drawn.
    // Since we animate to and from values of zero, treat a value of 'none' the
    // same. If both the two and from values are 'none', we return 'none'
    // rather than '0 0'.
    if (from.isEmpty() && to.isEmpty())
        return takeConstRef(this);
    if (from.isEmpty() || to.isEmpty()) {
        DEFINE_STATIC_REF_WILL_BE_PERSISTENT(AnimatableLength, zeroPixels, (AnimatableLength::create(Length(Fixed), 1)));
        if (from.isEmpty()) {
            from.append(zeroPixels);
            from.append(zeroPixels);
        }
        if (to.isEmpty()) {
            to.append(zeroPixels);
            to.append(zeroPixels);
        }
    }

    WillBeHeapVector<RefPtrWillBeMember<AnimatableValue>> interpolatedValues;
    bool success = interpolateLists(from, to, fraction, interpolatedValues);
    ASSERT_UNUSED(success, success);
    return adoptRefWillBeNoop(new AnimatableStrokeDasharrayList(interpolatedValues));
}

DEFINE_TRACE(AnimatableStrokeDasharrayList)
{
    AnimatableRepeatable::trace(visitor);
}

} // namespace blink


text:
package gobblin.converter;

import gobblin.configuration.ConfigurationKeys;
import gobblin.configuration.WorkUnitState;
import gobblin.metrics.kafka.KafkaSchemaRegistryFactory;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Unit test for {@link EnvelopeSchemaConverter}.
 */
@Test(groups = {"gobblin.converter"})
public class EnvelopeSchemaConverterTest {

  public static final String SCHEMA_KEY = "testKey";

  private GenericRecord mockInputRecord = mock(GenericRecord.class);
  private GenericRecord mockOutputRecord = mock(GenericRecord.class);
  public static Schema mockSchema = mock(Schema.class);

  class EnvelopeSchemaConverterForTest extends EnvelopeSchemaConverter {
    @Override
    public byte[] getPayload(GenericRecord inputRecord, String payloadFieldName) {
      return null;
    }

    @Override
    public GenericRecord deserializePayload(byte[] payload, Schema payloadSchema) {
      Assert.assertEquals(payloadSchema, mockSchema);
      return mockOutputRecord;
    }
  }

  @Test
  public void convertRecordTest() throws Exception {
    when(mockInputRecord.get("payloadSchemaId")).thenReturn(SCHEMA_KEY);
    when(mockOutputRecord.getSchema()).thenReturn(mockSchema);

    WorkUnitState workUnitState = new WorkUnitState();
    workUnitState.setProp(ConfigurationKeys.EXTRACT_TABLE_NAME_KEY, "testEvent");
    workUnitState.setProp("kafka.schema.registry.url", "testUrl");
    workUnitState.setProp(KafkaSchemaRegistryFactory.KAFKA_SCHEMA_REGISTRY_FACTORY_CLASS,
        KafkaAvroSchemaRegistryForTest.Factory.class.getName());

    EnvelopeSchemaConverterForTest converter = new EnvelopeSchemaConverterForTest();
    converter.init(workUnitState);
    GenericRecord output = converter.convertRecord(null, mockInputRecord, workUnitState).iterator().next();
    Assert.assertEquals(output, mockOutputRecord);
  }
}


text:
package org.ray.api.test;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.lang.ProcessBuilder.Redirect;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.ray.api.Ray;
import org.ray.runtime.util.NetworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

public abstract class BaseMultiLanguageTest {

  private static final Logger LOGGER = LoggerFactory.getLogger(BaseMultiLanguageTest.class);

  private static final String PLASMA_STORE_SOCKET_NAME = "/tmp/ray/test/plasma_store_socket";
  private static final String RAYLET_SOCKET_NAME = "/tmp/ray/test/raylet_socket";

  /**
   * Execute an external command.
   *
   * @return Whether the command succeeded.
   */
  private boolean executeCommand(List<String> command, int waitTimeoutSeconds,
      Map<String, String> env) {
    try {
      LOGGER.info("Executing command: {}", String.join(" ", command));
      ProcessBuilder processBuilder = new ProcessBuilder(command).redirectOutput(Redirect.INHERIT)
          .redirectError(Redirect.INHERIT);
      for (Entry<String, String> entry : env.entrySet()) {
        processBuilder.environment().put(entry.getKey(), entry.getValue());
      }
      Process process = processBuilder.start();
      process.waitFor(waitTimeoutSeconds, TimeUnit.SECONDS);
      return process.exitValue() == 0;
    } catch (Exception e) {
      throw new RuntimeException("Error executing command " + String.join(" ", command), e);
    }
  }

  private void checkMultiLanguageTestFlag() {
    if (!"1".equals(System.getenv("ENABLE_MULTI_LANGUAGE_TESTS"))) {
      LOGGER.info("Skip Multi-language tests because environment variable "
          + "ENABLE_MULTI_LANGUAGE_TESTS isn't set");
      throw new SkipException("Skip test.");
    }
  }

  @BeforeClass(alwaysRun = true)
  public void setUp() {
    checkMultiLanguageTestFlag();

    // Delete existing socket files.
    for (String socket : ImmutableList.of(RAYLET_SOCKET_NAME, PLASMA_STORE_SOCKET_NAME)) {
      File file = new File(socket);
      if (file.exists()) {
        file.delete();
      }
    }

    String nodeManagerPort = String.valueOf(NetworkUtil.getUnusedPort());

    // jars in the `ray` wheel doesn't contains test classes, so we add test classes explicitly.
    // Since mvn test classes contains `test` in path and bazel test classes is located at a jar
    // with `test` included in the name, we can check classpath `test` to filter out test classes.
    String classpath = Stream.of(System.getProperty("java.class.path").split(":"))
        .filter(s -> !s.contains(" ") && s.contains("test"))
        .collect(Collectors.joining(":"));
    String workerOptions =
        " -classpath " + classpath;
    // Start ray cluster.
    List<String> startCommand = ImmutableList.of(
        "ray",
        "start",
        "--head",
        "--redis-port=6379",
        String.format("--plasma-store-socket-name=%s", PLASMA_STORE_SOCKET_NAME),
        String.format("--raylet-socket-name=%s", RAYLET_SOCKET_NAME),
        String.format("--node-manager-port=%s", nodeManagerPort),
        "--load-code-from-local",
        "--include-java",
        "--java-worker-options=" + workerOptions
    );
    String numWorkersPerProcessJava = System
        .getProperty("ray.raylet.config.num_workers_per_process_java");
    if (!Strings.isNullOrEmpty(numWorkersPerProcessJava)) {
      startCommand = ImmutableList.<String>builder().addAll(startCommand)
          .add(String.format("--internal-config={\"num_workers_per_process_java\": %s}",
              numWorkersPerProcessJava)).build();
    }
    if (!executeCommand(startCommand, 10, getRayStartEnv())) {
      throw new RuntimeException("Couldn't start ray cluster.");
    }

    // Connect to the cluster.
    Assert.assertNull(Ray.internal());
    System.setProperty("ray.redis.address", "127.0.0.1:6379");
    System.setProperty("ray.object-store.socket-name", PLASMA_STORE_SOCKET_NAME);
    System.setProperty("ray.raylet.socket-name", RAYLET_SOCKET_NAME);
    System.setProperty("ray.raylet.node-manager-port", nodeManagerPort);
    Ray.init();
  }

  /**
   * @return The environment variables needed for the `ray start` command.
   */
  protected Map<String, String> getRayStartEnv() {
    return ImmutableMap.of();
  }

  @AfterClass(alwaysRun = true)
  public void tearDown() {
    checkMultiLanguageTestFlag();

    // Disconnect to the cluster.
    Ray.shutdown();
    System.clearProperty("ray.redis.address");
    System.clearProperty("ray.object-store.socket-name");
    System.clearProperty("ray.raylet.socket-name");
    System.clearProperty("ray.raylet.node-manager-port");

    // Stop ray cluster.
    final List<String> stopCommand = ImmutableList.of(
        "ray",
        "stop"
    );
    if (!executeCommand(stopCommand, 10, ImmutableMap.of())) {
      throw new RuntimeException("Couldn't stop ray cluster");
    }
  }
}