text:
package com.google.template.soy;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
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.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.ByteSink;
import com.google.common.io.CharSource;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.util.Providers;
import com.google.template.soy.SoyFileSetParser.ParseResult;
import com.google.template.soy.base.SoySyntaxException;
import com.google.template.soy.base.internal.SoyFileKind;
import com.google.template.soy.base.internal.SoyFileSupplier;
import com.google.template.soy.base.internal.VolatileSoyFileSupplier;
import com.google.template.soy.basetree.SyntaxVersion;
import com.google.template.soy.conformance.CheckConformance;
import com.google.template.soy.conformance.ConformanceInput;
import com.google.template.soy.error.PrettyErrorFactory;
import com.google.template.soy.error.SnippetFormatter;
import com.google.template.soy.error.SoyCompilationException;
import com.google.template.soy.error.SoyError;
import com.google.template.soy.incrementaldomsrc.IncrementalDomSrcMain;
import com.google.template.soy.jbcsrc.BytecodeCompiler;
import com.google.template.soy.jbcsrc.api.SoySauce;
import com.google.template.soy.jbcsrc.api.SoySauceImpl;
import com.google.template.soy.jbcsrc.shared.CompiledTemplate;
import com.google.template.soy.jbcsrc.shared.CompiledTemplates;
import com.google.template.soy.jssrc.SoyJsSrcOptions;
import com.google.template.soy.jssrc.internal.JsSrcMain;
import com.google.template.soy.msgs.SoyMsgBundle;
import com.google.template.soy.msgs.SoyMsgBundleHandler;
import com.google.template.soy.msgs.internal.ExtractMsgsVisitor;
import com.google.template.soy.msgs.restricted.SoyMsg;
import com.google.template.soy.msgs.restricted.SoyMsgBundleImpl;
import com.google.template.soy.parseinfo.passes.GenerateParseInfoVisitor;
import com.google.template.soy.parsepasses.contextautoesc.ContentSecurityPolicyPass;
import com.google.template.soy.parsepasses.contextautoesc.ContextualAutoescaper;
import com.google.template.soy.parsepasses.contextautoesc.DerivedTemplateUtils;
import com.google.template.soy.passes.ChangeCallsToPassAllDataVisitor;
import com.google.template.soy.passes.ClearSoyDocStringsVisitor;
import com.google.template.soy.passes.FindIjParamsVisitor;
import com.google.template.soy.passes.FindIjParamsVisitor.IjParamsInfo;
import com.google.template.soy.passes.FindTransitiveDepTemplatesVisitor;
import com.google.template.soy.passes.FindTransitiveDepTemplatesVisitor.TransitiveDepTemplatesInfo;
import com.google.template.soy.passes.PassManager;
import com.google.template.soy.pysrc.SoyPySrcOptions;
import com.google.template.soy.pysrc.internal.PySrcMain;
import com.google.template.soy.shared.SoyAstCache;
import com.google.template.soy.shared.SoyGeneralOptions;
import com.google.template.soy.shared.internal.MainEntryPointUtils;
import com.google.template.soy.shared.restricted.SoyFunction;
import com.google.template.soy.shared.restricted.SoyPrintDirective;
import com.google.template.soy.sharedpasses.opti.SimplifyVisitor;
import com.google.template.soy.soytree.SoyFileNode;
import com.google.template.soy.soytree.SoyFileSetNode;
import com.google.template.soy.soytree.SoytreeUtils;
import com.google.template.soy.soytree.TemplateDelegateNode;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.TemplateRegistry;
import com.google.template.soy.soytree.Visibility;
import com.google.template.soy.tofu.SoyTofu;
import com.google.template.soy.tofu.internal.BaseTofu.BaseTofuFactory;
import com.google.template.soy.types.SoyTypeRegistry;
import com.google.template.soy.xliffmsgplugin.XliffMsgPlugin;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * Represents a complete set of Soy files for compilation as one bundle. The files may depend on
 * each other but should not have dependencies outside of the set.
 *
 *
 Note: Soy file (or resource) contents must be encoded in UTF-8.
 *
 */
public final class SoyFileSet {

  /**
   * Creates a builder with the standard set of Soy directives, functions, and types.
   *
   *
If you need additional directives, functions, or types, create the Builder instance using
   * Guice.  If your project doesn't otherwise use Guice, you can just use Guice.createInjector
   * with only the modules you need, similar to the implementation of this method.
   */
  @SuppressWarnings("deprecation")
  public static Builder builder() {
    Builder builder = new Builder();
    // We inject based on a plain SoyModule, rather than using GuiceInitializer, to avoid relying
    // on whatever lingering static state is around.
    builder.setFactory(
        Guice.createInjector(new SoyModule()).getInstance(SoyFileSetFactory.class));
    return builder;
  }

  /**
   * Builder for a {@code SoyFileSet}.
   */
  public static final class Builder {

    /**
     * Assisted-injection factory. This is optionally injected since many clients inject
     * SoyFileSet.Builder without installing a SoyModule, in which case we need to fall back to
     * static injection.
     */
    private SoyFileSetFactory factory;

    /**
     * The SoyFileSuppliers collected so far in added order, as a set to prevent dupes.
     */
    private final ImmutableMap.Builder<String, SoyFileSupplier> filesBuilder;

    /** Optional AST cache. */
    private SoyAstCache cache;

    /** The general compiler options. */
    private SoyGeneralOptions lazyGeneralOptions;

    /** Type registry for this fileset only. */
    private SoyTypeRegistry localTypeRegistry;

    /**
     * Constructs a builder using a statically-injected configuration.
     *
     * @deprecated Use the static SoyFileSet.builder() method, or  inject SoyFileSet.Builder
     *     using Guice with SoyModule installed. The behavior of this builder is unpredictable and
     *     will use the Soy configuration from the most recently configured Injector containing a
     *     SoyModule, because it relies on Guice's static injection.
     */
    @Inject
    @Deprecated
    public Builder() {
      this.filesBuilder = ImmutableMap.builder();
      this.cache = null;
      this.lazyGeneralOptions = null;
    }

    @Inject(optional = true)
    /** Assigns the factory via Guice. */
    void setFactory(SoyFileSetFactory factory) {
      // Yay, we have Guice, and SoyModule is installed! :-) Inject the factory from the relevant
      // Injector!
      this.factory = factory;
    }

    /**
     * Sets all Soy general options.
     *
     *
This must be called before any other setters.
     */
    public void setGeneralOptions(SoyGeneralOptions generalOptions) {
      Preconditions.checkState(lazyGeneralOptions == null,
          "Call SoyFileSet#setGeneralOptions before any other setters.");
      Preconditions.checkNotNull(generalOptions, "Non-null argument expected.");
      lazyGeneralOptions = generalOptions.clone();
    }

    /**
     * Returns and/or lazily-creates the SoyGeneralOptions for this builder.
     *
     *
Laziness is an important feature to ensure that setGeneralOptions can fail if options were
     * already set.  Otherwise, it'd be easy to set some options on this builder and overwrite them
     * by calling setGeneralOptions.
     */
    private SoyGeneralOptions getGeneralOptions() {
      if (lazyGeneralOptions == null) {
        lazyGeneralOptions = new SoyGeneralOptions();
      }
      return lazyGeneralOptions;
    }

    /**
     * Builds the new {@code SoyFileSet}.
     * @return The new {@code SoyFileSet}.
     */
    public SoyFileSet build() {
      if (factory == null) {
        factory = GuiceInitializer.getHackySoyFileSetFactory();
      }
      return factory.create(
          filesBuilder.build(), cache, getGeneralOptions(), localTypeRegistry);
    }

    /**
     * Adds an input Soy file, given a {@code CharSource} for the file content, as well as the
     * desired file path for messages.
     *
     * @param contentSource Source for the Soy file content.
     * @param soyFileKind The kind of this input Soy file.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder addWithKind(
        CharSource contentSource, SoyFileKind soyFileKind, String filePath) {
      return addFile(SoyFileSupplier.Factory.create(contentSource, soyFileKind, filePath));
    }

    /**
     * Adds an input Soy file, given a {@code CharSource} for the file content, as well as the
     * desired file path for messages.
     *
     * @param contentSource Source for the Soy file content.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder add(CharSource contentSource, String filePath) {
      return addWithKind(contentSource, SoyFileKind.SRC, filePath);
    }

    /**
     * Adds an input Soy file, given a {@code File}.
     *
     * @param inputFile The Soy file.
     * @param soyFileKind The kind of this input Soy file.
     * @return This builder.
     */
    public Builder addWithKind(File inputFile, SoyFileKind soyFileKind) {
      return addFile(SoyFileSupplier.Factory.create(inputFile, soyFileKind));
    }

    /**
     * Adds an input Soy file, given a {@code File}.
     *
     * @param inputFile The Soy file.
     * @return This builder.
     */
    public Builder add(File inputFile) {
      return addWithKind(inputFile, SoyFileKind.SRC);
    }

    /**
     * Adds an input Soy file that supports checking for modifications, given a {@code File}.
     *
     *
Note: This does nothing by itself. It should be used in conjunction with a feature that
     * actually checks for volatile files. Currently, that feature is
     * {@link #setSoyAstCache(SoyAstCache)}.
     *
     * @param inputFile The Soy file.
     * @param soyFileKind The kind of this input Soy file.
     * @return This builder.
     */
    public Builder addVolatileWithKind(File inputFile, SoyFileKind soyFileKind) {
      return addFile(new VolatileSoyFileSupplier(inputFile, soyFileKind));
    }

    /**
     * Adds an input Soy file that supports checking for modifications, given a {@code File}.
     *
     *
Note: This does nothing by itself. It should be used in conjunction with a feature that
     * actually checks for volatile files. Currently, that feature is
     * {@link #setSoyAstCache(SoyAstCache)}.
     *
     * @param inputFile The Soy file.
     * @return This builder.
     */
    public Builder addVolatile(File inputFile) {
      return addVolatileWithKind(inputFile, SoyFileKind.SRC);
    }

