text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.devtools.build.lib.analysis.actions;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.ArtifactExpander;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.CollectionUtils;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.util.Preconditions;
import com.google.devtools.build.lib.vfs.PathFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Nullable;

/**
 * A customizable, serializable class for building memory efficient command lines.
 */
@Immutable
public final class CustomCommandLine extends CommandLine {

  private abstract static class ArgvFragment {
    abstract void eval(ImmutableList.Builder<String> builder);
  }

  /**
   * A command line argument for {@link TreeFileArtifact}.
   *
   *
Since {@link TreeFileArtifact} is not known or available at analysis time, subclasses should
   * enclose its parent TreeFileArtifact instead at analysis time. This interface provides method
   * {@link #substituteTreeArtifact} to generate another argument object that replaces the enclosed
   * TreeArtifact with one of its {@link TreeFileArtifact} at execution time.
   */
  private abstract static class TreeFileArtifactArgvFragment {
    /**
     * Substitutes this ArgvFragment with another arg object, with the original TreeArtifacts
     * contained in this ArgvFragment replaced by their associated TreeFileArtifacts.
     *
     * @param substitutionMap A map between TreeArtifacts and their associated TreeFileArtifacts
     *     used to replace them.
     */
    abstract Object substituteTreeArtifact(Map<Artifact, TreeFileArtifact> substitutionMap);
  }

  /**
   * A command line argument that can expand enclosed TreeArtifacts into a list of child
   * {@link TreeFileArtifact}s at execution time before argument evaluation.
   *
   *
The main difference between this class and {@link TreeFileArtifactArgvFragment} is that
   * {@link TreeFileArtifactArgvFragment} is used in {@link SpawnActionTemplate} to substitutes a
   * TreeArtifact with *one* of its child TreeFileArtifacts, while this class expands a TreeArtifact
   * into *all* of its child TreeFileArtifacts.
   *
   */
  private abstract static class TreeArtifactExpansionArgvFragment extends ArgvFragment {
    /**
     * Evaluates this argument fragment into an argument string and adds it into {@code builder}.
     * The enclosed TreeArtifact will be expanded using {@code artifactExpander}.
     */
    abstract void eval(ImmutableList.Builder<String> builder, ArtifactExpander artifactExpander);

    /**
     * Returns a string that describes this argument fragment. The string can be used as part of
     * an action key for the command line at analysis time.
     */
    abstract String describe();