    /**
     * Adds an input Soy file, given a resource {@code URL}, as well as the desired file path for
     * messages.
     *
     * @param inputFileUrl The Soy file.
     * @param soyFileKind The kind of this input Soy file.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder addWithKind(URL inputFileUrl, SoyFileKind soyFileKind, String filePath) {
      return addFile(SoyFileSupplier.Factory.create(inputFileUrl, soyFileKind, filePath));
    }

    /**
     * Adds an input Soy file, given a resource {@code URL}, as well as the desired file path for
     * messages.
     *
     * @param inputFileUrl The Soy file.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder add(URL inputFileUrl, String filePath) {
      return addWithKind(inputFileUrl, SoyFileKind.SRC, filePath);
    }

    /**
     * Adds an input Soy file, given a resource {@code URL}.
     *
     *
 Important: This function assumes that the desired file path is returned by
     * {@code inputFileUrl.toString()}. If this is not the case, please use
     * {@link #addWithKind(URL, SoyFileKind, String)} instead.
     *
     * @see #addWithKind(URL, SoyFileKind, String)
     * @param inputFileUrl The Soy file.
     * @param soyFileKind The kind of this input Soy file.
     * @return This builder.
     */
    public Builder addWithKind(URL inputFileUrl, SoyFileKind soyFileKind) {
      return addFile(SoyFileSupplier.Factory.create(inputFileUrl, soyFileKind));
    }

    /**
     * Adds an input Soy file, given a resource {@code URL}.
     *
     *
 Important: This function assumes that the desired file path is returned by
     * {@code inputFileUrl.toString()}. If this is not the case, please use
     * {@link #add(URL, String)} instead.
     *
     * @see #add(URL, String)
     * @param inputFileUrl The Soy file.
     * @return This builder.
     */
    public Builder add(URL inputFileUrl) {
      return addWithKind(inputFileUrl, SoyFileKind.SRC);
    }

    /**
     * Adds an input Soy file, given the file content provided as a string, as well as the desired
     * file path for messages.
     *
     * @param content The Soy file content.
     * @param soyFileKind The kind of this input Soy file.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder addWithKind(CharSequence content, SoyFileKind soyFileKind, String filePath) {
      return addFile(SoyFileSupplier.Factory.create(content, soyFileKind, filePath));
    }

    /**
     * Adds an input Soy file, given the file content provided as a string, as well as the desired
     * file path for messages.
     *
     * @param content The Soy file content.
     * @param filePath The path to the Soy file (used for messages only).
     * @return This builder.
     */
    public Builder add(CharSequence content, String filePath) {
      return addWithKind(content, SoyFileKind.SRC, filePath);
    }

    /**
     * Configures to use an AST cache to speed up development time.
     *
     *
This is undesirable in production mode since it uses strictly more memory, and this only
     * helps if the same templates are going to be recompiled frequently.
     *
     * @param cache The cache to use, which can have a lifecycle independent of the SoyFileSet.
     *     Null indicates not to use a cache.
     * @return This builder.
     */
    public Builder setSoyAstCache(SoyAstCache cache) {
      this.cache = cache;
      return this;
    }

    /**
     * Sets the user-declared syntax version name for the Soy file bundle.
     * @param versionName The syntax version name, e.g. "1.0", "2.0", "2.3".
     */
    public Builder setDeclaredSyntaxVersionName(@Nonnull String versionName) {
      getGeneralOptions().setDeclaredSyntaxVersionName(versionName);
      return this;
    }

    /**
     * Sets whether to allow external calls (calls to undefined templates).
     *
     * @param allowExternalCalls Whether to allow external calls (calls to undefined templates).
     * @return This builder.
     */
    public Builder setAllowExternalCalls(boolean allowExternalCalls) {
      getGeneralOptions().setAllowExternalCalls(allowExternalCalls);
      return this;
    }

    /**
     * Sets whether to force strict autoescaping. Enabling will cause compile time exceptions if
     * non-strict autoescaping is used in namespaces or templates.
     *
     * @param strictAutoescapingRequired Whether strict autoescaping is required.
     * @return This builder.
     */
    public Builder setStrictAutoescapingRequired(boolean strictAutoescapingRequired) {
      getGeneralOptions().setStrictAutoescapingRequired(strictAutoescapingRequired);
      return this;
    }

    /**
     * Sets the map from compile-time global name to value.
     *
     *
 The values can be any of the Soy primitive types: null, boolean, integer, float (Java
     * double), or string.
     *
     * @param compileTimeGlobalsMap Map from compile-time global name to value. The values can be
     *     any of the Soy primitive types: null, boolean, integer, float (Java double), or string.
     * @return This builder.
     * @throws SoySyntaxException If one of the values is not a valid Soy primitive type.
     */
    public Builder setCompileTimeGlobals(Map<String, ?> compileTimeGlobalsMap) {
      getGeneralOptions().setCompileTimeGlobals(compileTimeGlobalsMap);
      return this;
    }

    /**
     * Sets the file containing compile-time globals.
     *
     *
 Each line of the file should have the format
     *

     *     <global_name> = <primitive_data>
     *

     * where primitive_data is a valid Soy expression literal for a primitive type (null, boolean,
     * integer, float, or string). Empty lines and lines beginning with "//" are ignored. The file
     * should be encoded in UTF-8.
     *
     *
 If you need to generate a file in this format from Java, consider using the utility
     * {@code SoyUtils.generateCompileTimeGlobalsFile()}.
     *
     * @param compileTimeGlobalsFile The file containing compile-time globals.
     * @return This builder.
     * @throws IOException If there is an error reading the compile-time globals file.
     */
    public Builder setCompileTimeGlobals(File compileTimeGlobalsFile) throws IOException {
      getGeneralOptions().setCompileTimeGlobals(compileTimeGlobalsFile);
      return this;
    }

    /**
     * Sets the resource file containing compile-time globals.
     *
     *
 Each line of the file should have the format
     *

     *     <global_name> = <primitive_data>
     *

     * where primitive_data is a valid Soy expression literal for a primitive type (null, boolean,
     * integer, float, or string). Empty lines and lines beginning with "//" are ignored. The file
     * should be encoded in UTF-8.
     *
     *
 If you need to generate a file in this format from Java, consider using the utility
     * {@code SoyUtils.generateCompileTimeGlobalsFile()}.
     *
     * @param compileTimeGlobalsResource The resource containing compile-time globals.
     * @return This builder.
     * @throws IOException If there is an error reading the compile-time globals file.
     */
    public Builder setCompileTimeGlobals(URL compileTimeGlobalsResource) throws IOException {
      getGeneralOptions().setCompileTimeGlobals(compileTimeGlobalsResource);
      return this;
    }

    /**
     * Pass true to enable CSP (Content Security Policy) support which adds an extra pass that marks
     * inline scripts in templates specially so the browser can distinguish scripts written by
     * trusted template authors from scripts injected via XSS.
     *

     * Scripts are marked using a per-page-render secret stored in the injected variable
     * {@code $ij.csp_nonce}.
     * Scripts in non-contextually auto-escaped templates may not be found.
     */
    public Builder setSupportContentSecurityPolicy(boolean supportContentSecurityPolicy) {
      getGeneralOptions().setSupportContentSecurityPolicy(supportContentSecurityPolicy);
      return this;
    }

    /**
     * Override the global type registry with one that is local to this file set.
     */
    public Builder setLocalTypeRegistry(SoyTypeRegistry typeRegistry) {
      localTypeRegistry = typeRegistry;
      return this;
    }

    private Builder addFile(SoyFileSupplier supplier) {
      filesBuilder.put(supplier.getFilePath(), supplier);
      return this;
    }
  }

  /**
   * Injectable factory for creating an instance of this class.
   */
  public interface SoyFileSetFactory {

    /**
     * @param soyFileSuppliers The suppliers for the input Soy files.
     * @param cache Optional (nullable) AST cache for faster recompile times.
     * @param options The general compiler options.
     */
    SoyFileSet create(
        ImmutableMap<String, SoyFileSupplier> soyFileSuppliers,
        SoyAstCache cache,
        SoyGeneralOptions options,
        @Assisted("localTypeRegistry") SoyTypeRegistry localTypeRegistry);
  }

  /** Default SoyMsgBundleHandler uses the XLIFF message plugin. */
  private static final Provider<SoyMsgBundleHandler> DEFAULT_SOY_MSG_BUNDLE_HANDLER_PROVIDER =
      Providers.of(new SoyMsgBundleHandler(new XliffMsgPlugin()));

  /** Provider for getting an instance of SoyMsgBundleHandler. */
  private Provider<SoyMsgBundleHandler> msgBundleHandlerProvider;

  /** Factory for creating an instance of BaseTofu. */
  private final BaseTofuFactory baseTofuFactory;

  /** Factory for creating an instance of BaseTofu. */
  private final SoySauceImpl.Factory soyTemplatesFactory;

  /** Provider for getting an instance of JsSrcMain. */
  private final Provider<JsSrcMain> jsSrcMainProvider;

  /** Provider for getting an instance of IncrementalDomSrcMain. */
  private final Provider<IncrementalDomSrcMain> incrementalDomSrcMainProvider;

  /** Provider for getting an instance of PySrcMain. */
  private final Provider<PySrcMain> pySrcMainProvider;

  /** The instance of ContextualAutoescaper to use. */
  private final ContextualAutoescaper contextualAutoescaper;

  /** The instance of SimplifyVisitor to use. */
  private final SimplifyVisitor simplifyVisitor;

  /** The type registry for resolving type names. */
  private final SoyTypeRegistry typeRegistry;

  /** The suppliers for the input Soy files. */
  private final ImmutableMap<String, SoyFileSupplier> soyFileSuppliers;

  /** Optional soy tree cache for faster recompile times. */
  private final SoyAstCache cache;

  /** The general compiler options. */
  private final SoyGeneralOptions generalOptions;

  private CheckConformance checkConformance;

  /** For private use by pruneTranslatedMsgs(). */
  private ImmutableSet<Long> memoizedExtractedMsgIdsForPruning;

  private final ImmutableMap<String, ? extends SoyFunction> soyFunctionMap;
  private final ImmutableMap<String, ? extends SoyPrintDirective> printDirectives;

  /** For reporting errors during parsing. */
  private ErrorReporterImpl errorReporter;

  /**
   * @param baseTofuFactory Factory for creating an instance of BaseTofu.
   * @param jsSrcMainProvider Provider for getting an instance of JsSrcMain.
   * @param incrementalDomSrcMainProvider Provider for getting an instance of IncrementalDomSrcMain.
   * @param pySrcMainProvider Provider for getting an instance of PySrcMain.
   * @param contextualAutoescaper The instance of ContextualAutoescaper to use.
   * @param simplifyVisitor The instance of SimplifyVisitor to use.
   * @param typeRegistry The type registry to resolve parameter type names.
   * @param soyFileSuppliers The suppliers for the input Soy files.
   * @param generalOptions The general compiler options.
   * @param localTypeRegistry If non-null, use this local type registry instead
   *        of the typeRegistry param which is a global singleton.
   *        (Unfortunately because of the way assisted injection works, we need
   *        the global and local registries to be separate parameters).
   */
  @Inject
  SoyFileSet(
      BaseTofuFactory baseTofuFactory,
      SoySauceImpl.Factory soyTemplatesFactory,
      Provider<JsSrcMain> jsSrcMainProvider,
      Provider<IncrementalDomSrcMain> incrementalDomSrcMainProvider,
      Provider<PySrcMain> pySrcMainProvider,
      ContextualAutoescaper contextualAutoescaper,
      SimplifyVisitor simplifyVisitor,
      SoyTypeRegistry typeRegistry,
      ImmutableMap<String, ? extends SoyFunction> soyFunctionMap,
      ImmutableMap<String, ? extends SoyPrintDirective> printDirectives,
      @Assisted ImmutableMap<String, SoyFileSupplier> soyFileSuppliers,
      @Assisted SoyGeneralOptions generalOptions,
      @Assisted @Nullable SoyAstCache cache,
      @Assisted("localTypeRegistry") @Nullable SoyTypeRegistry localTypeRegistry) {

    // Default value is optionally replaced using method injection.
    this.msgBundleHandlerProvider = DEFAULT_SOY_MSG_BUNDLE_HANDLER_PROVIDER;
    this.soyTemplatesFactory = soyTemplatesFactory;
    this.baseTofuFactory = baseTofuFactory;
    this.jsSrcMainProvider = jsSrcMainProvider;
    this.incrementalDomSrcMainProvider = incrementalDomSrcMainProvider;
    this.pySrcMainProvider = pySrcMainProvider;
    this.contextualAutoescaper = contextualAutoescaper;
    this.simplifyVisitor = simplifyVisitor;

    Preconditions.checkArgument(
        !soyFileSuppliers.isEmpty(), "Must have non-zero number of input Soy files.");
    this.typeRegistry = localTypeRegistry != null ? localTypeRegistry : typeRegistry;
    this.soyFileSuppliers = soyFileSuppliers;
    this.cache = cache;
    this.generalOptions = generalOptions.clone();
    this.soyFunctionMap = soyFunctionMap;
    this.printDirectives = printDirectives;
  }

  /** @param msgBundleHandlerProvider Provider for getting an instance of SoyMsgBundleHandler. */
  @Inject(optional = true)
  void setMsgBundleHandlerProvider(Provider<SoyMsgBundleHandler> msgBundleHandlerProvider) {
    this.msgBundleHandlerProvider = msgBundleHandlerProvider;
  }

  @Inject(optional = true)
  void setCheckConformance(CheckConformance checkConformance) {
    this.checkConformance = checkConformance;
  }

  /** Returns the list of suppliers for the input Soy files. For testing use only! */
  @VisibleForTesting ImmutableMap<String, SoyFileSupplier> getSoyFileSuppliersForTesting() {
    return soyFileSuppliers;
  }

  /** Returns the general compiler options. For testing use only! */
  @VisibleForTesting SoyGeneralOptions getOptionsForTesting() {
    return generalOptions;
  }

  /**
   * Generates Java classes containing parse info (param names, template names, meta info). There
   * will be one Java class per Soy file.
   *
   * @param javaPackage The Java package for the generated classes.
   * @param javaClassNameSource Source of the generated class names. Must be one of "filename",
   *     "namespace", or "generic".
   * @return A map from generated file name (of the form "<*>SoyInfo.java") to generated file
   *     content.
   * @throws SoyCompilationException If compilation fails.
   */
  ImmutableMap<String, String> generateParseInfo(String javaPackage, String javaClassNameSource) {
    resetErrorReporter();
    // TODO(lukes): see if we can enforce that globals are provided at compile time here. given that
    // types have to be, this should be possible.  Currently it is disabled for backwards
    // compatibility
    ParseResult result =
        parse(
            SyntaxVersion.V2_0,
            true /* allow unknown globals */,
            true /* allow unknown functions */,
            typeRegistry,
            soyFunctionMap);

    SoyFileSetNode soyTree = result.fileSet();
    TemplateRegistry registry = result.registry();
    registry = runMiddleendPasses(registry, soyTree);

    // Do renaming of package-relative class names.
    ImmutableMap<String, String> parseInfo =
        new GenerateParseInfoVisitor(javaPackage, javaClassNameSource, registry).exec(soyTree);
    throwIfErrorsPresent();
    return parseInfo;
  }

  /**
   * Extracts all messages from this Soy file set into a SoyMsgBundle (which can then be turned
   * into an extracted messages file with the help of a SoyMsgBundleHandler).
   *
   * @return A SoyMsgBundle containing all the extracted messages (locale "en").
   * @throws SoyCompilationException If compilation fails.
   */
  public SoyMsgBundle extractMsgs() {
    resetErrorReporter();
    SoyFileSetNode soyTree =
        parse(
                SyntaxVersion.V1_0,
                true /* allow unknown globals */,
                true /* allow unknown functions */,
                SoyTypeRegistry.DEFAULT_UNKNOWN,
                soyFunctionMap)
            .fileSet();
    SoyMsgBundle bundle = new ExtractMsgsVisitor().exec(soyTree);
    // TODO(lukes): this should call throwIfErrorsPresent(), but can't because it will break
    // build rules.
    return bundle;
  }

  /**
   * Prunes messages from a given message bundle, keeping only messages used in this Soy file set.
   *
   *
 Important: Do not use directly. This is subject to change and your code will break.
   *
   *
 Note: This method memoizes intermediate results to improve efficiency in the case that it
   * is called multiple times (which is a common case). Thus, this method will not work correctly if
   * the underlying Soy files are modified between calls to this method.
   *
   * @param origTransMsgBundle The message bundle to prune.
   * @return The pruned message bundle.
   * @throws SoyCompilationException If compilation fails.
   */
  public SoyMsgBundle pruneTranslatedMsgs(SoyMsgBundle origTransMsgBundle) {
    resetErrorReporter();
    // ------ Extract msgs from all the templates reachable from public templates. ------
    // Note: In the future, instead of using all public templates as the root set, we can allow the
    // user to provide a root set.

    if (memoizedExtractedMsgIdsForPruning == null) {
      ParseResult result =
          parse(
              SyntaxVersion.V1_0,
              true /* allow unknown globals */,
              true /* allow unknown functions */,
              SoyTypeRegistry.DEFAULT_UNKNOWN,
              soyFunctionMap);

      SoyFileSetNode soyTree = result.fileSet();
      TemplateRegistry registry = result.registry();

      List<TemplateNode> allPublicTemplates = Lists.newArrayList();
      for (SoyFileNode soyFile : soyTree.getChildren()) {
        for (TemplateNode template : soyFile.getChildren()) {
          if (template.getVisibility() == Visibility.PUBLIC) {
            allPublicTemplates.add(template);
          }
        }
      }
      Map<TemplateNode, TransitiveDepTemplatesInfo> depsInfoMap =
          new FindTransitiveDepTemplatesVisitor(registry)
              .execOnMultipleTemplates(allPublicTemplates);
      TransitiveDepTemplatesInfo mergedDepsInfo =
          TransitiveDepTemplatesInfo.merge(depsInfoMap.values());

      SoyMsgBundle extractedMsgBundle = new ExtractMsgsVisitor()
          .execOnMultipleNodes(mergedDepsInfo.depTemplateSet);

      ImmutableSet.Builder<Long> extractedMsgIdsBuilder = ImmutableSet.builder();
      for (SoyMsg extractedMsg : extractedMsgBundle) {
        extractedMsgIdsBuilder.add(extractedMsg.getId());
      }
      memoizedExtractedMsgIdsForPruning = extractedMsgIdsBuilder.build();
    }

    // ------ Prune. ------

    ImmutableList.Builder<SoyMsg> prunedTransMsgsBuilder = ImmutableList.builder();
    for (SoyMsg transMsg : origTransMsgBundle) {
      if (memoizedExtractedMsgIdsForPruning.contains(transMsg.getId())) {
        prunedTransMsgsBuilder.add(transMsg);
      }
    }
    // TODO(lukes): this should call throwIfErrorsPresent(), but can't because it will break
    // build rules.
    return new SoyMsgBundleImpl(
        origTransMsgBundle.getLocaleString(), prunedTransMsgsBuilder.build());
  }

  /**
   * Compiles this Soy file set into a Java object (type {@code SoyTofu}) capable of rendering the
   * compiled templates.
   *
   * @return The resulting {@code SoyTofu} object.
   * @throws SoyCompilationException If compilation fails.
   */
  public SoyTofu compileToTofu() {
    resetErrorReporter();
    ServerCompilationPrimitives primitives = compileForServerRendering();
    throwIfErrorsPresent();
    return doCompileToTofu(primitives);
  }