    /**
     * Evaluates this argument fragment by serializing it into a string. Note that the returned
     * argument is not suitable to be used as part of an actual command line. The purpose of this
     * method is to provide a unique command line argument string to be used as part of an action
     * key at analysis time.
     *
     *
Internally this method just calls {@link #describe}.
     */
    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.add(describe());
    }
  }

  // It's better to avoid anonymous classes if we want to serialize command lines
  private static final class JoinExecPathsArg extends ArgvFragment {

    private final String delimiter;
    private final Iterable<Artifact> artifacts;

    private JoinExecPathsArg(String delimiter, Iterable<Artifact> artifacts) {
      this.delimiter = delimiter;
      this.artifacts = CollectionUtils.makeImmutable(artifacts);
    }

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.add(Artifact.joinExecPaths(delimiter, artifacts));
    }
  }

  private static final class JoinExpandedTreeArtifactExecPathsArg
      extends TreeArtifactExpansionArgvFragment {

    private final String delimiter;
    private final Artifact treeArtifact;

    private JoinExpandedTreeArtifactExecPathsArg(String delimiter, Artifact treeArtifact) {
      Preconditions.checkArgument(
          treeArtifact.isTreeArtifact(), "%s is not a TreeArtifact", treeArtifact);
      this.delimiter = delimiter;
      this.treeArtifact = treeArtifact;
    }

    @Override
    void eval(ImmutableList.Builder<String> builder, ArtifactExpander artifactExpander) {
      Set<Artifact> expandedArtifacts = new TreeSet<>();
      artifactExpander.expand(treeArtifact, expandedArtifacts);

      if (!expandedArtifacts.isEmpty()) {
        builder.add(Artifact.joinExecPaths(delimiter, expandedArtifacts));
      }
    }

    @Override
    public String describe() {
      return String.format(
          "JoinExpandedTreeArtifactExecPathsArg{ delimiter: %s, treeArtifact: %s}",
          delimiter,
          treeArtifact.getExecPathString());
    }
  }

  private static final class PathWithTemplateArg extends ArgvFragment {

    private final String template;
    private final PathFragment[] paths;

    private PathWithTemplateArg(String template, PathFragment... paths) {
      this.template = template;
      this.paths = paths;
    }

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      // PathFragment.toString() uses getPathString()
      builder.add(String.format(template, (Object[]) paths));
    }
  }

  /**
   * An argument object that evaluates to a formatted string for {@link TreeFileArtifact} exec
   * paths, enclosing the associated string format template and {@link TreeFileArtifact}s.
   */
  private static final class TreeFileArtifactExecPathWithTemplateArg
      extends TreeFileArtifactArgvFragment {

    private final String template;
    private final Artifact[] placeHolderTreeArtifacts;

    private TreeFileArtifactExecPathWithTemplateArg(
        String template, Artifact... artifacts) {
      for (Artifact artifact : artifacts) {
        Preconditions.checkArgument(artifact.isTreeArtifact(), "%s must be a TreeArtifact",
            artifact);
      }
      this.template = template;
      this.placeHolderTreeArtifacts = artifacts;
    }

    @Override
    ArgvFragment substituteTreeArtifact(Map<Artifact, TreeFileArtifact> substitutionMap) {
      ImmutableList.Builder<PathFragment> argBuilder = ImmutableList.builder();
      for (Artifact placeHolderTreeArtifact : placeHolderTreeArtifacts) {
        Artifact artifact = substitutionMap.get(placeHolderTreeArtifact);
        Preconditions.checkNotNull(artifact, "Artifact to substitute: %s", placeHolderTreeArtifact);
        argBuilder.add(artifact.getExecPath());
      }
      return new PathWithTemplateArg(
          template, argBuilder.build().toArray(new PathFragment[0]));
    }
  }

  // TODO(bazel-team): CustomArgv and CustomMultiArgv is  going to be difficult to expose
  // in Skylark. Maybe we can get rid of them by refactoring JavaCompileAction. It also
  // raises immutability / serialization issues.
  /**
   * Custom Java code producing a String argument. Usage of this class is discouraged.
   */
  public abstract static class CustomArgv extends ArgvFragment {

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.add(argv());
    }

    public abstract String argv();
  }

  /**
   * Custom Java code producing a List of String arguments. Usage of this class is discouraged.
   */
  public abstract static class CustomMultiArgv extends ArgvFragment {

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.addAll(argv());
    }

    public abstract Iterable<String> argv();
  }

  private static final class JoinPathsArg extends ArgvFragment {

    private final String delimiter;
    private final Iterable<PathFragment> paths;

    private JoinPathsArg(String delimiter, Iterable<PathFragment> paths) {
      this.delimiter = delimiter;
      this.paths = CollectionUtils.makeImmutable(paths);
    }

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.add(Joiner.on(delimiter).join(paths));
    }
  }

  private static final class JoinStringsArg extends ArgvFragment {

    private final String delimiter;
    private final Iterable<String> strings;

    private JoinStringsArg(String delimiter, Iterable<String> strings) {
      this.delimiter = delimiter;
      this.strings = CollectionUtils.makeImmutable(strings);
    }

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      builder.add(Joiner.on(delimiter).join(strings));
    }
  }

  /**
   * Arguments that intersperse strings between the items in a sequence. There are two forms of
   * interspersing, and either may be used by this implementation:
   *

   *
before each - a string is added before each item in a sequence. e.g.
   *       {@code -f foo -f bar -f baz}
   *
format each - a format string is used to format each item in a sequence. e.g.
   *       {@code -I/foo -I/bar -I/baz} for the format {@code "-I%s"}
   *

   *
   *
This class could be used both with both the "before" and "format" features at the same
   * time, but this is probably more confusion than it is worth. If you need this functionality,
   * consider using "before" only but storing the strings pre-formated in a {@link NestedSet}.
   */
  private static final class InterspersingArgs extends ArgvFragment {
    private final Iterable<?> sequence;
    private final String beforeEach;
    private final String formatEach;

    /**
     * Do not call from outside this class because this does not guarantee that {@code sequence} is
     * immutable.
     */
    private InterspersingArgs(Iterable<?> sequence, String beforeEach, String formatEach) {
      this.sequence = sequence;
      this.beforeEach = beforeEach;
      this.formatEach = formatEach;
    }

    static InterspersingArgs fromStrings(
        Iterable<?> sequence, String beforeEach, String formatEach) {
      return new InterspersingArgs(
          CollectionUtils.makeImmutable(sequence), beforeEach, formatEach);
    }

    static InterspersingArgs fromExecPaths(
        Iterable<Artifact> sequence, String beforeEach, String formatEach) {
      return new InterspersingArgs(
          Artifact.toExecPaths(CollectionUtils.makeImmutable(sequence)), beforeEach, formatEach);
    }

    @Override
    void eval(ImmutableList.Builder<String> builder) {
      for (Object item : sequence) {
        if (item == null) {
          continue;
        }

        if (beforeEach != null) {
          builder.add(beforeEach);
        }
        String arg = item.toString();
        if (formatEach != null) {
          arg = String.format(formatEach, arg);
        }
        builder.add(arg);
      }
    }
  }

  /**
   * An argument object that evaluates to the exec path of a {@link TreeFileArtifact}, enclosing
   * the associated {@link TreeFileArtifact}.
   */
  private static final class TreeFileArtifactExecPathArg extends TreeFileArtifactArgvFragment {
    private final Artifact placeHolderTreeArtifact;

    private TreeFileArtifactExecPathArg(Artifact artifact) {
      Preconditions.checkArgument(artifact.isTreeArtifact(), "%s must be a TreeArtifact", artifact);
      placeHolderTreeArtifact = artifact;
    }

    @Override
    Object substituteTreeArtifact(Map<Artifact, TreeFileArtifact> substitutionMap) {
      Artifact artifact = substitutionMap.get(placeHolderTreeArtifact);
      Preconditions.checkNotNull(artifact, "Artifact to substitute: %s", placeHolderTreeArtifact);
      return artifact.getExecPath();
    }
  }

  /**
   * A Builder class for CustomCommandLine with the appropriate methods.
   *
   *
{@link Iterable} instances passed to {@code add*} methods will be stored internally as
   * collections that are known to be immutable copies. This means that any {@link Iterable} that is
   * not a {@link NestedSet} or {@link ImmutableList} may be copied.
   *
   *
{@code addFormatEach*} methods take an {@link Iterable} but use these as arguments to
   * {@link String#format(String, Object...)} with a certain constant format string. For instance,
   * if {@code format} is {@code "-I%s"}, then the final arguments may be
   * {@code -Ifoo -Ibar -Ibaz}
   *
   *
{@code addBeforeEach*} methods take an {@link Iterable} but insert a certain {@link String}
   * once before each element in the string, meaning the total number of elements added is twice the
   * length of the {@link Iterable}. For instance: {@code -f foo -f bar -f baz}
   */
  public static final class Builder {
    // In order to avoid unnecessary wrapping, we keep raw objects here, but these objects are
    // always either ArgvFragments or objects whose desired string representations are just their
    // toString() results.
    private final List<Object> arguments = new ArrayList<>();

    public Builder add(CharSequence arg) {
      if (arg != null) {
        arguments.add(arg);
      }
      return this;
    }

    public Builder add(Label arg) {
      if (arg != null) {
        arguments.add(arg);
      }
      return this;
    }

    public Builder add(String arg, Iterable<String> args) {
      if (arg != null && args != null) {
        arguments.add(arg);
        arguments.add(
            InterspersingArgs.fromStrings(args, /*beforeEach=*/ null, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder add(Iterable<String> args) {
      if (args != null) {
        arguments.add(
            InterspersingArgs.fromStrings(args, /*beforeEach=*/ null, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder addExecPath(String arg, Artifact artifact) {
      if (arg != null && artifact != null) {
        arguments.add(arg);
        arguments.add(artifact.getExecPath());
      }
      return this;
    }

    public Builder addExecPaths(String arg, Iterable<Artifact> artifacts) {
      if (arg != null && artifacts != null) {
        arguments.add(arg);
        arguments.add(
            InterspersingArgs.fromExecPaths(artifacts, /*beforeEach=*/ null, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder addExecPaths(Iterable<Artifact> artifacts) {
      if (artifacts != null) {
        arguments.add(
            InterspersingArgs.fromExecPaths(artifacts, /*beforeEach=*/ null, /*formatEach=*/ null));
      }
      return this;
    }

    /**
     * Adds a exec path flag of a {@link TreeFileArtifact} inside the given TreeArtifact.
     *
     * @param arg the name of the argument
     * @param artifact the TreeArtifact that will be evaluated to one of its child
     *     {@link TreeFileArtifact} at execution time
     */
    public Builder addTreeFileArtifactExecPath(String arg, Artifact artifact) {
      if (arg != null && artifact != null) {
        arguments.add(arg);
        arguments.add(new TreeFileArtifactExecPathArg(artifact));
      }
      return this;
    }

    /**
     * Adds the exec path of a {@link TreeFileArtifact} inside the given TreeArtifact.
     *
     * @param artifact the TreeArtifact that will be evaluated to one of its child
     *     {@link TreeFileArtifact} at execution time
     */
    public Builder addTreeFileArtifactExecPath(Artifact artifact) {
      if (artifact != null) {
        arguments.add(new TreeFileArtifactExecPathArg(artifact));
      }
      return this;
    }

    public Builder addJoinStrings(String arg, String delimiter, Iterable<String> strings) {
      if (arg != null && strings != null) {
        arguments.add(arg);
        arguments.add(new JoinStringsArg(delimiter, strings));
      }
      return this;
    }

    public Builder addJoinExecPaths(String arg, String delimiter, Iterable<Artifact> artifacts) {
      if (arg != null && artifacts != null) {
        arguments.add(arg);
        arguments.add(new JoinExecPathsArg(delimiter, artifacts));
      }
      return this;
    }

    public Builder addPath(PathFragment path) {
      if (path != null) {
        arguments.add(path);
      }
      return this;
    }

    public Builder addPaths(String template, PathFragment... path) {
      if (template != null && path != null) {
        arguments.add(new PathWithTemplateArg(template, path));
      }
      return this;
    }

    /**
     * Adds a formatted string containing the exec paths of {@link TreeFileArtifact}s inside the
     * given TreeArtifacts.
     *
     * @param template the string format template
     * @param artifacts the TreeArtifact that will be evaluated to one of their child
     *     {@link TreeFileArtifact} at execution time
     */
    public Builder addTreeFileArtifactExecPaths(String template, Artifact... artifacts) {
      if (template != null && artifacts != null) {
        arguments.add(new TreeFileArtifactExecPathWithTemplateArg(template, artifacts));
      }
      return this;
    }

    public Builder addJoinPaths(String delimiter, Iterable<PathFragment> paths) {
      if (delimiter != null && paths != null) {
        arguments.add(new JoinPathsArg(delimiter, paths));
      }
      return this;
    }

    /**
     * Adds a string joined together by the exec paths of all {@link TreeFileArtifact}s under
     * {@code treeArtifact}.
     *
     * @param delimiter the delimiter used to join the artifact exec paths.
     * @param treeArtifact the TreeArtifact containing the {@link TreeFileArtifact}s to join.
     */
    public Builder addJoinExpandedTreeArtifactExecPath(String delimiter, Artifact treeArtifact) {
      arguments.add(new JoinExpandedTreeArtifactExecPathsArg(delimiter, treeArtifact));
      return this;
    }

    public Builder addBeforeEachPath(String repeated, Iterable<PathFragment> paths) {
      if (repeated != null && paths != null) {
        arguments.add(InterspersingArgs.fromStrings(paths, repeated, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder addBeforeEach(String repeated, Iterable<String> strings) {
      if (repeated != null && strings != null) {
        arguments.add(InterspersingArgs.fromStrings(strings, repeated, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder addBeforeEachExecPath(String repeated, Iterable<Artifact> artifacts) {
      if (repeated != null && artifacts != null) {
        arguments.add(InterspersingArgs.fromExecPaths(artifacts, repeated, /*formatEach=*/ null));
      }
      return this;
    }

    public Builder addFormatEach(String format, Iterable<String> strings) {
      if (format != null && strings != null) {
        arguments.add(InterspersingArgs.fromStrings(strings, /*beforeEach=*/null, format));
      }
      return this;
    }

    public Builder add(CustomArgv arg) {
      if (arg != null) {
        arguments.add(arg);
      }
      return this;
    }

    public Builder add(CustomMultiArgv arg) {
      if (arg != null) {
        arguments.add(arg);
      }
      return this;
    }

    public CustomCommandLine build() {
      return new CustomCommandLine(arguments);
    }
  }

  public static Builder builder() {
    return new Builder();
  }

  private final ImmutableList<Object> arguments;

  /**
   * A map between enclosed TreeArtifacts and their associated {@link TreeFileArtifacts} for
   * substitution.
   *
   *
 This map is used to support TreeArtifact substitutions in
   * {@link TreeFileArtifactArgvFragment}s.
   */
  private final Map<Artifact, TreeFileArtifact> substitutionMap;

  private CustomCommandLine(List<Object> arguments) {
    this.arguments = ImmutableList.copyOf(arguments);
    this.substitutionMap = null;
  }

  private CustomCommandLine(
      List<Object> arguments, Map<Artifact, TreeFileArtifact> substitutionMap) {
    this.arguments = ImmutableList.copyOf(arguments);
    this.substitutionMap = ImmutableMap.copyOf(substitutionMap);
  }

  /**
   * Given the list of {@link TreeFileArtifact}s, returns another CustomCommandLine that replaces
   * their parent TreeArtifacts with the TreeFileArtifacts in all
   * {@link TreeFileArtifactArgvFragment} argument objects.
   */
  @VisibleForTesting
  public CustomCommandLine evaluateTreeFileArtifacts(Iterable<TreeFileArtifact> treeFileArtifacts) {
    ImmutableMap.Builder<Artifact, TreeFileArtifact> substitutionMap = ImmutableMap.builder();
    for (TreeFileArtifact treeFileArtifact : treeFileArtifacts) {
      substitutionMap.put(treeFileArtifact.getParent(), treeFileArtifact);
    }

    return new CustomCommandLine(arguments, substitutionMap.build());
  }

  @Override
  public Iterable<String> arguments() {
    return argumentsInternal(null);
  }

  @Override
  public Iterable<String> arguments(ArtifactExpander artifactExpander) {
    return argumentsInternal(Preconditions.checkNotNull(artifactExpander));
  }

  private Iterable<String> argumentsInternal(@Nullable ArtifactExpander artifactExpander) {
    ImmutableList.Builder<String> builder = ImmutableList.builder();
    for (Object arg : arguments) {
      Object substitutedArg = substituteTreeFileArtifactArgvFragment(arg);
      if (substitutedArg instanceof ArgvFragment) {
        if (artifactExpander != null
            && substitutedArg instanceof TreeArtifactExpansionArgvFragment) {
          TreeArtifactExpansionArgvFragment expansionArg =
              (TreeArtifactExpansionArgvFragment) substitutedArg;
          expansionArg.eval(builder, artifactExpander);
        } else {
          ((ArgvFragment) substitutedArg).eval(builder);
        }
      } else {
        builder.add(substitutedArg.toString());
      }
    }
    return builder.build();
  }

  /**
   * If the given arg is a {@link TreeFileArtifactArgvFragment} and we have its associated
   * TreeArtifact substitution map, returns another argument object that has its enclosing
   * TreeArtifact substituted by one of its {@link TreeFileArtifact}. Otherwise, returns the given
   * arg unmodified.
   */
  private Object substituteTreeFileArtifactArgvFragment(Object arg) {
    if (arg instanceof TreeFileArtifactArgvFragment) {
      TreeFileArtifactArgvFragment argvFragment = (TreeFileArtifactArgvFragment) arg;
      return argvFragment.substituteTreeArtifact(
          Preconditions.checkNotNull(substitutionMap, argvFragment));
    } else {
      return arg;
    }
  }
}


text:
package org.cqframework.cql.cql2elm.operators;

import org.cqframework.cql.cql2elm.CqlTranslator;
import org.cqframework.cql.cql2elm.ModelManager;
import org.hl7.elm.r1.*;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import org.cqframework.cql.cql2elm.LibraryManager;

import static org.cqframework.cql.cql2elm.matchers.ConvertsToDecimalFrom.convertsToDecimalFrom;
import static org.cqframework.cql.cql2elm.matchers.HasTypeAndResult.hasTypeAndResult;
import static org.cqframework.cql.cql2elm.matchers.LiteralFor.literalFor;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class ArithmeticOperatorsTest {

    private Map<String, ExpressionDef> defs;

    @BeforeTest
    public void setup() throws IOException {
        ModelManager modelManager = new ModelManager();
        CqlTranslator translator = CqlTranslator.fromStream(ArithmeticOperatorsTest.class.getResourceAsStream("../OperatorTests/ArithmeticOperators.cql"), modelManager, new LibraryManager(modelManager));
        assertThat(translator.getErrors().size(), is(0));
        Library library = translator.toELM();
        defs = new HashMap<>();
        for (ExpressionDef def: library.getStatements().getDef()) {
            defs.put(def.getName(), def);
        }
    }

    @Test
    public void testDivide() {
        ExpressionDef def = defs.get("IntegerDivide");
        assertThat(def, hasTypeAndResult(Divide.class, "System.Decimal"));

        def = defs.get("IntegerDivide10");
        assertThat(def, hasTypeAndResult(Divide.class, "System.Decimal"));

        def = defs.get("RealDivide");
        assertThat(def, hasTypeAndResult(Divide.class, "System.Decimal"));

        def = defs.get("QuantityRealDivide");
        assertThat(def, hasTypeAndResult(Divide.class, "System.Quantity"));

        def = defs.get("QuantityDivide");
        assertThat(def, hasTypeAndResult(Divide.class, "System.Quantity"));
    }

    @Test
    public void testCeiling() {
        ExpressionDef def = defs.get("IntegerCeiling");
        assertThat(def, hasTypeAndResult(Ceiling.class, "System.Integer"));

        Ceiling ceiling = (Ceiling) def.getExpression();
        assertThat(ceiling.getOperand(), convertsToDecimalFrom(1));

        def = defs.get("DecimalCeiling");
        assertThat(def, hasTypeAndResult(Ceiling.class, "System.Integer"));

        ceiling = (Ceiling) def.getExpression();
        assertThat(ceiling.getOperand(), literalFor(1.0));
    }

    @Test
    public void testFloor() {
        ExpressionDef def = defs.get("IntegerFloor");
        assertThat(def, hasTypeAndResult(Floor.class, "System.Integer"));

        Floor floor = (Floor) def.getExpression();
        assertThat(floor.getOperand(), convertsToDecimalFrom(1));

        def = defs.get("DecimalFloor");
        assertThat(def, hasTypeAndResult(Floor.class, "System.Integer"));

        floor = (Floor) def.getExpression();
        assertThat(floor.getOperand(), literalFor(1.0));
    }

    @Test
    public void testTruncate() {
        ExpressionDef def = defs.get("IntegerTruncate");
        assertThat(def, hasTypeAndResult(Truncate.class, "System.Integer"));

        Truncate truncate = (Truncate) def.getExpression();
        assertThat(truncate.getOperand(), convertsToDecimalFrom(5));

        def = defs.get("DecimalTruncate");
        assertThat(def, hasTypeAndResult(Truncate.class, "System.Integer"));

        truncate = (Truncate) def.getExpression();
        assertThat(truncate.getOperand(), literalFor(5.5));
    }

    @Test
    public void testAbs() {
        ExpressionDef def = defs.get("IntegerAbs");
        assertThat(def, hasTypeAndResult(Abs.class, "System.Integer"));

        Abs abs = (Abs) def.getExpression();
        assertThat(abs.getOperand(), instanceOf(Negate.class));
        assertThat(((Negate) abs.getOperand()).getOperand(), literalFor(1));

        def = defs.get("DecimalAbs");
        assertThat(def, hasTypeAndResult(Abs.class, "System.Decimal"));

        abs = (Abs) def.getExpression();
        assertThat(abs.getOperand(), instanceOf(Negate.class));
        assertThat(((Negate) abs.getOperand()).getOperand(), literalFor(1.0));

        def = defs.get("QuantityAbs");
        assertThat(def, hasTypeAndResult(Abs.class, "System.Quantity"));

        abs = (Abs) def.getExpression();
        assertThat(abs.getOperand(), instanceOf(Negate.class));
        Negate n = (Negate) abs.getOperand();
        assertThat(n.getOperand(), instanceOf(Quantity.class));
        Quantity q = (Quantity) n.getOperand();
        assertThat(q.getValue(), is(BigDecimal.valueOf(1.0)));
        assertThat(q.getUnit(), is("cm"));
    }

    @Test
    public void testLog() {
        ExpressionDef def = defs.get("DecimalDecimalLog");
        assertThat(def, hasTypeAndResult(Log.class, "System.Decimal"));

        Log log = (Log) def.getExpression();
        assertThat(log.getOperand(), hasSize(2));
        assertThat(log.getOperand().get(0), literalFor(1000.0));
        assertThat(log.getOperand().get(1), literalFor(10.0));

        def = defs.get("DecimalIntegerLog");
        assertThat(def, hasTypeAndResult(Log.class, "System.Decimal"));

        log = (Log) def.getExpression();
        assertThat(log.getOperand(), hasSize(2));
        assertThat(log.getOperand().get(0), literalFor(1000.0));
        assertThat(log.getOperand().get(1), convertsToDecimalFrom(10));

        def = defs.get("IntegerDecimalLog");
        assertThat(def, hasTypeAndResult(Log.class, "System.Decimal"));

        log = (Log) def.getExpression();
        assertThat(log.getOperand(), hasSize(2));
        assertThat(log.getOperand().get(0), convertsToDecimalFrom(1000));
        assertThat(log.getOperand().get(1), literalFor(10.0));

        def = defs.get("IntegerIntegerLog");
        assertThat(def, hasTypeAndResult(Log.class, "System.Decimal"));

        log = (Log) def.getExpression();
        assertThat(log.getOperand(), hasSize(2));
        assertThat(log.getOperand().get(0), convertsToDecimalFrom(1000));
        assertThat(log.getOperand().get(1), convertsToDecimalFrom(10));
    }

    @Test
    public void testLn() {
        ExpressionDef def = defs.get("IntegerLn");
        assertThat(def, hasTypeAndResult(Ln.class, "System.Decimal"));

        Ln ln = (Ln) def.getExpression();
        assertThat(ln.getOperand(), convertsToDecimalFrom(1000));

        def = defs.get("DecimalLn");
        assertThat(def, hasTypeAndResult(Ln.class, "System.Decimal"));

        ln = (Ln) def.getExpression();
        assertThat(ln.getOperand(), literalFor(1000.0));
    }

    @Test
    public void testExp() {
        ExpressionDef def = defs.get("IntegerExp");
        assertThat(def, hasTypeAndResult(Exp.class, "System.Decimal"));

        Exp exp = (Exp)def.getExpression();
        assertThat(exp.getOperand(), convertsToDecimalFrom(1000));

        def = defs.get("DecimalExp");
        assertThat(def, hasTypeAndResult(Exp.class, "System.Decimal"));

        exp = (Exp)def.getExpression();
        assertThat(exp.getOperand(), literalFor(1000.0));
    }

    @Test
    public void testRound() {
        ExpressionDef def = defs.get("DecimalRound");
        assertThat(def, hasTypeAndResult(Round.class, "System.Decimal"));

        Round round = (Round) def.getExpression();
        assertThat(round.getOperand(), literalFor(10.55));
        assertThat(round.getPrecision(), nullValue());

        def = defs.get("DecimalRoundWithPrecision");
        assertThat(def, hasTypeAndResult(Round.class, "System.Decimal"));

        round = (Round) def.getExpression();
        assertThat(round.getOperand(), literalFor(10.5555));
        assertThat(round.getPrecision(), literalFor(2));
    }

    @Test
    public void testPrecision() {
        ExpressionDef def = defs.get("DecimalPrecision");
        assertThat(def, hasTypeAndResult(Precision.class, "System.Integer"));

        def = defs.get("DatePrecision");
        assertThat(def, hasTypeAndResult(Precision.class, "System.Integer"));

        def = defs.get("DateTimePrecision");
        assertThat(def, hasTypeAndResult(Precision.class, "System.Integer"));

        def = defs.get("TimePrecision");
        assertThat(def, hasTypeAndResult(Precision.class, "System.Integer"));
    }

    @Test
    public void testLowBoundary() {
        ExpressionDef def = defs.get("DecimalLowBoundary");
        assertThat(def, hasTypeAndResult(LowBoundary.class, "System.Decimal"));

        def = defs.get("DateLowBoundary");
        assertThat(def, hasTypeAndResult(LowBoundary.class, "System.Date"));

        def = defs.get("DateTimeLowBoundary");
        assertThat(def, hasTypeAndResult(LowBoundary.class, "System.DateTime"));

        def = defs.get("TimeLowBoundary");
        assertThat(def, hasTypeAndResult(LowBoundary.class, "System.Time"));
    }

    @Test
    public void testHighBoundary() {
        ExpressionDef def = defs.get("DecimalHighBoundary");
        assertThat(def, hasTypeAndResult(HighBoundary.class, "System.Decimal"));

        def = defs.get("DateHighBoundary");
        assertThat(def, hasTypeAndResult(HighBoundary.class, "System.Date"));

        def = defs.get("DateTimeHighBoundary");
        assertThat(def, hasTypeAndResult(HighBoundary.class, "System.DateTime"));

        def = defs.get("TimeHighBoundary");
        assertThat(def, hasTypeAndResult(HighBoundary.class, "System.Time"));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.modsl.core.util;

import java.util.LinkedList;
import java.util.List;

public class ThreadLocalContainer {

    private static ThreadLocal<ThreadLocalContainer> threadLocal = new ThreadLocal<ThreadLocalContainer>();

    List<String> logMessages = new LinkedList<String>();

    public static void set(ThreadLocalContainer tlc) {
        threadLocal.set(tlc);
    }

    public static ThreadLocalContainer get() {
        ThreadLocalContainer tlc = (ThreadLocalContainer) threadLocal.get();
        if (tlc == null) {
            tlc = new ThreadLocalContainer();
            set(tlc);
        }
        return tlc;
    }

    public void addLogMessage(String msg) {
        logMessages.add(msg);
    }

    public List<String> extractLogMessages() {
        List<String> temp = logMessages;
        logMessages = new LinkedList<String>();
        return temp;
    }

}


text:
angular.
    module('buildMonitor.settings', [ 'buildMonitor.services', 'uiSlider']).

    controller('controlPanel', ['$scope', 'cookieJar',
        function ($scope, cookieJar) {
            'use strict';

            $scope.settings.fontSize        = cookieJar.get('fontSize',        1);
            $scope.settings.numberOfColumns = cookieJar.get('numberOfColumns', 2);
            $scope.settings.colourBlind     = cookieJar.get('colourBlind',     0);

            angular.forEach($scope.settings, function(value, name) {
                $scope.$watch('settings.' + name, function(currentValue) {
                    cookieJar.put(name, currentValue);
                });
            });
        }]);


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 297028 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.ibase-free-event-handler">
 <refnamediv>
  <refname>ibase_free_event_handler</refname>
  <refpurpose>Cancels a registered event handler</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>ibase_free_event_handler</methodname>
   <methodparam><type>resource</type><parameter>event</parameter></methodparam>
  </methodsynopsis>
  <para>
   This function causes the registered event handler specified by
   <parameter>event</parameter> to be cancelled. The callback function will
   no longer be called for the events it was registered to handle.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>event</parameter></term>
     <listitem>
      <para>
       An event resource, created by
       <function>ibase_set_event_handler</function>.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   &return.success;
  </para>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>ibase_set_event_handler</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
using System;
using Azure.Core;

namespace Azure.Communication.Identity.Models
{
    /// <summary> The TeamsUserExchangeTokenRequest. </summary>
    internal partial class TeamsUserExchangeTokenRequest
    {
        /// <summary> Initializes a new instance of TeamsUserExchangeTokenRequest. </summary>
        /// <param name="token"> Azure AD access token of a Teams User to acquire a new Communication Identity access token. </param>
        /// <param name="appId"> Client ID of an Azure AD application to be verified against the appid claim in the Azure AD access token. </param>
        /// <param name="userId"> Object ID of an Azure AD user (Teams User) to be verified against the oid claim in the Azure AD access token. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="token"/>, <paramref name="appId"/> or <paramref name="userId"/> is null. </exception>
        public TeamsUserExchangeTokenRequest(string token, string appId, string userId)
        {
            Argument.AssertNotNull(token, nameof(token));
            Argument.AssertNotNull(appId, nameof(appId));
            Argument.AssertNotNull(userId, nameof(userId));

            Token = token;
            AppId = appId;
            UserId = userId;
        }

        /// <summary> Azure AD access token of a Teams User to acquire a new Communication Identity access token. </summary>
        public string Token { get; }
        /// <summary> Client ID of an Azure AD application to be verified against the appid claim in the Azure AD access token. </summary>
        public string AppId { get; }
        /// <summary> Object ID of an Azure AD user (Teams User) to be verified against the oid claim in the Azure AD access token. </summary>
        public string UserId { get; }
    }
}


text:
<?php

namespace XeroPHP\Models\Accounting\Overpayment;

use XeroPHP\Remote;
use XeroPHP\Models\Accounting\Invoice;

class Allocation extends Remote\Model
{
    /**
     * the invoice the overpayment is being allocated against.
     *
     * @property Invoice Invoice
     */

    /**
     * the amount being applied to the invoice.
     *
     * @property float AppliedAmount
     */

    /**
     * the date the overpayment is applied YYYY-MM-DD (read-only). This will be the latter of the invoice
     * date and the overpayment date.
     *
     * @property \DateTimeInterface Date
     */

    /**
     * Get the resource uri of the class (Contacts) etc.
     *
     * @return string
     */
    public static function getResourceURI()
    {
        return 'Allocations';
    }

    /**
     * Get the root node name.  Just the unqualified classname.
     *
     * @return string
     */
    public static function getRootNodeName()
    {
        return 'Allocation';
    }

    /**
     * Get the guid property.
     *
     * @return string
     */
    public static function getGUIDProperty()
    {
        return '';
    }

    /**
     * Get the stem of the API (core.xro) etc.
     *
     * @return string
     */
    public static function getAPIStem()
    {
        return Remote\URL::API_CORE;
    }

    /**
     * Get the supported methods.
     */
    public static function getSupportedMethods()
    {
        return [
        ];
    }

    /**
     * Get the properties of the object.  Indexed by constants
     *  [0] - Mandatory
     *  [1] - Type
     *  [2] - PHP type
     *  [3] - Is an Array
     *  [4] - Saves directly.
     *
     * @return array
     */
    public static function getProperties()
    {
        return [
            'Invoice' => [false, self::PROPERTY_TYPE_OBJECT, 'Accounting\\Invoice', false, false],
            'AppliedAmount' => [false, self::PROPERTY_TYPE_FLOAT, null, false, false],
            'Date' => [false, self::PROPERTY_TYPE_DATE, '\\DateTimeInterface', false, false],
        ];
    }

    public static function isPageable()
    {
        return false;
    }

    /**
     * @return Invoice
     */
    public function getInvoice()
    {
        return $this->_data['Invoice'];
    }

    /**
     * @param Invoice $value
     *
     * @return Allocation
     */
    public function setInvoice(Invoice $value)
    {
        $this->propertyUpdated('Invoice', $value);
        $this->_data['Invoice'] = $value;

        return $this;
    }

    /**
     * @return float
     */
    public function getAppliedAmount()
    {
        return $this->_data['AppliedAmount'];
    }

    /**
     * @param float $value
     *
     * @return Allocation
     */
    public function setAppliedAmount($value)
    {
        $this->propertyUpdated('AppliedAmount', $value);
        $this->_data['AppliedAmount'] = $value;

        return $this;
    }

    /**
     * @return \DateTimeInterface
     */
    public function getDate()
    {
        return $this->_data['Date'];
    }

    /**
     * @param \DateTimeInterface $value
     *
     * @return Allocation
     */
    public function setDate(\DateTimeInterface $value)
    {
        $this->propertyUpdated('Date', $value);
        $this->_data['Date'] = $value;

        return $this;
    }
}


text:
package com.digitalpetri.opcua.stack.core.types.structured;

import com.digitalpetri.opcua.stack.core.Identifiers;
import com.digitalpetri.opcua.stack.core.serialization.DelegateRegistry;
import com.digitalpetri.opcua.stack.core.serialization.UaDecoder;
import com.digitalpetri.opcua.stack.core.serialization.UaEncoder;
import com.digitalpetri.opcua.stack.core.types.builtin.DateTime;
import com.digitalpetri.opcua.stack.core.types.builtin.NodeId;

public class AggregateFilter extends MonitoringFilter {

    public static final NodeId TypeId = Identifiers.AggregateFilter;
    public static final NodeId BinaryEncodingId = Identifiers.AggregateFilter_Encoding_DefaultBinary;
    public static final NodeId XmlEncodingId = Identifiers.AggregateFilter_Encoding_DefaultXml;

    protected final DateTime _startTime;
    protected final NodeId _aggregateType;
    protected final Double _processingInterval;
    protected final AggregateConfiguration _aggregateConfiguration;

    public AggregateFilter(DateTime _startTime, NodeId _aggregateType, Double _processingInterval, AggregateConfiguration _aggregateConfiguration) {
        super();
        this._startTime = _startTime;
        this._aggregateType = _aggregateType;
        this._processingInterval = _processingInterval;
        this._aggregateConfiguration = _aggregateConfiguration;
    }

    public DateTime getStartTime() { return _startTime; }

    public NodeId getAggregateType() { return _aggregateType; }

    public Double getProcessingInterval() { return _processingInterval; }

    public AggregateConfiguration getAggregateConfiguration() { return _aggregateConfiguration; }

    @Override
    public NodeId getTypeId() { return TypeId; }

    @Override
    public NodeId getBinaryEncodingId() { return BinaryEncodingId; }

    @Override
    public NodeId getXmlEncodingId() { return XmlEncodingId; }

    public static void encode(AggregateFilter aggregateFilter, UaEncoder encoder) {
        encoder.encodeDateTime("StartTime", aggregateFilter._startTime);
        encoder.encodeNodeId("AggregateType", aggregateFilter._aggregateType);
        encoder.encodeDouble("ProcessingInterval", aggregateFilter._processingInterval);
        encoder.encodeSerializable("AggregateConfiguration", aggregateFilter._aggregateConfiguration);
    }

    public static AggregateFilter decode(UaDecoder decoder) {
        DateTime _startTime = decoder.decodeDateTime("StartTime");
        NodeId _aggregateType = decoder.decodeNodeId("AggregateType");
        Double _processingInterval = decoder.decodeDouble("ProcessingInterval");
        AggregateConfiguration _aggregateConfiguration = decoder.decodeSerializable("AggregateConfiguration", AggregateConfiguration.class);

        return new AggregateFilter(_startTime, _aggregateType, _processingInterval, _aggregateConfiguration);
    }

    static {
        DelegateRegistry.registerEncoder(AggregateFilter::encode, AggregateFilter.class, BinaryEncodingId, XmlEncodingId);
        DelegateRegistry.registerDecoder(AggregateFilter::decode, AggregateFilter.class, BinaryEncodingId, XmlEncodingId);
    }

}


text:
@class NSPrintInfo;
#else
class NSPrintInfo;
#endif  // __OBJC__

namespace printing {

class PRINTING_EXPORT PrintingContextMac : public PrintingContext {
 public:
  explicit PrintingContextMac(const std::string& app_locale);
  virtual ~PrintingContextMac();

  // PrintingContext implementation.
  virtual void AskUserForSettings(
      gfx::NativeView parent_view,
      int max_pages,
      bool has_selection,
      const PrintSettingsCallback& callback) OVERRIDE;
  virtual Result UseDefaultSettings() OVERRIDE;
  virtual Result UpdatePrinterSettings(
      const base::DictionaryValue& job_settings,
      const PageRanges& ranges) OVERRIDE;
  virtual Result InitWithSettings(const PrintSettings& settings) OVERRIDE;
  virtual Result NewDocument(const string16& document_name) OVERRIDE;
  virtual Result NewPage() OVERRIDE;
  virtual Result PageDone() OVERRIDE;
  virtual Result DocumentDone() OVERRIDE;
  virtual void Cancel() OVERRIDE;
  virtual void ReleaseContext() OVERRIDE;
  virtual gfx::NativeDrawingContext context() const OVERRIDE;

 private:
  // Initializes PrintSettings from |print_info_|. This must be called
  // after changes to |print_info_| in order for the changes to take effect in
  // printing.
  // This function ignores the page range information specified in the print
  // info object and use |ranges| instead.
  void InitPrintSettingsFromPrintInfo(const PageRanges& ranges);

  // Returns the set of page ranges constructed from |print_info_|.
  PageRanges GetPageRangesFromPrintInfo();

  // Updates |print_info_| to use the given printer.
  // Returns true if the printer was set else returns false.
  bool SetPrinter(const std::string& device_name);

  // Updates |print_info_| page format with user default paper information.
  // Returns true if the paper was set else returns false.
  bool UpdatePageFormatWithPaperInfo();

  // Sets the print job destination type as preview job.
  // Returns true if the print job destination type is set.
  bool SetPrintPreviewJob();

  // Sets |copies| in PMPrintSettings.
  // Returns true if the number of copies is set.
  bool SetCopiesInPrintSettings(int copies);

  // Sets |collate| in PMPrintSettings.
  // Returns true if |collate| is set.
  bool SetCollateInPrintSettings(bool collate);

  // Sets orientation in native print info object.
  // Returns true if the orientation was set.
  bool SetOrientationIsLandscape(bool landscape);

  // Sets duplex mode in PMPrintSettings.
  // Returns true if duplex mode is set.
  bool SetDuplexModeInPrintSettings(DuplexMode mode);

  // Sets output color mode in PMPrintSettings.
  // Returns true if color mode is set.
  bool SetOutputColor(int color_mode);

  // The native print info object.
  base::scoped_nsobject<NSPrintInfo> print_info_;

  // The current page's context; only valid between NewPage and PageDone call
  // pairs.
  CGContext* context_;

  DISALLOW_COPY_AND_ASSIGN(PrintingContextMac);
};

}  // namespace printing

#endif  // PRINTING_PRINTING_CONTEXT_MAC_H_


text:
package gameEngine.model.effect;

import jgame.JGObject;

public class FloatEffect extends Effect {
    private final double FLOAT_SPEED=0.1;
    public FloatEffect (String effectName, double x, double y, JGObject o) {
        super(effectName, x, y, o);

    }
    public FloatEffect(JGObject o){
        super(o);
    }
    public void move(){
        myObject.y-=FLOAT_SPEED;
    }

}


text:
QString formatDoubleToString(const double value, const bool allowScientific, const uint precision)
{
  QString number = QLocale::system().toString(value, allowScientific ? 'g' : 'f', precision);
  QStringList numberParts = number.split(QLocale::system().decimalPoint());
  if (numberParts.size() == 1)
  {
    return number;
  }
  else if (numberParts.size() == 2)
  {
    QString fractionalPart = numberParts.back();

    while (fractionalPart.size() && fractionalPart.lastIndexOf(QChar('0')) == fractionalPart.size() - 1)
      fractionalPart = fractionalPart.remove(fractionalPart.size() - 1, 1);

    if (fractionalPart.isEmpty())
      return numberParts.front();
    else
      return numberParts.front() + QLocale::system().decimalPoint() + fractionalPart;
  }
  else
  {
    assert(false);
    return QString();
  }
}


text:
package getter

import (
	"fmt"
	"io"
	"net/url"
	"os"
	"path/filepath"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
	"github.com/aws/aws-sdk-go/aws/ec2metadata"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"
)

// S3Getter is a Getter implementation that will download a module from
// a S3 bucket.
type S3Getter struct{}

func (g *S3Getter) ClientMode(u *url.URL) (ClientMode, error) {
	// Parse URL
	region, bucket, path, _, creds, err := g.parseUrl(u)
	if err != nil {
		return 0, err
	}

	// Create client config
	config := g.getAWSConfig(region, u, creds)
	sess := session.New(config)
	client := s3.New(sess)

	// List the object(s) at the given prefix
	req := &s3.ListObjectsInput{
		Bucket: aws.String(bucket),
		Prefix: aws.String(path),
	}
	resp, err := client.ListObjects(req)
	if err != nil {
		return 0, err
	}

	for _, o := range resp.Contents {
		// Use file mode on exact match.
		if *o.Key == path {
			return ClientModeFile, nil
		}

		// Use dir mode if child keys are found.
		if strings.HasPrefix(*o.Key, path+"/") {
			return ClientModeDir, nil
		}
	}

	// There was no match, so just return file mode. The download is going
	// to fail but we will let S3 return the proper error later.
	return ClientModeFile, nil
}

func (g *S3Getter) Get(dst string, u *url.URL) error {
	// Parse URL
	region, bucket, path, _, creds, err := g.parseUrl(u)
	if err != nil {
		return err
	}

	// Remove destination if it already exists
	_, err = os.Stat(dst)
	if err != nil && !os.IsNotExist(err) {
		return err
	}

	if err == nil {
		// Remove the destination
		if err := os.RemoveAll(dst); err != nil {
			return err
		}
	}

	// Create all the parent directories
	if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
		return err
	}

	config := g.getAWSConfig(region, u, creds)
	sess := session.New(config)
	client := s3.New(sess)

	// List files in path, keep listing until no more objects are found
	lastMarker := ""
	hasMore := true
	for hasMore {
		req := &s3.ListObjectsInput{
			Bucket: aws.String(bucket),
			Prefix: aws.String(path),
		}
		if lastMarker != "" {
			req.Marker = aws.String(lastMarker)
		}

		resp, err := client.ListObjects(req)
		if err != nil {
			return err
		}

		hasMore = aws.BoolValue(resp.IsTruncated)

		// Get each object storing each file relative to the destination path
		for _, object := range resp.Contents {
			lastMarker = aws.StringValue(object.Key)
			objPath := aws.StringValue(object.Key)

			// If the key ends with a backslash assume it is a directory and ignore
			if strings.HasSuffix(objPath, "/") {
				continue
			}

			// Get the object destination path
			objDst, err := filepath.Rel(path, objPath)
			if err != nil {
				return err
			}
			objDst = filepath.Join(dst, objDst)

			if err := g.getObject(client, objDst, bucket, objPath, ""); err != nil {
				return err
			}
		}
	}

	return nil
}

func (g *S3Getter) GetFile(dst string, u *url.URL) error {
	region, bucket, path, version, creds, err := g.parseUrl(u)
	if err != nil {
		return err
	}

	config := g.getAWSConfig(region, u, creds)
	sess := session.New(config)
	client := s3.New(sess)
	return g.getObject(client, dst, bucket, path, version)
}

func (g *S3Getter) getObject(client *s3.S3, dst, bucket, key, version string) error {
	req := &s3.GetObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	}
	if version != "" {
		req.VersionId = aws.String(version)
	}

	resp, err := client.GetObject(req)
	if err != nil {
		return err
	}

	// Create all the parent directories
	if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
		return err
	}

	f, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, resp.Body)
	return err
}

func (g *S3Getter) getAWSConfig(region string, url *url.URL, creds *credentials.Credentials) *aws.Config {
	conf := &aws.Config{}
	if creds == nil {
		// Grab the metadata URL
		metadataURL := os.Getenv("AWS_METADATA_URL")
		if metadataURL == "" {
			metadataURL = "http://169.254.169.254:80/latest"
		}

		creds = credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
				&ec2rolecreds.EC2RoleProvider{
					Client: ec2metadata.New(session.New(&aws.Config{
						Endpoint: aws.String(metadataURL),
					})),
				},
			})
	}

	if creds != nil {
		conf.Endpoint = &url.Host
		conf.S3ForcePathStyle = aws.Bool(true)
		if url.Scheme == "http" {
			conf.DisableSSL = aws.Bool(true)
		}
	}

	conf.Credentials = creds
	if region != "" {
		conf.Region = aws.String(region)
	}

	return conf
}

func (g *S3Getter) parseUrl(u *url.URL) (region, bucket, path, version string, creds *credentials.Credentials, err error) {
	// This just check whether we are dealing with S3 or
	// any other S3 compliant service. S3 has a predictable
	// url as others do not
	if strings.Contains(u.Host, "amazonaws.com") {
		// Expected host style: s3.amazonaws.com. They always have 3 parts,
		// although the first may differ if we're accessing a specific region.
		hostParts := strings.Split(u.Host, ".")
		if len(hostParts) != 3 {
			err = fmt.Errorf("URL is not a valid S3 URL")
			return
		}

		// Parse the region out of the first part of the host
		region = strings.TrimPrefix(strings.TrimPrefix(hostParts[0], "s3-"), "s3")
		if region == "" {
			region = "us-east-1"
		}

		pathParts := strings.SplitN(u.Path, "/", 3)
		if len(pathParts) != 3 {
			err = fmt.Errorf("URL is not a valid S3 URL")
			return
		}

		bucket = pathParts[1]
		path = pathParts[2]
		version = u.Query().Get("version")

	} else {
		pathParts := strings.SplitN(u.Path, "/", 3)
		if len(pathParts) != 3 {
			err = fmt.Errorf("URL is not a valid S3 complaint URL")
			return
		}
		bucket = pathParts[1]
		path = pathParts[2]
		version = u.Query().Get("version")
		region = u.Query().Get("region")
		if region == "" {
			region = "us-east-1"
		}
	}

	_, hasAwsId := u.Query()["aws_access_key_id"]
	_, hasAwsSecret := u.Query()["aws_access_key_secret"]
	_, hasAwsToken := u.Query()["aws_access_token"]
	if hasAwsId || hasAwsSecret || hasAwsToken {
		creds = credentials.NewStaticCredentials(
			u.Query().Get("aws_access_key_id"),
			u.Query().Get("aws_access_key_secret"),
			u.Query().Get("aws_access_token"),
		)
	}

	return
}


text:
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2007 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================

#include "ISOBaseMedia_Support.hpp"
#include "XMPFiles_Impl.hpp"

// =================================================================================================
/// \file ISOBaseMedia_Support.cpp
/// \brief Manager for parsing and serializing ISO Base Media files ( MPEG-4 and JPEG-2000).
///
// =================================================================================================

namespace ISOMedia {

static BoxInfo voidInfo;

// =================================================================================================
// GetBoxInfo - from memory
// ========================

const XMP_Uns8 * GetBoxInfo ( const XMP_Uns8 * boxPtr, const XMP_Uns8 * boxLimit,
							  BoxInfo * info, bool throwErrors /* = false */ )
{
	XMP_Uns32 u32Size;

	if ( info == 0 ) info = &voidInfo;
	info->boxType = info->headerSize = 0;
	info->contentSize = 0;

	if ( boxPtr >= boxLimit ) XMP_Throw ( "Bad offset to GetBoxInfo", kXMPErr_InternalFailure );

	if ( (boxLimit - boxPtr) < 8 ) {	// Is there enough space for a standard box header?
		if ( throwErrors ) XMP_Throw ( "No space for ISO box header", kXMPErr_BadFileFormat );
		info->headerSize = (XMP_Uns32) (boxLimit - boxPtr);
		return boxLimit;
	}

	u32Size = GetUns32BE ( boxPtr );
	info->boxType = GetUns32BE ( boxPtr+4 );

	if ( u32Size >= 8 ) {
		info->headerSize  = 8;	// Normal explicit size case.
		info->contentSize = u32Size - 8;
	} else if ( u32Size == 0 ) {
		info->headerSize  = 8;	// The box goes to EoF - treat it as "to limit".
		info->contentSize = (boxLimit - boxPtr) - 8;
	} else if ( u32Size != 1 ) {
		if ( throwErrors ) XMP_Throw ( "Bad ISO box size, 2..7", kXMPErr_BadFileFormat );
		info->headerSize  = 8;	// Bad total size in the range of 2..7, treat as 8.
		info->contentSize = 0;
	} else {
		if ( (boxLimit - boxPtr) < 16 ) {	// Is there enough space for an extended box header?
			if ( throwErrors ) XMP_Throw ( "No space for ISO extended header", kXMPErr_BadFileFormat );
			info->headerSize = (XMP_Uns32) (boxLimit - boxPtr);
			return boxLimit;
		}
		XMP_Uns64 u64Size = GetUns64BE ( boxPtr+8 );
		if ( u64Size < 16 ) {
			if ( throwErrors ) XMP_Throw ( "Bad ISO extended box size, < 16", kXMPErr_BadFileFormat );
			u64Size = 16;	// Treat bad total size as 16.
		}
		info->headerSize  = 16;
		info->contentSize = u64Size - 16;
	}

	XMP_Assert ( (XMP_Uns64)(boxLimit - boxPtr) >= (XMP_Uns64)info->headerSize );
	if ( info->contentSize > (XMP_Uns64)((boxLimit - boxPtr) - info->headerSize) ) {
		if ( throwErrors ) XMP_Throw ( "Bad ISO box content size", kXMPErr_BadFileFormat );
		info->contentSize = ((boxLimit - boxPtr) - info->headerSize);	// Trim a bad content size to the limit.
	}

	return (boxPtr + info->headerSize + info->contentSize);

}	// GetBoxInfo

// =================================================================================================
// GetBoxInfo - from a file
// ========================

XMP_Uns64 GetBoxInfo ( LFA_FileRef fileRef, const XMP_Uns64 boxOffset, const XMP_Uns64 boxLimit,
					   BoxInfo * info, bool doSeek /* = true */, bool throwErrors /* = false */ )
{
	XMP_Uns8  buffer [8];
	XMP_Uns32 u32Size;

	if ( info == 0 ) info = &voidInfo;
	info->boxType = info->headerSize = 0;
	info->contentSize = 0;

	if ( boxOffset >= boxLimit ) XMP_Throw ( "Bad offset to GetBoxInfo", kXMPErr_InternalFailure );

	if ( (boxLimit - boxOffset) < 8 ) {	// Is there enough space for a standard box header?
		if ( throwErrors ) XMP_Throw ( "No space for ISO box header", kXMPErr_BadFileFormat );
		info->headerSize = (XMP_Uns32) (boxLimit - boxOffset);
		return boxLimit;
	}

	if ( doSeek ) LFA_Seek ( fileRef, boxOffset, SEEK_SET );
	(void) LFA_Read ( fileRef, buffer, 8, kLFA_RequireAll );

	u32Size = GetUns32BE ( &buffer[0] );
	info->boxType = GetUns32BE ( &buffer[4] );

	if ( u32Size >= 8 ) {
		info->headerSize  = 8;	// Normal explicit size case.
		info->contentSize = u32Size - 8;
	} else if ( u32Size == 0 ) {
		info->headerSize  = 8;	// The box goes to EoF.
		info->contentSize = LFA_Measure(fileRef) - (boxOffset + 8);
	} else if ( u32Size != 1 ) {
		if ( throwErrors ) XMP_Throw ( "Bad ISO box size, 2..7", kXMPErr_BadFileFormat );
		info->headerSize  = 8;	// Bad total size in the range of 2..7, treat as 8.
		info->contentSize = 0;
	} else {
		if ( (boxLimit - boxOffset) < 16 ) {	// Is there enough space for an extended box header?
			if ( throwErrors ) XMP_Throw ( "No space for ISO extended header", kXMPErr_BadFileFormat );
			info->headerSize = (XMP_Uns32) (boxLimit - boxOffset);
			return boxLimit;
		}
		(void) LFA_Read ( fileRef, buffer, 8, kLFA_RequireAll );
		XMP_Uns64 u64Size = GetUns64BE ( &buffer[0] );
		if ( u64Size < 16 ) {
			if ( throwErrors ) XMP_Throw ( "Bad ISO extended box size, < 16", kXMPErr_BadFileFormat );
			u64Size = 16;	// Treat bad total size as 16.
		}
		info->headerSize  = 16;
		info->contentSize = u64Size - 16;
	}

	XMP_Assert ( (boxLimit - boxOffset) >= info->headerSize );
	if ( info->contentSize > (boxLimit - boxOffset - info->headerSize) ) {
		if ( throwErrors ) XMP_Throw ( "Bad ISO box content size", kXMPErr_BadFileFormat );
		info->contentSize = (boxLimit - boxOffset - info->headerSize);	// Trim a bad content size to the limit.
	}

	return (boxOffset + info->headerSize + info->contentSize);

}	// GetBoxInfo

}	// namespace ISO_Media

// =================================================================================================


text:
ACCEPTED

#### According to
GRIN Taxonomy for Plants

#### Published in
Candollea 13:266. 1952

#### Original name
null

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html  PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>

<title>Twisted Documentation: Choosing a Reactor and GUI Toolkit Integration</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>

Choosing a Reactor and GUI Toolkit Integration

Overview

Reactor Functionality

General Purpose Reactors

Select()-based Reactor

Poll()-based Reactor

Platform-Specific Reactors

KQueue

Win32 (WFMO)

Win32 (IOCP)

Epoll-based Reactor

GUI Integration Reactors

GTK+

CoreFoundation

Non-Reactor GUI Integration

Tkinter

wxPython

PyUI

Overview

Twisted provides a variety of implementations of the twisted.internet.reactor.  The specialized
    implementations are suited for different purposes and are
    designed to integrate better with particular platforms.

The general purpose reactor implementations are:

The select()-based reactor

The poll()-based reactor

Platform-specific reactor implementations exist for:

KQueue for FreeBSD and OS X

Win32 (WFMO)

Win32 (IOCP)

Mac OS X

Epoll for Linux 2.6

The remaining custom reactor implementations provide support
    for integrating with the native event loops of various graphical
    toolkits.  This lets your Twisted application use all of the
    usual Twisted APIs while still being a graphical application.

Twisted currently integrates with the following graphical
    toolkits:

GTK+ 1.2 and 2.0

Tkinter

WxPython

Win32

CoreFoundation

PyUI

When using applications that runnable using twistd, e.g.
       TAPs or plugins, there is no need to choose a reactor explicitly, since
       this can be chosen using twistd's -r option.

In all cases, the event loop is started by calling reactor.run(). In all cases, the event loop
    should be stopped with reactor.stop().

IMPORTANT: installing a reactor should be the first thing
    done in the app, since any code that does
    from twisted.internet import reactor will automatically
    install the default reactor if the code hasn't already installed one.

Reactor Functionality

Status	TCP	SSL	UDP	Threading	Processes	Scheduling	Platforms

select()	Stable	Y	Y	Y	Y	Y	Y	Unix, Win32

poll()	Stable	Y	Y	Y	Y	Y	Y	Unix

Win32 (WFMO)	Experimental	Y	Y	Y	Y	Y	Y	Win32

Win32 (IOCP)	Experimental	Y	Y	N	N	N	Y	Win32

CoreFoundation	Unmaintained	Y	Y	Y	Y	Y	Y	OS X

epoll	Stable	Y	Y	Y	Y	Y	Y	Linux 2.6

Gtk	Stable	Y	Y	Y	Y	Y	Y	Unix, Win32

wx	Experimental	Y	Y	Y	Y	Y	Y	Unix, Win32

kqueue	Experimental	Y	Y	Y	Y	Y	Y	FreeBSD

General Purpose Reactors

Select()-based Reactor

The select reactor is currently the default reactor on all
    platforms. The following code will install it, if no other reactor has
    been installed:

1

from twisted.internet import reactor

In the future, if another reactor becomes the default, but the
    select reactor is desired, it may be installed via:

1
2
3
4

from twisted.internet import selectreactor
selectreactor.install()

from twisted.internet import reactor

Poll()-based Reactor

The PollReactor will work on any platform that provides poll() (while OS X provides poll(), it is not recommended to use the
    PollReactor on OS X due to bugs in its implementation of the call).
    With larger numbers of connected sockets, it may provide for better
    performance than the SelectReactor.

1
2
3
4

from twisted.internet import pollreactor
pollreactor.install()

from twisted.internet import reactor

Platform-Specific Reactors

KQueue

The KQueue Reactor allows Twisted to use FreeBSD's kqueue mechanism for
       event scheduling. See instructions in the twisted.internet.kqreactor's
       docstring for installation notes.

1
2
3
4

from twisted.internet import kqreactor
kqreactor.install()

from twisted.internet import reactor

Win32 (WFMO)

The Win32 reactor is not yet complete and has various limitations
    and issues that need to be addressed.  The reactor supports GUI integration
    with the win32gui module, so it can be used for native Win32 GUI applications.

1
2
3
4

from twisted.internet import win32eventreactor
win32eventreactor.install()

from twisted.internet import reactor

Win32 (IOCP)

    Windows provides a fast, scalable event notification system known as IO
    Completion Ports, or IOCP for short.  Twisted includes a reactor based
    on IOCP which is nearly complete.  The reactor has a handful of known
    bugs and lacks SSL support.

1
2
3
4

from twisted.internet import iocpreactor
iocpreactor.install()

from twisted.internet import reactor

Epoll-based Reactor

The EPollReactor will work on any platform that provides
    epoll, today only Linux 2.6 and over. The
    implementation of the epoll reactor currently uses the Level Triggered
    interface, which is basically like poll() but scales much better.

1
2
3
4

from twisted.internet import epollreactor
epollreactor.install()

from twisted.internet import reactor

GUI Integration Reactors

GTK+

Twisted integrates with PyGTK, versions 1.2 (gtkreactor) and 2.0
    (gtk2reactor). Sample applications using GTK+ and
    Twisted are available in the Twisted SVN.

GTK-2.0 split the event loop out of the GUI toolkit, into a separate
    module called <q>glib</q>. To run an application using the glib event
    loop, use the glib2reactor. This will be slightly faster
    than gtk2reactor (and does not require a working X display),
    but cannot be used to run GUI applications.

1
2
3
4

from twisted.internet import gtkreactor # for gtk-1.2
gtkreactor.install()

from twisted.internet import reactor

1
2
3
4

from twisted.internet import gtk2reactor # for gtk-2.0
gtk2reactor.install()

from twisted.internet import reactor

1
2
3
4

from twisted.internet import glib2reactor # for non-GUI apps
glib2reactor.install()

from twisted.internet import reactor

CoreFoundation

Twisted integrates with PyObjC, version 1.0.  Sample applications using Cocoa and Twisted
    are available in the examples directory under
    threadedselect/Cocoa.

1
2
3
4

from twisted.internet import cfreactor
cfreactor.install()

from twisted.internet import reactor

Non-Reactor GUI Integration

Tkinter

The support for Tkinter doesn't use a specialized reactor.  Instead, there is
    some specialized support code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

from Tkinter import *
from twisted.internet import tksupport

root = Tk()

# Install the Reactor support
tksupport.install(root)

# at this point build Tk app as usual using the root object,
# and start the program with "reactor.run()", and stop it
# with "reactor.stop()".

wxPython

Twisted currently supports two methods of integrating
    wxPython. Unfortunately, neither method will work on all wxPython
    platforms (such as GTK2 or Windows). It seems that the only
    portable way to integrate with wxPython is to run it in a separate
    thread. One of these methods may be sufficient if your wx app is
    limited to a single platform.

As with Tkinter, the support for integrating
    Twisted with a wxPython
    application uses specialized support code rather than a simple reactor.

1
2
3
4
5

from wxPython.wx import *
from twisted.internet import wxsupport, reactor

myWxAppInstance = wxApp(0)
wxsupport.install(myWxAppInstance)

However, this has issues when running on Windows, so Twisted now
    comes with alternative wxPython support using a reactor. Using
    this method is probably better. Initialization is done in two
    stages. In the first, the reactor is installed:

1
2

from twisted.internet import wxreactor
wxreactor.install()

Later, once a wxApp instance has
    been created, but before reactor.run()
    is called:

1
2

myWxAppInstance = wxApp(0)
reactor.registerWxApp(myWxAppInstance)

An example Twisted application that uses WxWindows can be found
    in doc/examples/wxdemo.py.

PyUI

As with Tkinter, the support for integrating
    Twisted with a PyUI
    application uses specialized support code rather than a simple reactor.

1
2
3

from twisted.internet import pyuisupport, reactor

pyuisupport.install(args=(640, 480), kw={'renderer': 'gl'})

An example Twisted application that uses PyUI can be found in doc/examples/pyuidemo.py.

Index

    Version: 10.0.0


text:
package com.orbekk.protobuf;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.protobuf.Descriptors;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.Service;

public class RequestDispatcher extends Thread {
    private static final Logger logger = Logger.getLogger(RequestDispatcher.class.getName());
    public static int DEFAULT_QUEUE_SIZE = 5;
    private volatile boolean isStopped = false;
    private final BlockingQueue<Data.Response> output;
    private final ServiceHolder services;

    /** A pool that can be shared among all dispatchers. */
    private final ExecutorService pool;

    private static class RequestHandler implements Runnable {
        private final Data.Request request;
        private final Data.Response.Builder response =
                Data.Response.newBuilder();
        private final BlockingQueue<Data.Response> output;
        private final ServiceHolder services;
        private final Rpc rpc = new Rpc();

        private final RpcCallback<Message> callback =
                new RpcCallback<Message>() {
            @Override public void run(Message responseMessage) {
                if (responseMessage == null && rpc.isOk()) {
                    throw new IllegalStateException(
                            "responseMessage is null, but rpc is ok:  " +
                            rpc);
                }
                if (responseMessage != null) {
                    response.setResponseProto(responseMessage.toByteString());
                }
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer(String.format("I(%d): %s <= ",
                            request.getRequestId(), responseMessage));
                }
                rpc.writeTo(response);
                try {
                    output.put(response.build());
                } catch (InterruptedException e) {
                    // Terminate callback.
                    return;
                }
            }
        };

        public RequestHandler(Data.Request request,
                BlockingQueue<Data.Response> output,
                ServiceHolder services) {
            this.request = request;
            this.output = output;
            this.services = services;
        }

        public void internalRun() throws InterruptedException {
            response.setRequestId(request.getRequestId());
            Service service = services.get(request.getFullServiceName());
            if (service == null) {
                response.setError(Data.Response.RpcError.UNKNOWN_SERVICE);
                output.put(response.build());
                return;
            }

            Descriptors.MethodDescriptor method =
                    service.getDescriptorForType()
                            .findMethodByName(request.getMethodName());
            if (method == null) {
                response.setError(Data.Response.RpcError.UNKNOWN_METHOD);
                output.put(response.build());
                return;
            }

            Message requestMessage = null;
            try {
                requestMessage = service.getRequestPrototype(method)
                        .toBuilder().mergeFrom(request.getRequestProto()).build();
            } catch (InvalidProtocolBufferException e) {
                response.setError(Data.Response.RpcError.INVALID_PROTOBUF);
                output.put(response.build());
                return;
            }

            if (logger.isLoggable(Level.FINER)) {
                logger.fine(String.format("I(%d) => %s(%s)",
                        request.getRequestId(),
                        method.getFullName(),
                        requestMessage));
            }
            service.callMethod(method, rpc, requestMessage, callback);
        }

        @Override public void run() {
            try {
                internalRun();
            } catch (InterruptedException e) {
                // Terminate request.
                return;
            }
        }
    }

    public RequestDispatcher(ExecutorService pool,
            BlockingQueue<Data.Response> output,
            ServiceHolder services) {
        this.pool = pool;
        this.output = output;
        this.services = services;
    }

    public void handleRequest(Data.Request request) throws InterruptedException {
        RequestHandler handler = new RequestHandler(request, output, services);
        pool.execute(handler);
    }
}


text:
<?php

namespace Kunstmaan\LeadGenerationBundle\Controller;

use Kunstmaan\AdminListBundle\AdminList\Configurator\AdminListConfiguratorInterface;
use Kunstmaan\AdminListBundle\Controller\AdminListController;
use Kunstmaan\LeadGenerationBundle\AdminList\RulesAdminListConfigurator;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

class RulesAdminListController extends AdminListController
{
    /**
     * @var RulesAdminListConfigurator
     */
    private $configurator;

    /**
     * @return AdminListConfiguratorInterface
     */
    public function getAdminListConfigurator($id)
    {
        if (!isset($this->configurator)) {
            $this->configurator = new RulesAdminListConfigurator($this->getEntityManager(), null, $id);
        }

        return $this->configurator;
    }

    /**
     * The detail action
     *
     * @Route("/{popup}/rules", requirements={"popup" = "\d+"}, name="kunstmaanleadgenerationbundle_admin_rule_abstractrule_detail")
     */
    public function detailAction(Request $request, $popup)
    {
        return parent::doIndexAction($this->getAdminListConfigurator($popup), $request);
    }

    /**
     * The add action
     *
     * @Route("/{popup}/add", requirements={"popup" = "\d+"}, name="kunstmaanleadgenerationbundle_admin_rule_abstractrule_add")
     * @Method({"GET", "POST"})
     *
     * @return array
     */
    public function addAction(Request $request, $popup)
    {
        $type = $request->get('type');

        return parent::doAddAction($this->getAdminListConfigurator($popup), $type, $request);
    }

    /**
     * The edit action
     *
     * @param int $id
     *
     * @Route("/{popup}/rules/{id}/edit", requirements={"popup" = "\d+", "rule" = "\d+"}, name="kunstmaanleadgenerationbundle_admin_rule_abstractrule_edit")
     * @Method({"GET", "POST"})
     *
     * @return array
     */
    public function editAction(Request $request, $id, $popup)
    {
        return parent::doEditAction($this->getAdminListConfigurator($popup), $id, $request);
    }

    /**
     * The delete action
     *
     * @param int $id
     *
     * @Route("/{popup}/rules/{id}/delete", requirements={"popup" = "\d+"}, name="kunstmaanleadgenerationbundle_admin_rule_abstractrule_delete")
     * @Method({"GET", "POST"})
     *
     * @return array
     */
    public function deleteAction(Request $request, $id, $popup)
    {
        return parent::doDeleteAction($this->getAdminListConfigurator($popup), $id, $request);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/medical-supplies/optidisc" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/medical-supplies/optidisc</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Optidisc</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/medical-supplies/optidisc</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/medical-supplies/optidisc</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
define([], function () {

    // Defines the logger object
    var logger = {
        log: function () {},
        info: function () {},
        warn: function () {},
        error: function () {}
    };

    // We can run StackEdit with http://.../?console to print logs in the console
    return (/(\?|&)console($|&)/).test(location.search) ? console : logger;
});


text:
#include "jerryscript-mbed-library-registry/registry.h"

mbed::js::LibraryRegistry mbed::js::LibraryRegistry::instance;


text:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView, ListView
from django.views.generic.dates import ArchiveIndexView

# COMMENTS
from .models import Comment
from .views import (
    comment_archive_view,
    delete_comment_view,
    CommentDetailView,
    CommentCreateView,
    CommentUpdateView,
)

urlpatterns = patterns('',
    # comment items
    url(r'^create/$',
            view=CommentCreateView.as_view(), name='create_comment'),
    url(r'^(?P<pk>\d+)/$',
            view=CommentDetailView.as_view(), name='comment'),
    url(r'^update/(?P<pk>\d+)/$',
            view=CommentUpdateView.as_view(), name='update_comment'),
    url(r'^delete/(?P<pk>\d+)/$',
            view=delete_comment_view, name='delete_comment'),
    url(r'^$', view=comment_archive_view, name='current_comments'),
    url(r'^page/(?P<page>\d+)/$', view=comment_archive_view,
            name='current_comments_paginated'),
)


text:
package com.qtfreet.devasimpleapp.ui.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by Bear on 2016/1/29.
 */
public class FragmentAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;
    private List<String> titles;

    public FragmentAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titles) {
        super(fm);
        this.fragments = fragments;
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}


text:
#ifndef IDL_GENSPLICELITETYPE_H
#define IDL_GENSPLICELITETYPE_H

#include "idl_program.h"

idl_program idl_genSpliceLiteTypeProgram (void);

void
idl_genSpliceLiteTypeSetTestMode (
    c_bool val);

void
idl_genSpliceLiteTypeSetIncludeFileName (
    os_char* val);

void
idl_genSpliceLiteTypeUseVoidPtrs (
    c_bool val);

#endif /* IDL_GENSPLICELITETYPE_H */


text:
> Animai-vos uns aos outros, enquanto ainda se disser 'hoje'.

**Leitura da Carta aos Hebreus 3,7-14**

Irmãos:
7 Escutai o que declara o Espírito Santo:
 'Hoje, se ouvirdes a sua voz,
8 não endureçais os vossos corações,
 como aconteceu na provacação,
 no dia da tentação, no deserto,
9 onde vossos pais me tentaram, colocando-me à prova,
10 embora vissem as minhas obras,
 durante quarenta anos.
 Por isso me irritei com essa geração
 e afirmei: sempre se enganam no coração
 e desconhecem os meus caminhos.
11 Assim jurei em minha ira:
 não entrarão no meu repouso'.
12 Cuidai, irmãos, que não se ache em algum de vós
 um coração transviado pela incredulidade,
 levando-o a afastar-se do Deus vivo.
13 Antes, animai-vos uns aos outros, dia após dia,
 enquanto ainda se disser 'hoje',
 para que nenhum de vós se endureça
 pela sedução do pecado
14 - pois tornamo-nos companheiros de Cristo,
 contanto que mantenhamos firme até ao fim
 a nossa confiança inicial.
 Palavra do Senhor.

## Salmo - Sl 94, 6-7. 8-9. 10-11 (R. 8)

`R. Oxalá ouvísseis hoje a sua voz:Não fecheis os vossos corações.`

6 Vinde adoremos e prostremo-nos por terra, *
 e ajoelhemos ante o Deus que nos criou!
7 Porque ele é o nosso Deus, nosso Pastor, +
 e nós somos o seu povo e seu rebanho, *
 as ovelhas que conduz com sua mão. R.
8 Oxalá ouvísseis hoje a sua voz: +
 'Não fecheis os corações como em Meriba, *
9 como em Massa, no deserto, aquele dia,
 em que outrora vossos pais me provocaram, *
 apesar de terem visto as minhas obras'. R.
10 Quarenta anos desgostou-me aquela raça +
 e eu disse: 'Eis um povo transviado, *
11 seu coração não conheceu os meus caminhos!'
 E por isso lhes jurei na minha ira: *
 'Não entrarão no meu repouso prometido!' R.

## Evangelho - Mc 1,40-45

> A lepra desapareceu e o homem ficou curado

**+ Proclamação do Evangelho de Jesus Cristo segundo Marcos 1,40-45**

Naquele tempo:
40 Um leproso chegou perto de Jesus,
 e de joelhos pediu:
 'Se queres tens o poder de curar-me'.
41 Jesus, cheio de compaixão,
 estendeu a mão, tocou nele, e disse:
 'Eu quero: fica curado!'
42 No mesmo instante a lepra desapareceu
 e ele ficou curado.
43 Então Jesus o mandou logo embora,
44 falando com firmeza:
 'Não contes nada disso a ninguém!
 Vai, mostra-te ao sacerdote
 e oferece, pela tua purificação, o que Moisés ordenou,
 como prova para eles!'
45 Ele foi e começou a contar
 e a divulgar muito o fato.
 Por isso Jesus não podia mais
 entrar publicamente numa cidade:
 ficava fora, em lugares desertos.
 E de toda parte vinham procurá-lo.
 Palavra da Salvação.

## Reflexão - Mc 1, 40-45

Uma das promessas que sempre estão presentes nas profecias do Antigo Testamento a respeito dos tempos messiânicos é a cura da lepra. Isso acontece porque a lepra era uma das doenças mais temidas entre as pessoas, principalmente porque uma das suas conseqüências era a exclusão social e religiosa. Ao curar uma pessoa da lepra, Jesus não apenas o livra da doença em si que a faz sofrer como também a reintegra na vida social e religiosa. Por isso entendemos a alegria do homem que foi curado, que fez com que ele não fosse capaz de guardar o fato só para si, mas passou a divulgá-lo de tal modo que Jesus não podia mais aparecer em público.

Veja mais no [Liturgia Diária - CNBB](http://liturgiadiaria.cnbb.org.br/app/user/user/UserView.php?ano=2017&mes=1&dia=12)


text:
<!DOCTYPE html>

<title>Blog</title>
<link  href="http://fonts.googleapis.com/css?family=Droid+Sans+Mono" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="stylesheets/main.css" />

Blog


text:
project_path: /web/_project.yaml
book_path: /web/updates/_book.yaml

{# wf_updated_on: 2011-12-09 #}
{# wf_published_on: 2011-12-09 #}
{# wf_tags: news,binary,performance,workers #}

# Transferable Objects: Lightning Fast! {: .page-title }

{% include "web/_shared/contributors/ericbidelman.html" %}

Chrome 13 introduced sending `ArrayBuffer`s to/from a Web Worker using an algorithm called [structured cloning](http://updates.html5rocks.com/2011/09/Workers-ArrayBuffer). This allowed the `postMessage()` API to accept messages that were not just strings, but complex types like `File`, `Blob`, `ArrayBuffer`, and JSON objects. Structured cloning is also supported in later versions of Firefox.

### Faster is better

Structured cloning is great, but it's still a copy operation. The overhead of passing a 32MB `ArrayBuffer` to a Worker can be hundreds of milliseconds.
New versions of browsers contain a huge performance improvement for message passing, called [Transferable Objects](http://dev.w3.org/html5/spec/common-dom-interfaces.html#transferable-objects).

With transferable objects, data is transferred from one context to another. It is zero-copy, which vastly improves the performance of sending data to a Worker. Think of it as pass-by-reference if you're from the C/C++ world. However, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred to the new context. For example, when transferring an `ArrayBuffer` from your main app to Worker, the original `ArrayBuffer` is cleared and no longer usable. Its contents are (quiet literally) transferred to the Worker context.

To play with transferables, there's a new version of `postMessage()` that supports transferable objects:

    worker.webkitPostMessage(arrayBuffer, [arrayBuffer]);
    window.webkitPostMessage(arrayBuffer, targetOrigin, [arrayBuffer]);

For the worker case, the first argument is the `ArrayBuffer` message. The second argument is a list of items that should be transferred.

### Benchmark demo

To see the performance gains of transferrables, I've put together [a demo](http://html5-demos.appspot.com/static/workers/transferables/index.html).

The demo sends a 32MB `ArrayBuffer` to a worker and back using `webkitPostMessage()`. If your browser doesn't support transferables, the sample falls back to structured cloning. Averaging 5 runs in different browsers, here's what I got:

On a MacBook Pro/10.6.8/2.53 GHz/Intel Core 2 Duo, FF was the fastest using structured cloning. On average, it took 302ms to send the 32MB `ArrayBuffer` to a worker and post it back to the main thread (RRT - Round Trip Time). Comparing that with transferables, the same test took 6.6ms. That is a huge perf boost!

Having these kinds of speeds allows massive WebGL textures/meshes to be seamlessly passed between a Worker and main app.

### Feature detecting

Feature detecting is a bit tricky with this one. My recommendation is to send a small `ArrayBuffer` to your worker. If the buffer is transferred and not copied, its `.byteLength` will go to 0:

    worker.postMessage = worker.webkitPostMessage || worker.postMessage;

    var ab = new ArrayBuffer(1);
    worker.postMessage(ab, [ab]);
    if (ab.byteLength) {
      alert('Transferables are not supported in your browser!');
    } else {
      // Transferables are supported.
    }

*Support:* Currently Chrome 17+, Firefox, Opera, Safari, and IE10+

*Updated (2011-12-13):* Code snippet to show `webkitPostMessage()` signature is different for window and worker.

{% include "comment-widget.html" %}


text:
FOUNDATION_EXPORT double Pods_Trail_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_Trail_TestsVersionString[];


text:
package wad.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import wad.domain.Permission;

public interface PermissionRepository extends JpaRepository<Permission, Long> {
    public Permission findByName(String name);
}