  /** Helper method to compile SoyTofu from {@link ServerCompilationPrimitives} */
  private SoyTofu doCompileToTofu(ServerCompilationPrimitives primitives) {
    return baseTofuFactory.create(
        primitives.registry,
        getTransitiveIjs(primitives.soyTree, primitives.registry),
        printDirectives);
  }

  /**
   * This is an extremely experimental API and subject to change.  Not all features of soy
   * are implemented in this new backend and the features that are implemented are not necessarily
   * correct!
   *
   *
See com/google/template/soy/jbcsrc/README.md for background on this new backend.
   *
   *
Compiles this Soy file set into a set of java classes implementing the
   * {@link CompiledTemplate} interface.
   *
   * @return A set of compiled templates
   * @throws SoyCompilationException If compilation fails.
   */
  public SoySauce compileTemplates() {
    resetErrorReporter();
    disallowExternalCalls();
    ServerCompilationPrimitives primitives = compileForServerRendering();
    throwIfErrorsPresent();
    return doCompileSoySauce(primitives);
  }

  /**
   *
Compiles this Soy file set into a set of java classes implementing the
   * {@link CompiledTemplate} interface and writes them out to the given ByteSink as a JAR file.
   *
   * @throws SoyCompilationException If compilation fails.
   */
  void compileToJar(ByteSink jarTarget, Optional<ByteSink> srcJarTarget) throws IOException {
    resetErrorReporter();
    disallowExternalCalls();
    ServerCompilationPrimitives primitives = compileForServerRendering();
    BytecodeCompiler.compileToJar(primitives.registry, errorReporter, jarTarget);
    if (srcJarTarget.isPresent()) {
      BytecodeCompiler.writeSrcJar(primitives.registry, soyFileSuppliers, srcJarTarget.get());
    }
    throwIfErrorsPresent();
  }

  /** Helper method to compile SoySauce from {@link ServerCompilationPrimitives} */
  private SoySauce doCompileSoySauce(ServerCompilationPrimitives primitives) {
    Optional<CompiledTemplates> templates =
        BytecodeCompiler.compile(
            primitives.registry,
            // if there is an AST cache, assume we are in 'dev mode' and trigger lazy compilation.
            cache != null,
            errorReporter);

    throwIfErrorsPresent();

    return soyTemplatesFactory.create(templates.get(), soyFunctionMap, printDirectives);
  }

  /**
   * A tuple of the outputs of shared compiler passes that are needed to produce SoyTofu or
   * SoySauce.
   */
  private static final class ServerCompilationPrimitives {
    final SoyFileSetNode soyTree;
    final TemplateRegistry registry;

    ServerCompilationPrimitives(TemplateRegistry registry, SoyFileSetNode soyTree) {
      this.registry = registry;
      this.soyTree = soyTree;
    }
  }

  /**
   * Runs common compiler logic shared by tofu and jbcsrc backends.
   */
  private ServerCompilationPrimitives compileForServerRendering() {
    ParseResult result = parse(SyntaxVersion.V2_0);
    throwIfErrorsPresent();

    SoyFileSetNode soyTree = result.fileSet();
    TemplateRegistry registry = result.registry();
    registry = runMiddleendPasses(registry, soyTree);

    // Clear the SoyDoc strings because they use unnecessary memory, unless we have a cache, in
    // which case it is pointless.
    if (cache == null) {
      new ClearSoyDocStringsVisitor().exec(soyTree);
    }

    throwIfErrorsPresent();
    return new ServerCompilationPrimitives(registry, soyTree);
  }

  private ImmutableMap<String, ImmutableSortedSet<String>> getTransitiveIjs(
      SoyFileSetNode soyTree, TemplateRegistry registry) {
    ImmutableMap<TemplateNode, IjParamsInfo> templateToIjParamsInfoMap =
        new FindIjParamsVisitor(registry)
            .execOnAllTemplates(soyTree);
    ImmutableMap.Builder<String, ImmutableSortedSet<String>> templateToTransitiveIjParams =
        ImmutableMap.builder();
    for (Map.Entry<TemplateNode, IjParamsInfo> entry : templateToIjParamsInfoMap.entrySet()) {
      templateToTransitiveIjParams.put(
          entry.getKey().getTemplateName(), entry.getValue().ijParamSet);
    }
    return templateToTransitiveIjParams.build();
  }

  private void disallowExternalCalls() {
    Boolean allowExternalCalls = generalOptions.allowExternalCalls();
    if (allowExternalCalls == null) {
      generalOptions.setAllowExternalCalls(false);
    } else if (allowExternalCalls) {
      throw new IllegalStateException(
          "SoyGeneralOptions.setAllowExternalCalls(true) is not supported with this method");
    }
    // otherwise, it was already explicitly set to false which is what we want.
  }

  /**
   * Compiles this Soy file set into JS source code files and returns these JS files as a list of
   * strings, one per file.
   *
   * @param jsSrcOptions The compilation options for the JS Src output target.
   * @param msgBundle The bundle of translated messages, or null to use the messages from the Soy
   *     source.
   * @return A list of strings where each string represents the JS source code that belongs in one
   *     JS file. The generated JS files correspond one-to-one to the original Soy source files.
   * @throws SoyCompilationException If compilation fails.
   */
  @SuppressWarnings("deprecation")
  public List<String> compileToJsSrc(
      SoyJsSrcOptions jsSrcOptions, @Nullable SoyMsgBundle msgBundle) {
    resetErrorReporter();

    // Synchronize old and new ways to declare syntax version V1.
    if (jsSrcOptions.shouldAllowDeprecatedSyntax()) {
      generalOptions.setDeclaredSyntaxVersionName("1.0");
    }
    // JS has traditionally allowed unknown globals, as a way for soy to reference normal js enums
    // and constants.  For consistency/reusability of templates it would be nice to not allow that
    // but the cat is out of the bag.
    ParseResult parseResult =
        parse(
            SyntaxVersion.V2_0,
            true /* allow unknown globals */,
            false /* allow unknown functions */,
            typeRegistry,
            soyFunctionMap);
    throwIfErrorsPresent();
    TemplateRegistry registry = parseResult.registry();
    SoyFileSetNode fileSet = parseResult.fileSet();
    registry = runMiddleendPasses(registry, fileSet);
    throwIfErrorsPresent();
    List<String> generatedSrcs = jsSrcMainProvider
        .get()
        .genJsSrc(fileSet, registry, jsSrcOptions, msgBundle, errorReporter);
    throwIfErrorsPresent();
    return generatedSrcs;
  }

  /**
   * Compiles this Soy file set into JS source code files and writes these JS files to disk.
   *
   * @param outputPathFormat The format string defining how to build the output file path
   *     corresponding to an input file path.
   * @param inputFilePathPrefix The prefix prepended to all input file paths (can be empty string).
   * @param jsSrcOptions The compilation options for the JS Src output target.
   * @param locales The list of locales. Can be an empty list if not applicable.
   * @param messageFilePathFormat The message file path format, or null if not applicable.
   * @throws SoyCompilationException If compilation fails.
   * @throws IOException If there is an error in opening/reading a message file or opening/writing
   *     an output JS file.
   */
  @SuppressWarnings("deprecation")
  void compileToJsSrcFiles(
      String outputPathFormat,
      String inputFilePathPrefix,
      SoyJsSrcOptions jsSrcOptions,
      List<String> locales,
      @Nullable String messageFilePathFormat)
      throws IOException {
    resetErrorReporter();

    // Synchronize old and new ways to declare syntax version V1.
    if (jsSrcOptions.shouldAllowDeprecatedSyntax()) {
      generalOptions.setDeclaredSyntaxVersionName("1.0");
    }

    // Allow unknown globals for backwards compatibility
    ParseResult result =
        parse(
            SyntaxVersion.V2_0,
            true /* allow unknown globals */,
            false /* allow unknown functions */,
            typeRegistry,
            soyFunctionMap);
    throwIfErrorsPresent();

    SoyFileSetNode soyTree = result.fileSet();
    TemplateRegistry registry = result.registry();
    registry = runMiddleendPasses(registry, soyTree);
    throwIfErrorsPresent();
    if (locales.isEmpty()) {
      // Not generating localized JS.
      jsSrcMainProvider
          .get()
          .genJsFiles(
              soyTree,
              registry,
              jsSrcOptions,
              null,
              null,
              outputPathFormat,
              inputFilePathPrefix,
              errorReporter);

    } else {
      // Generating localized JS.
      for (String locale : locales) {

        SoyFileSetNode soyTreeClone = SoytreeUtils.cloneNode(soyTree);

        String msgFilePath = MainEntryPointUtils.buildFilePath(
            messageFilePathFormat, locale, null, inputFilePathPrefix);

        SoyMsgBundle msgBundle =
            msgBundleHandlerProvider.get().createFromFile(new File(msgFilePath));
        if (msgBundle.getLocaleString() == null) {
          // TODO: Remove this check (but make sure no projects depend on this behavior).
          // There was an error reading the message file. We continue processing only if the locale
          // begins with "en", because falling back to the Soy source will probably be fine.
          if (!locale.startsWith("en")) {
            throw new IOException("Error opening or reading message file " + msgFilePath);
          }
        }

        jsSrcMainProvider
            .get()
            .genJsFiles(
                soyTreeClone,
                registry,
                jsSrcOptions,
                locale,
                msgBundle,
                outputPathFormat,
                inputFilePathPrefix,
                errorReporter);
      }
    }
    throwIfErrorsPresent();
  }

  /**
   * Compiles this Soy file set into JS source code files and writes these JS files to disk.
   *
   * @param outputPathFormat The format string defining how to build the output file path
   *     corresponding to an input file path.
   * @param jsSrcOptions The compilation options for the JS Src output target.
   * @throws SoyCompilationException If compilation fails.
   * @throws IOException If there is an error in opening/reading a message file or opening/writing
   *     an output JS file.
   */
  @SuppressWarnings("deprecation")
  void compileToIncrementalDomSrcFiles(String outputPathFormat, SoyJsSrcOptions jsSrcOptions)
      throws IOException {
    resetErrorReporter();
    SyntaxVersion declaredSyntaxVersion =
        generalOptions.getDeclaredSyntaxVersion(SyntaxVersion.V2_0);

    Preconditions.checkState(
        declaredSyntaxVersion.num >= SyntaxVersion.V2_0.num,
        "Incremental DOM code generation only supports syntax version of V2 or higher.");

    ParseResult result = parse(SyntaxVersion.V2_0);

    throwIfErrorsPresent();
    SoyFileSetNode soyTree = result.fileSet();
    new ChangeCallsToPassAllDataVisitor().exec(soyTree);
    simplifyVisitor.simplify(soyTree, result.registry());

    throwIfErrorsPresent();

    incrementalDomSrcMainProvider
        .get()
        .genJsFiles(soyTree, result.registry(), jsSrcOptions, outputPathFormat, errorReporter);

    throwIfErrorsPresent();
  }

  /**
   * Compiles this Soy file set into Python source code files and writes these Python files to
   * disk.
   *
   * @param outputPathFormat The format string defining how to build the output file path
   *     corresponding to an input file path.
   * @param inputFilePathPrefix The prefix prepended to all input file paths (can be empty string).
   * @param pySrcOptions The compilation options for the Python Src output target.
   * @throws SoyCompilationException If compilation fails.
   * @throws IOException If there is an error in opening/reading a message file or opening/writing
   *     an output JS file.
   */
  void compileToPySrcFiles(
      String outputPathFormat, String inputFilePathPrefix, SoyPySrcOptions pySrcOptions)
      throws IOException {
    resetErrorReporter();

    ParseResult result = parse(SyntaxVersion.V2_0);
    throwIfErrorsPresent();
    SoyFileSetNode soyTree = result.fileSet();

    TemplateRegistry registry = result.registry();
    registry = runMiddleendPasses(registry, result.fileSet());
    throwIfErrorsPresent();

    pySrcMainProvider
        .get()
        .genPyFiles(
            soyTree, registry, pySrcOptions, outputPathFormat, inputFilePathPrefix, errorReporter);

    throwIfErrorsPresent();
  }

  // Parse the current file set with the given default syntax version.
  private ParseResult parse(SyntaxVersion defaultVersion) {
    return parse(
        defaultVersion,
        false /* allow unknown globals */,
        false /* allow unknown functions */,
        typeRegistry,
        soyFunctionMap);
  }

  /**
   * A parse method that allows disabling certain features.  All callers should prefer the
   * {@link #parse(SyntaxVersion)} overload whenever possible.
   *
   * @param defaultVersion The default declared syntax version
   * @param allowUknownGlobals Whether to allow unknown globals
   * @param typeRegistry The type registry to use
   * @param soyFunctionMap The map of Soy functions to use
   */
  private ParseResult parse(
      SyntaxVersion defaultVersion,
      boolean allowUknownGlobals,
      boolean allowUknownFunctions,
      SoyTypeRegistry typeRegistry,
      ImmutableMap<String, ? extends SoyFunction> soyFunctionMap) {
    SyntaxVersion declaredSyntaxVersion = generalOptions.getDeclaredSyntaxVersion(defaultVersion);
    PassManager.Builder builder =
        new PassManager.Builder()
            .setTypeRegistry(typeRegistry)
            .setGeneralOptions(generalOptions)
            .setDeclaredSyntaxVersion(declaredSyntaxVersion)
            .setSoyFunctionMap(soyFunctionMap)
            .setErrorReporter(errorReporter);
    if (allowUknownGlobals) {
      builder.allowUnknownGlobals();
    }
    if (allowUknownFunctions) {
      builder.allowUnknownFunctions();
    }
    return new SoyFileSetParser(
            typeRegistry,
            cache,
            soyFileSuppliers,
            builder.build(),
            errorReporter)
        .parse();
  }

  // TODO(gboyer): There are several fields on this class that end up saving around some state, and
  // thus are not safe to be used by multiple threads at once. Here, we add synchronized as a
  // stop-gap. However, given that most users of SoyFileSet use it once and throw it away, that
  // might be a better precondition.
  /**
   * Runs middleend passes on the given Soy tree.
   *
   * @param soyTree The Soy tree to run middleend passes on.
   * @return A new TemplateRegistry.  The contextual autoescaper occasionally adds new templates and
   *     so the TemplateRegistry needs to be recreated.
   */
  @CheckReturnValue
  private synchronized TemplateRegistry runMiddleendPasses(
      TemplateRegistry registry, SoyFileSetNode soyTree) {

    // Run contextual escaping after CSS and substitutions have been done.
    doContextualEscaping(soyTree, registry);
    // Further passes that rely on sliced raw text nodes, such as conformance and CSP, can't
    // proceed if contextual escaping failed.
    throwIfErrorsPresent();

    // contextual autoescaping may actually add new templates to the tree so we need to reconstruct
    // the registry
    registry = new TemplateRegistry(soyTree, errorReporter);
    if (checkConformance != null) {
      checkConformance.check(
          ConformanceInput.create(soyTree, contextualAutoescaper.getSlicedRawTextNodes()),
          errorReporter);
    }

    // Add print directives that mark inline-scripts as safe to run.
    if (generalOptions.supportContentSecurityPolicy()) {
      ContentSecurityPolicyPass.blessAuthorSpecifiedScripts(
          contextualAutoescaper.getSlicedRawTextNodes());
    }

    // Attempt to simplify the tree.
    new ChangeCallsToPassAllDataVisitor().exec(soyTree);
    simplifyVisitor.simplify(soyTree, registry);
    return registry;
  }

  private void doContextualEscaping(SoyFileSetNode soyTree, TemplateRegistry registry) {
    List<TemplateNode> extraTemplates =
        contextualAutoescaper.rewrite(soyTree, registry, errorReporter);
    // TODO: Run the redundant template remover here and rename after CL 16642341 is in.
    if (!extraTemplates.isEmpty()) {
      // TODO: pull out somewhere else.  Ideally do the merge as part of the redundant template
      // removal.
      Map<String, SoyFileNode> containingFile = Maps.newHashMap();
      for (SoyFileNode fileNode : soyTree.getChildren()) {
        for (TemplateNode templateNode : fileNode.getChildren()) {
          String name =
              templateNode instanceof TemplateDelegateNode
                  ? ((TemplateDelegateNode) templateNode).getDelTemplateName()
                  : templateNode.getTemplateName();
          containingFile.put(DerivedTemplateUtils.getBaseName(name), fileNode);
        }
      }
      for (TemplateNode extraTemplate : extraTemplates) {
        String name =
            extraTemplate instanceof TemplateDelegateNode
                ? ((TemplateDelegateNode) extraTemplate).getDelTemplateName()
                : extraTemplate.getTemplateName();
        containingFile.get(DerivedTemplateUtils.getBaseName(name)).addChild(extraTemplate);
      }
    }
  }

  /**
   * This method resets the error reporter field in preparation to a new compiler invocation.
   *
   *
This method should be called at the beginning of every entry point into SoyFileSet.
   *
TODO(lukes): instead of resetting, consider making it an error to call a compiler method
   * on the same SoyFileSet object more than once.
   */
  private void resetErrorReporter() {
    // TODO(lukes): consider moving ErrorReporterImpl to the error package and making this a static
    // factory method there somewhere
    errorReporter =
        new ErrorReporterImpl(new PrettyErrorFactory(new SnippetFormatter(soyFileSuppliers)));
  }

  private void throwIfErrorsPresent() {
    if (errorReporter.hasErrors()) {
      Iterable<SoyError> errors = errorReporter.getErrors();
      // clear the field to ensure that error reporters can't leak between compilations
      errorReporter = null;
      throw new SoyCompilationException(errors);
    }
  }
}


text:
{% extends 'artist/base.html' %}

{% block css %}
	<link rel="stylesheet" type="text/css" href="/static/artist/about.css" />
{% endblock %}

{% block title %} About {% endblock %}

{% block page-title %}

 Placeholder title for about

{% endblock %}

{% block navbar %}

 Home

 Gallery

 About

 Contact

{% endblock %}
{% block content %}

 Sample content

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
set -e -x
source ./kube/config.sh

cd docker
docker build -t gcr.io/skia-public/infra:prod .
docker push gcr.io/skia-public/infra:prod


text:
module Yaffle
	module ActsAsYaffle
		extend ActiveSupport::Concern

		included do
		end

		module ClassMethods
			def acts_as_yaffle(options = {})
				cattr_accessor :yaffle_text_field
				self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
			end
		end
	end
end

ActiveRecord::Base.send :include, Yaffle::ActsAsYaffle


text:
cd /Users/egillespie/Projects/technicalrex.com.master
bundle exec jekyll build

cd ../technicalrex.com.gh-pages
rm -rf ./*
cp -r ../technicalrex.com.master/_site/* .


text:
static ScriptCenter *sharedInstance;
static NSConnection *theConnection;

@implementation ScriptCenter
+ (void) initialize
{
	sharedInstance = [ScriptCenter new];
}
+ (ScriptCenter*) sharedInstance
{
	return sharedInstance;
}
- (void) enableScriptingWithObjects:(NSDictionary*) scriptObjects
{
	[dict release];
	dict = [[scriptObjects mutableCopy] retain];
	if (![dict objectForKey:@"Application"])
	{
		[dict setObject:NSApp forKey:@"Application"];
	}

	if (nil != theConnection)
	{
		[theConnection setRootObject:dict];
		return;
	}
	theConnection = [[NSConnection alloc] init];
	[theConnection setRootObject:dict];
	NSString *name = [NSString stringWithFormat:@"Etoile/%@/Scripts",
			 [[NSProcessInfo processInfo] processName]];
	if ([theConnection registerName:name] == NO)
	{
		[NSException raise:@"DOException"
					format:@"Can't register with DO server"];
	}
}
- (void) enableScripting
{
	[self enableScriptingWithObjects:D(NSApp, @"Application")];
}
- (void) scriptObject:(id)anObject withName:(NSString*) aName
{
	[dict setObject:anObject forKey:aName];
}
+ (NSDictionary*) scriptDictionaryForApplication:(NSString*) anApp
{
	NSString *name = [NSString stringWithFormat:@"Etoile/%@/Scripts", anApp];
	id dict = [NSConnection rootProxyForConnectionWithRegisteredName:name
	                                                            host:nil];
	if (nil == dict)
	{
		[[NSWorkspace sharedWorkspace] launchApplication:anApp];
		dict = [NSConnection rootProxyForConnectionWithRegisteredName:name
	                                                             host:nil];
	}
	return dict;
}
+ (NSDictionary*) scriptDictionaryForActiveApplication
{
	NSString *appName = [[[NSWorkspace sharedWorkspace] activeApplication]
		objectForKey: @"NSApplicationName"];
	if (nil == appName)
	{
		return nil;
	}
	return [self scriptDictionaryForApplication:appName];
}
@end


text:
package kafka.cluster

import kafka.common.KafkaException
import org.apache.kafka.common.network.ListenerName
import org.apache.kafka.common.protocol.SecurityProtocol
import org.apache.kafka.common.utils.Utils

import scala.collection.Map

object EndPoint {

  private val uriParseExp = """^(.*)://\[?([0-9a-zA-Z\-%._:]*)\]?:(-?[0-9]+)""".r

  private[kafka] val DefaultSecurityProtocolMap: Map[ListenerName, SecurityProtocol] =
    SecurityProtocol.values.map(sp => ListenerName.forSecurityProtocol(sp) -> sp).toMap

  /**
   * Create EndPoint object from `connectionString` and optional `securityProtocolMap`. If the latter is not provided,
   * we fallback to the default behaviour where listener names are the same as security protocols.
   *
   * @param connectionString the format is listener_name://host:port or listener_name://[ipv6 host]:port
   *                         for example: PLAINTEXT://myhost:9092, CLIENT://myhost:9092 or REPLICATION://[::1]:9092
   *                         Host can be empty (PLAINTEXT://:9092) in which case we'll bind to default interface
   *                         Negative ports are also accepted, since they are used in some unit tests
   */
  def createEndPoint(connectionString: String, securityProtocolMap: Option[Map[ListenerName, SecurityProtocol]]): EndPoint = {
    val protocolMap = securityProtocolMap.getOrElse(DefaultSecurityProtocolMap)

    def securityProtocol(listenerName: ListenerName): SecurityProtocol =
      protocolMap.getOrElse(listenerName,
        throw new IllegalArgumentException(s"No security protocol defined for listener ${listenerName.value}"))

    connectionString match {
      case uriParseExp(listenerNameString, "", port) =>
        val listenerName = ListenerName.normalised(listenerNameString)
        new EndPoint(null, port.toInt, listenerName, securityProtocol(listenerName))
      case uriParseExp(listenerNameString, host, port) =>
        val listenerName = ListenerName.normalised(listenerNameString)
        new EndPoint(host, port.toInt, listenerName, securityProtocol(listenerName))
      case _ => throw new KafkaException(s"Unable to parse $connectionString to a broker endpoint")
    }
  }
}

/**
 * Part of the broker definition - matching host/port pair to a protocol
 */
case class EndPoint(host: String, port: Int, listenerName: ListenerName, securityProtocol: SecurityProtocol) {
  def connectionString: String = {
    val hostport =
      if (host == null)
        ":"+port
      else
        Utils.formatAddress(host, port)
    listenerName.value + "://" + hostport
  }
}


text:
module Kms
  class UserSerializer < ActiveModel::Serializer
    attributes :id, :email, :role, :localized_role
  end
end


text:
test: ./node_modules/.bin/mocha
	$<

./node_modules/.bin/mocha:
	npm install mocha


text:
using System;

namespace Newtonsoft.Json
{
    internal class NumericConverter : JsonConverter
    {
        #region Constructor
        public NumericConverter()
        {
        }
        #endregion

        #region Public Methods
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(long);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return reader.Value ?? (long)0;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteValue(value);
        }
        #endregion
    }
}


text:
CKEDITOR.plugins.setLang( 'image2', 'eu', {
	alt: 'Ordezko Testua',
	btnUpload: 'Zerbitzarira bidalia',
	captioned: 'Captioned image', // MISSING
	captionPlaceholder: 'Caption', // MISSING
	infoTab: 'Irudi informazioa',
	lockRatio: 'Erlazioa Blokeatu',
	menu: 'Irudi Ezaugarriak',
	pathName: 'image', // MISSING
	pathNameCaption: 'caption', // MISSING
	resetSize: 'Tamaina Berrezarri',
	resizer: 'Click and drag to resize', // MISSING
	title: 'Irudi Ezaugarriak',
	uploadTab: 'Gora kargatu',
	urlMissing: 'Irudiaren iturburu URL-a falta da.'
} );


text:
package com.paypal.mesos.executor.utils;

import org.apache.commons.exec.*;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeUnit;

public class ProcessUtils {

    private static Logger log = Logger.getLogger(ProcessUtils.class);

    public static int executeCommand(String command, ExecuteWatchdog watchdog) {
        return executeCommand(command, watchdog, null, null, null);
    }

    public static int executeCommand(String command, ExecuteWatchdog watchdog, OutputStream outputStream, OutputStream errorStream, InputStream inputStream) {
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        if (outputStream == null) {
            outputStream = System.out;
        }
        if (errorStream == null) {
            errorStream = System.err;
        }
        executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream, inputStream));
        executor.setExitValues(new int[]{0, 1});
        if (watchdog != null) {
            executor.setWatchdog(watchdog);
        }
        int exitValue = 0;
        try {
            exitValue = executor.execute(cmdLine);
        } catch (IOException e) {
            exitValue = 1;
            log.error("error executing command", e);
        }

        return exitValue;
    }

    public static ExecuteWatchdog createTimeoutWatchdog(TimeUnit timeunit, int timeout) {
        ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeunit.toMillis(timeout));
        return timeoutWatchdog;
    }

    public static boolean isProcessRunning(int pid) {
        String line;
        if (OS.isFamilyWindows()) {
            line = "cmd /c \"tasklist /FI \"PID eq " + pid + "\" | findstr " + pid + "\"";
        } else {
            line = "ps -p " + pid;
        }
        int exitValue = ProcessUtils.executeCommand(line, null);
        return exitValue == 0;
    }

}


text:
<list>
  <codeTemplate version="3.2.0">
    <id>270003aa-9350-45a7-9397-58679320cb9d</id>
    <name>Get Segments After a Particular Segment</name>
    <tooltip>Returns an array of segments with the specified name that come after a given segment in the message.</tooltip>
    /*
	Author: Nick Rupley
	Date Modified: 2/13/2013
	getSegmentsAfter: Returns an array of segments with the specified name that come after a given segment in the message.

	Arguments
	---------
		Required
		--------
			root:			The root HL7Message node of the message, or the parent of the segment node.
			startSeg:		The segment AFTER which to start collecting segments.
			segName:		The name (String or RegExp) of the segments you want to collect.

		Optional
		--------
			consecutiveInd:	If true, indicates that the segments are expected to come directly after startSeg.
							If false, segments are collected until another segment with the same name as startSeg is encountered.
							Defaults to false.
			stopSegNames:	An array of segment names that, when encountered, stop the collection of segments.
*/

function getSegmentsAfter(root, startSeg, segName, consecutiveInd, stopSegNames) {
	function test(str) {
		return segName instanceof RegExp ? segName.test(str) : segName === str;
	}

	// The index to start collection is the next one up from the starting segment
	var index = startSeg.childIndex()+1;
	// The return array
	var out = [];
	// Boolean placeholder to stop iteration
	var done = false;
	// Object that will contain all of the stopSegNames strings, bound to a truthy value (1)
	var stopNames = {};
	// Indicates whether we have any stop segments
	var stopNamesInd = false;
	// If stopSegNames is defined
	if (stopSegNames !== undefined && stopSegNames !== null) {
		// Set our indicator to true
		stopNamesInd = true;
		// Add each string in the array to our object
		for each (name in stopSegNames)
			stopNames[name] = 1;
	}

	// Iterate through each child in the root, starting at the segment after startSeg, and
	// ending at the final segment, or when the done flag is set to true.
	while (index < root.children().length() && !done) {
		// If a stop segment is encountered, stop iteration
		if (stopNamesInd && root.children()[index].name().toString() in stopNames)
			done = true;
		// If a segment with the same name as startSeg is encountered, stop iteration
		else if (root.children()[index].name().toString() == startSeg.name().toString() && !consecutiveInd)
			done = true;
		// If we're only collecting consecutive segments and we encounter a segment with a name other than segName, stop iteration
		else if (!test(root.children()[index].name().toString()) && consecutiveInd)
			done = true;
		// If all previous tests passed, and the current segment has a name of segName, then add it to our array
		else if (test(root.children()[index].name().toString()))
			out.push(root.children()[index]);
		// Increment our index counter
		index++;
	}

	// Return the output array
	return out;
}
    <type>FUNCTION</type>
    <scope>0</scope>
  </codeTemplate>
  <codeTemplate version="3.2.0">
    <id>dc230931-3f70-4a03-b82c-fdc4f6d1ac7f</id>
    <name>Convert HL7 Date Format</name>
    <tooltip>Converts standard HL7 v2.x date format to human-readable ISO date format</tooltip>
    /* author: abakken */

function convertHL7Date( date ) {

	/*  Check that the date string is
		1) not null
		2) a positive integer or timestamp
		4) valid length	*/

	if ( date != null && !isNaN(date) && date > 0 && date.length == 14 ) {
		return new String(DateUtil.convertDate("yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", date));
	} else if ( date != null && !isNaN(date) && date > 0 && date.length == 12 ) {
		return new String(DateUtil.convertDate("yyyyMMddHHmm", "yyyy-MM-dd HH:mm", date));
	} else if ( date != null && !isNaN(date) && date > 0 && date.length == 8 ) {
		return new String(DateUtil.convertDate("yyyyMMdd", "yyyy-MM-dd", date));
	} else if ( date != null && !isNaN(date.substring(0,13)) && date.substring(0,13) > 0
			&& !isNaN(date.substring(15,18)) && date.substring(15,18) > 0
			&& date.length == 19 ) {
		return new String(DateUtil.convertDate("yyyyMMddHHmmssz",
		"yyyy-MM-dd HH:mm:ss z ", date));
	} else return date;
}
    <type>FUNCTION</type>
    <scope>0</scope>
  </codeTemplate>
  <codeTemplate version="3.2.0">
    <id>434fca05-9749-4d12-829a-a046b5798e68</id>
    <name>Check if defined</name>
    <tooltip>Check that a reference to an object is defined</tooltip>
    function isDefined(x) {
	if (typeof x != 'undefined') {
		return true;
	}
	else return false;
}
    <type>FUNCTION</type>
    <scope>0</scope>
  </codeTemplate>
  <codeTemplate version="3.2.0">
    <id>5ac5794b-cf47-4aa5-ac25-d1bbef75e42d</id>
    <name>Convert ISO Date Format</name>
    <tooltip>Converts ISO date format to HL7 v2 format</tooltip>
    /* author: abakken */

function convertISODate( date )
{
	// yyyy-MM-dd HH:mm:ss
	if ( date != null && date.length == 19
			&& !isNaN(date.substring(0,3)) && date.charAt(4) == "-"
			&& !isNaN(date.substring(5,6)) && date.charAt(7) == "-"
			&& !isNaN(date.substring(8,9)) && date.charAt(10) == " "
			&& !isNaN(date.substring(11,12)) && date.charAt(13) == ":"
			&& !isNaN(date.substring(14,15)) && date.charAt(16) == ":"
			&& !isNaN(date.substring(17,18)) ) {
		return new String(DateUtil.convertDate("yyyy-MM-dd HH:mm:ss", "yyyyMMddHHmmss", date));
	}
	// yyyy-MM-dd HH:mm
	else if ( date != null && date.length == 16
			&& !isNaN(date.substring(0,3)) && date.charAt(4) == "-"
			&& !isNaN(date.substring(5,6)) && date.charAt(7) == "-"
			&& !isNaN(date.substring(8,9)) && date.charAt(10) == ' '
			&& !isNaN(date.substring(11,12)) && date.charAt(13) == ":"
			&& !isNaN(date.substring(14,15)) ) {
		return new String(DateUtil.convertDate("yyyy-MM-dd HH:mm", "yyyyMMddHHmm", date));
	}
	// yyyy-MM-dd
	else if ( date != null && date.length == 10
			&& !isNaN(date.substring(0,3)) && date.charAt(4) == "-"
			&& !isNaN(date.substring(5,6)) && date.charAt(7) == "-"
			&& !isNaN(date.substring(8,9)) ) {
		return new String(DateUtil.convertDate("yyyy-MM-dd", "yyyyMMdd", date));
	}
	// Timestamp
	else if ( date != null && date.length <= 25 && date.length >= 22
			&& !isNaN(date.substring(0,3)) && date.charAt(4) == "-"
			&& !isNaN(date.substring(5,6)) && date.charAt(7) == "-"
			&& !isNaN(date.substring(8,9)) && date.charAt(10) == " "
			&& !isNaN(date.substring(11,12)) && date.charAt(13) == ":"
			&& !isNaN(date.substring(14,15)) && date.charAt(16) == ":"
			&& !isNaN(date.substring(17,18)) && date.charAt(19) == " ") {
		return new String(DateUtil.convertDate("yyyy-MM-dd HH:mm:ss z",
		"yyyyMMddHHmmssZ", date));
	}
	else return date;
}
    <type>FUNCTION</type>
    <scope>0</scope>
  </codeTemplate>
</list>


text:
@ECHO OFF

REM swig command
@set SWIG=swig

REM default output language, see swig -h for more
@set LANG=lua

REM module name
@set MODULE_NAME=of

REM strip "of" from function, class, & define/enum names?
@set RENAME=true

REM default platform target, available targets are:
REM   * desktop: win, linux, & mac osx
REM  * ios: apple iOS using OpenGL ES
REM   * linuxarm: embedded linux using OpenGL ES
@set TARGET=desktop

REM generated bindings filename
@set NAME=openFrameworks_wrap

REM where to copy the generated bindings
@set DEST_DIR=..\src\bindings

REM where to copy the generated specific language files
@set DEST_LANG_DIR=.

REM path to OF headers
@set OF_HEADERS=..\..\..\libs\openFrameworks

cd ..\swig

@echo Generating for: %TARGET%
@echo LANG = %LANG%
@echo NAME = %NAME%
@echo DEST_DIR = %DEST_DIR%

swig -c++ -%LANG% -fcompact -fvirtual -I%OF_HEADERS% -DOF_SWIG_RENAME -DTARGET_OPENGLES -DEMSCRIPTEN -DTARGET_EMSCRIPTEN -D__EMSCRIPTEN__ -DMODULE_NAME=%MODULE_NAME% -outdir %DEST_LANG_DIR% openFrameworks.i
mv openFrameworks_wrap.cxx %NAME%.cpp

swig -c++ -%LANG% -external-runtime %NAME%.h

move %NAME%.h %DEST_DIR%\ofxLuaBindings.h
move %NAME%.cpp %DEST_DIR%\%TARGET%\ofxLuaBindings.cpp

pause


text:
using LibrarySystem.Migrations;
using LibrarySystem.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Http;

namespace LibrarySystem
{
    // Note: For instructions on enabling IIS7 classic mode,
    // visit http://go.microsoft.com/fwlink/?LinkId=301868
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer<LibraryDbContext>(new MigrateDatabaseToLatestVersion<LibraryDbContext, Configuration>());
        }
    }
}


text:
package com.evilco.configuration.xml;

import com.evilco.configuration.xml.adapter.IAdapter;
import com.evilco.configuration.xml.annotation.Configuration;
import com.evilco.configuration.xml.exception.AdapterInitializationException;
import com.evilco.configuration.xml.exception.ConfigurationException;

public interface IMarshallerInterface {

	/**
	 * Returns an adapter instance based on the supplied adapter class.
	 * @param adapter
	 * @return
	 * @throws com.evilco.configuration.xml.exception.AdapterInitializationException
	 */
	public IAdapter getAdapterInstance (Class<? extends IAdapter> adapter) throws AdapterInitializationException;

	/**
	 * Returns an adapter instance based on the supplied object.
	 * @param object
	 * @return
	 * @throws AdapterInitializationException
	 */
	public IAdapter getAdapterInstance (Object object) throws AdapterInitializationException;

	/**
	 * Returns the type the marshaller is configured to use.
	 * @return
	 */
	public Class<?> getType ();

	/**
	 * Returns the type configuration for this marshaller.
	 * @return
	 */
	public Configuration getTypeConfiguration ();

	/**
	 * Registers a new adapter.
	 * @param adapter
	 * @throws ConfigurationException
	 */
	public void registerAdapter (Class<? extends IAdapter> adapter) throws ConfigurationException;
}


text:
	<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
		Toggle navigation

	</button>
	router->routeHome() }}">{{{ $adminTitle }}}


text:
using Plugin.Toasts;
using System;
using Xamarin.Forms;

namespace CareApp
{
    public static class Notifier
    {
        static IToastNotificator notifier = DependencyService.Get<IToastNotificator>();
        public static async void Inform(string msg)
        {
            await notifier.Notify(ToastNotificationType.Info, "Info", msg, TimeSpan.FromSeconds(1.5));
        }
    }
}


text:
package io.fabric8.forge.camel.commands.project.helper;

import java.io.InputStream;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * An XML parser that uses SAX to include line and column number for each XML element in the parsed Document.
 *

 * The line number and column number can be obtained from a Node/Element using
 *

 *   String lineNumber = (String) node.getUserData(XmlLineNumberParser.LINE_NUMBER);
 *   String columnNumber = (String) node.getUserData(XmlLineNumberParser.COLUMN_NUMBER);
 *

 */
public final class XmlLineNumberParser {

    public static final String LINE_NUMBER = "lineNumber";
    public static final String COLUMN_NUMBER = "colNumber";

    /**
     * Parses the XML.
     *
     * @param is the XML content as an input stream
     * @return the DOM model
     * @throws Exception is thrown if error parsing
     */
    public static Document parseXml(final InputStream is) throws Exception {
        final Document doc;
        SAXParser parser;
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        parser = factory.newSAXParser();
        final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        doc = docBuilder.newDocument();

        final Stack<Element> elementStack = new Stack<Element>();
        final StringBuilder textBuffer = new StringBuilder();
        final DefaultHandler handler = new DefaultHandler() {
            private Locator locator;

            @Override
            public void setDocumentLocator(final Locator locator) {
                this.locator = locator; // Save the locator, so that it can be used later for line tracking when traversing nodes.
            }

            @Override
            public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {
                addTextIfNeeded();

                final Element el = doc.createElement(qName);
                for (int i = 0; i < attributes.getLength(); i++) {
                    el.setAttribute(attributes.getQName(i), attributes.getValue(i));
                }

                el.setUserData(LINE_NUMBER, String.valueOf(this.locator.getLineNumber()), null);
                el.setUserData(COLUMN_NUMBER, String.valueOf(this.locator.getColumnNumber()), null);
                elementStack.push(el);
            }

            @Override
            public void endElement(final String uri, final String localName, final String qName) {
                addTextIfNeeded();
                final Element closedEl = elementStack.pop();
                if (elementStack.isEmpty()) {
                    // Is this the root element?
                    doc.appendChild(closedEl);
                } else {
                    final Element parentEl = elementStack.peek();
                    parentEl.appendChild(closedEl);
                }
            }

            @Override
            public void characters(final char ch[], final int start, final int length) throws SAXException {
                textBuffer.append(ch, start, length);
            }

            // Outputs text accumulated under the current node
            private void addTextIfNeeded() {
                if (textBuffer.length() > 0) {
                    final Element el = elementStack.peek();
                    final Node textNode = doc.createTextNode(textBuffer.toString());
                    el.appendChild(textNode);
                    textBuffer.delete(0, textBuffer.length());
                }
            }
        };
        parser.parse(is, handler);

        return doc;
    }

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coralloidea Roussel

### Remarks
null


text:
namespace media {

class VideoUtilTest : public testing::Test {
 public:
  VideoUtilTest()
      : height_(0),
        y_stride_(0),
        u_stride_(0),
        v_stride_(0) {
  }

  virtual ~VideoUtilTest() {}

  void CreateSourceFrame(int width, int height,
                         int y_stride, int u_stride, int v_stride) {
    EXPECT_GE(y_stride, width);
    EXPECT_GE(u_stride, width / 2);
    EXPECT_GE(v_stride, width / 2);

    height_ = height;
    y_stride_ = y_stride;
    u_stride_ = u_stride;
    v_stride_ = v_stride;

    y_plane_.reset(new uint8[y_stride * height]);
    u_plane_.reset(new uint8[u_stride * height / 2]);
    v_plane_.reset(new uint8[v_stride * height / 2]);
  }

  void CreateDestinationFrame(int width, int height) {
    gfx::Size size(width, height);
    destination_frame_ =
        VideoFrame::CreateFrame(VideoFrame::YV12, size, size,
                                base::TimeDelta());
  }

  void CopyPlanes() {
    CopyYPlane(y_plane_.get(), y_stride_, height_, destination_frame_);
    CopyUPlane(u_plane_.get(), u_stride_, height_ / 2, destination_frame_);
    CopyVPlane(v_plane_.get(), v_stride_, height_ / 2, destination_frame_);
  }

 private:
  scoped_array<uint8> y_plane_;
  scoped_array<uint8> u_plane_;
  scoped_array<uint8> v_plane_;

  int height_;
  int y_stride_;
  int u_stride_;
  int v_stride_;

  scoped_refptr<VideoFrame> destination_frame_;

  DISALLOW_COPY_AND_ASSIGN(VideoUtilTest);
};

TEST_F(VideoUtilTest, CopyPlane_Exact) {
  CreateSourceFrame(16, 16, 16, 8, 8);
  CreateDestinationFrame(16, 16);
  CopyPlanes();
}

TEST_F(VideoUtilTest, CopyPlane_SmallerSource) {
  CreateSourceFrame(8, 8, 8, 4, 4);
  CreateDestinationFrame(16, 16);
  CopyPlanes();
}

TEST_F(VideoUtilTest, CopyPlane_SmallerDestination) {
  CreateSourceFrame(16, 16, 16, 8, 8);
  CreateDestinationFrame(8, 8);
  CopyPlanes();
}

}  // namespace media


text:
class UsageError < RuntimeError
end

class TestExit < RuntimeError
end

class NotAKegError < RuntimeError
end


text:
<?php

namespace System\Linq;

/**
 * Describes a grouped iterator.
 *
 * @package System\Linq
 * @author Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
 */
interface IGrouping extends \IteratorAggregate, \System\IObject {
    /**
     * Gets the underlying key.
     *
     * @return mixed The key.
     */
    function key();
}


text:
.. _tutorial-slam-for-beginners-the-basics:

===========================================================================
Simultaneous Localization and Mapping (SLAM) for beginners: the basics
===========================================================================

.. contents:: :local:

Videos
====================

For those who are new into mobile robotics and want a gentle introduction, I
recommend the following online resources:

- The `"5 minutes with Cyrill" series <https://www.youtube.com/playlist?list=PLgnQpQtFTOGSO8HC48K9sPuNliY1qxzV9>`_ (2020-2021).
  Here you can see the chapter for SLAM:

.. raw:: html

- These `taped seminars <https://www.youtube.com/watch?v=U6vr3iNrwRA&list=PLgnQpQtFTOGQrZ4O5QzbIHgl3b1JHimN_>`_ by Cyrill Stachniss (2013-2014):

.. raw:: html

- This course by Dr. Jürgen Sturm (TUM, 2013):

.. raw:: html

- My 2020 course `"A brief introduction to factor graphs" <https://www.youtube.com/watch?v=nLQ-YiPPMeU&list=PLOJ3GF0x2_eWtGXfZ5Ne1Jul5L-6Q76Sz>`_ (5 videos).
  Here it is the fifth video, an introduction to the GTSAM library:

.. raw:: html

Papers and books
====================

- The current must-read SLAM survey paper (2020-2021):
  Cadena, C., Carlone, L., Carrillo, H., Latif, Y., Scaramuzza, D., Neira, J., ... & Leonard, J. J. (2016).
  Past, present, and future of simultaneous localization and mapping: Toward the robust-perception age.
  IEEE Transactions on robotics, 32(6), 1309-1332. (`PDF <https://marinerobotics.mit.edu/sites/default/files/slam%20survey.pdf>`_)

- Our SLAM book, for those who want a rigorous treatment of all probabilistic equations in modern mobile robotics (~2012):
  `"Simultaneous Localization and Mapping for Mobile Robots: Introduction and Methods" <https://www.mrpt.org/slam_book_2012/>`_ (Fernández-Madrigal, J.A. and Blanco, J.L., 2012).

- About EKF-based SLAM with landmark maps (the trend between 1999 and ~2010, outdated nowadays):

  - Hugh Durrant-Whyte & Tim Bailey. "Simultaneous Localisation and Mapping (SLAM): Part I The Essential Algorithms", (2006) (`PDF <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.128.4195&rep=rep1&type=pdf>`_)

  - Tim Bailey & Hugh Durrant-Whyte and . "Simultaneous Localisation and Mapping (SLAM): Part II State of the Art", (2006) (`PDF <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.108.4153&rep=rep1&type=pdf>`_)

- An excellent introductory/advanced book (for everything up to ~2005): `Probabilistic Robotics <https://mitpress.mit.edu/books/probabilistic-robotics>`_, by Sebastian Thrun, Wolfram Burgard and Dieter Fox.


text:
<?php

/*# declare(strict_types=1); */

namespace Phossa\Query\Clause;

use Phossa\Query\Statement\RawInterface;
use Phossa\Query\Statement\StatementInterface;

/**
 * ValueTrait
 *
 * Dealing with value of WHERE, SET etc.
 *
 * @package Phossa\Query
 * @author  Hong Zhang <phossa@126.com>
 * @version 1.0.0
 * @since   1.0.0 added
 */
trait ValueTrait
{
    /**
     * Process value
     *
     * @param  mixed $value
     * @return string placeholder or value
     * @access protected
     */
    protected function processValue($value)/*# : string */
    {
        // object
        if (is_object($value)) {
            if ($value instanceof RawInterface) {
                return $value->getStatement([], false);
            } elseif ($value instanceof StatementInterface) {
                return '(' . $value->getStatement([], false) . ')';
            }
        }

        // scalar
        if (is_null($value)) {
            return 'NULL';
        } else {
            return $this->getPlaceholder($value);
        }
    }

    /* from ParameterAwareTrait */
    abstract protected function getPlaceholder($value)/*# : string */;
}


text:
'use strict';
var fs, path, parser, colors, uniqueRandomArray, fullname, hearts;
fs = require('fs');
path = require('path');
parser = require('iniparser');
colors = require('chalk');
uniqueRandomArray = require('unique-random-array');
fullname = require('fullname');
hearts = require('./hearts.json');
module.exports = function(){
  var heart;
  heart = uniqueRandomArray(hearts);
  console.log(colors.red('\n' + heart().join('')));
  console.log(colors.gray('\n Happy Valentine\'s Day, dear '));
  return fullname().then(function(name){
    return console.log(colors.red(name) + colors.gray('.'));
  });
};


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hedwigia 29: 149 (1890)

#### Original name
Coniothyrium hysterioideum P. Karst. & Har., 1890

### Remarks
null


text:
#include <aws/gamelift/model/UpdateScriptResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateScriptResult::UpdateScriptResult()
{
}

UpdateScriptResult::UpdateScriptResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateScriptResult& UpdateScriptResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  JsonView jsonValue = result.GetPayload().View();
  if(jsonValue.ValueExists("Script"))
  {
    m_script = jsonValue.GetObject("Script");

  }

  return *this;
}


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_

#include <utility>

#include "tensorflow/compiler/xla/service/hlo_pass_interface.h"
#include "tensorflow/compiler/xla/statusor.h"

namespace xla {
namespace gpu {

// Changes the shape of cudnn convolutions to allow faster "vectorized"
// algorithms.
//
// On sm61+ will convert int8_t convolutions from
//
//   - [N, C, H, W] to [N, C/4, H, W, 4],
//
// assuming C is divisible by 4.
//
// On sm75+ will convert int8_t convolutions from
//
//   - [N, C, H, W]      to [N, C/32, H, W, 32],
//   - [N, C/4, H, W, 4] to [N, C/32, H, W, 32], and
//   - [N, C, H, W]      to [N,  C/4, H, W,  4] (same as sm61+),
//
// assuming C is divisible by 4 or 32.
//
// This pass will not pad the channel dim to a multiple of 4 or 32, so you
// should run CudnnPadForConvolutions before this.
class CudnnVectorizeConvolutions : public HloModulePass {
 public:
  explicit CudnnVectorizeConvolutions(
      se::CudaComputeCapability compute_capability)
      : compute_capability_(compute_capability) {}

  absl::string_view name() const override {
    return "cudnn_vectorize_convolutions";
  }
  StatusOr<bool> Run(HloModule* module) override;

 private:
  se::CudaComputeCapability compute_capability_;
};

}  // namespace gpu
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_CUDNN_VECTORIZE_CONVOLUTIONS_H_