text:
// Copyright 2015 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.skyframe;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.base.Objects;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Callables;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Executor;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.actions.util.DummyExecutor;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.build.skyframe.EvaluationProgressReceiver;
import com.google.devtools.build.skyframe.EvaluationProgressReceiver.EvaluationState;
import com.google.devtools.build.skyframe.SkyFunction.Environment;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link SkyframeAwareAction}. */
@RunWith(JUnit4.class)
public class SkyframeAwareActionTest extends TimestampBuilderTestCase {
  private Builder builder;
  private Executor executor;
  private TrackingEvaluationProgressReceiver progressReceiver;

  @Before
  public final void createBuilder() throws Exception {
    progressReceiver = new TrackingEvaluationProgressReceiver();
    builder = createBuilder(inMemoryCache, 1, /*keepGoing=*/ false, progressReceiver);
  }

  @Before
  public final void createExecutor() throws Exception {
    executor = new DummyExecutor(rootDirectory);
  }

  private static final class TrackingEvaluationProgressReceiver
      extends EvaluationProgressReceiver.NullEvaluationProgressReceiver {

    public static final class InvalidatedKey {
      public final SkyKey skyKey;
      public final InvalidationState state;

      InvalidatedKey(SkyKey skyKey, InvalidationState state) {
        this.skyKey = skyKey;
        this.state = state;
      }

      @Override
      public boolean equals(Object obj) {
        return obj instanceof InvalidatedKey
            && this.skyKey.equals(((InvalidatedKey) obj).skyKey)
            && this.state.equals(((InvalidatedKey) obj).state);
      }

      @Override
      public int hashCode() {
        return Objects.hashCode(skyKey, state);
      }
    }

    public static final class EvaluatedEntry {
      public final SkyKey skyKey;
      public final SkyValue value;
      public final EvaluationState state;

      EvaluatedEntry(SkyKey skyKey, SkyValue value, EvaluationState state) {
        this.skyKey = skyKey;
        this.value = value;
        this.state = state;
      }

      @Override
      public boolean equals(Object obj) {
        return obj instanceof EvaluatedEntry
            && this.skyKey.equals(((EvaluatedEntry) obj).skyKey)
            && this.value.equals(((EvaluatedEntry) obj).value)
            && this.state.equals(((EvaluatedEntry) obj).state);
      }

      @Override
      public int hashCode() {
        return Objects.hashCode(skyKey, value, state);
      }
    }

    public final Set<InvalidatedKey> invalidated = Sets.newConcurrentHashSet();
    public final Set<SkyKey> enqueued = Sets.newConcurrentHashSet();
    public final Set<EvaluatedEntry> evaluated = Sets.newConcurrentHashSet();

    public void reset() {
      invalidated.clear();
      enqueued.clear();
      evaluated.clear();
    }

    public boolean wasInvalidated(SkyKey skyKey) {
      for (InvalidatedKey e : invalidated) {
        if (e.skyKey.equals(skyKey)) {
          return true;
        }
      }
      return false;
    }

    public EvaluatedEntry getEvalutedEntry(SkyKey forKey) {
      for (EvaluatedEntry e : evaluated) {
        if (e.skyKey.equals(forKey)) {
          return e;
        }
      }
      return null;
    }

    @Override
    public void invalidated(SkyKey skyKey, InvalidationState state) {
      invalidated.add(new InvalidatedKey(skyKey, state));
    }

    @Override
    public void enqueueing(SkyKey skyKey) {
      enqueued.add(skyKey);
    }

    @Override
    public void evaluated(
        SkyKey skyKey, Supplier<SkyValue> skyValueSupplier, EvaluationState state) {
      evaluated.add(new EvaluatedEntry(skyKey, skyValueSupplier.get(), state));
    }
  }

  /** A mock action that counts how many times it was executed. */
  private static class ExecutionCountingAction extends AbstractAction {
    private final AtomicInteger executionCounter;

    ExecutionCountingAction(Artifact input, Artifact output, AtomicInteger executionCounter) {
      super(ActionsTestUtil.NULL_ACTION_OWNER, ImmutableList.of(input), ImmutableList.of(output));
      this.executionCounter = executionCounter;
    }

    @Override
    public void execute(ActionExecutionContext actionExecutionContext)
        throws ActionExecutionException, InterruptedException {
      executionCounter.incrementAndGet();

      // This action first reads its input file (there can be only one). For the purpose of these
      // tests we assume that the input file is short, maybe just 10 bytes long.
      byte[] input = new byte[10];
      int inputLen = 0;
      try (InputStream in = Iterables.getOnlyElement(getInputs()).getPath().getInputStream()) {
        inputLen = in.read(input);
      } catch (IOException e) {
        throw new ActionExecutionException(e, this, false);
      }

      // This action then writes the contents of the input to the (only) output file, and appends an
      // extra "x" character too.
      try (OutputStream out = getPrimaryOutput().getPath().getOutputStream()) {
        out.write(input, 0, inputLen);
        out.write('x');
      } catch (IOException e) {
        throw new ActionExecutionException(e, this, false);
      }
    }

    @Override
    public String getMnemonic() {
      return null;
    }

    @Override
    protected String computeKey() {
      return getPrimaryOutput().getExecPathString() + executionCounter.get();
    }
  }

  private static class ExecutionCountingCacheBypassingAction extends ExecutionCountingAction {
    ExecutionCountingCacheBypassingAction(
        Artifact input, Artifact output, AtomicInteger executionCounter) {
      super(input, output, executionCounter);
    }

    @Override
    public boolean executeUnconditionally() {
      return true;
    }

    @Override
    public boolean isVolatile() {
      return true;
    }
  }

  /** A mock skyframe-aware action that counts how many times it was executed. */
  private static class SkyframeAwareExecutionCountingAction
      extends ExecutionCountingCacheBypassingAction implements SkyframeAwareAction {
    private final SkyKey actionDepKey;

    SkyframeAwareExecutionCountingAction(
        Artifact input, Artifact output, AtomicInteger executionCounter, SkyKey actionDepKey) {
      super(input, output, executionCounter);
      this.actionDepKey = actionDepKey;
    }

    @Override
    public void establishSkyframeDependencies(Environment env)
        throws ExceptionBase, InterruptedException {
      // Establish some Skyframe dependency. A real action would then use this to compute and
      // cache data for the execute(...) method.
      env.getValue(actionDepKey);
    }
  }

  private interface ExecutionCountingActionFactory {
    ExecutionCountingAction create(Artifact input, Artifact output, AtomicInteger executionCounter);
  }

  private enum ChangeArtifact {
    DONT_CHANGE,
    CHANGE_MTIME {
      @Override
      boolean changeMtime() {
        return true;
      }
    },
    CHANGE_MTIME_AND_CONTENT {
      @Override
      boolean changeMtime() {
        return true;
      }

      @Override
      boolean changeContent() {
        return true;
      }
    };

    boolean changeMtime() {
      return false;
    }

    boolean changeContent() {
      return false;
    }
  }

  private enum ExpectActionIs {
    NOT_DIRTIED {
      @Override
      boolean actuallyClean() {
        return true;
      }
    },
    DIRTIED_BUT_VERIFIED_CLEAN {
      @Override
      boolean dirtied() {
        return true;
      }

      @Override
      boolean actuallyClean() {
        return true;
      }
    },

    // REBUILT_BUT_ACTION_CACHE_HIT,
    // This would be a bug, symptom of a skyframe-aware action that doesn't bypass the action cache
    // and is incorrectly regarded as an action cache hit when its inputs stayed the same but its
    // "skyframe dependencies" changed.

    REEXECUTED {
      @Override
      boolean dirtied() {
        return true;
      }

      @Override
      boolean reexecuted() {
        return true;
      }
    };

    boolean dirtied() {
      return false;
    }

    boolean actuallyClean() {
      return false;
    }

    boolean reexecuted() {
      return false;
    }
  }

  private void maybeChangeFile(Artifact file, ChangeArtifact changeRequest) throws Exception {
    if (changeRequest == ChangeArtifact.DONT_CHANGE) {
      return;
    }

    if (changeRequest.changeMtime()) {
      // 1000000 should be larger than the filesystem timestamp granularity.
      file.getPath().setLastModifiedTime(file.getPath().getLastModifiedTime() + 1000000);
      tsgm.waitForTimestampGranularity(reporter.getOutErr());
    }

    if (changeRequest.changeContent()) {
      appendToFile(file.getPath());
    }

    // Invalidate the file state value to inform Skyframe that the file may have changed.
    // This will also invalidate the action execution value.
    differencer.invalidate(
        ImmutableList.of(
            FileStateValue.key(
                RootedPath.toRootedPath(file.getRoot().getPath(), file.getRootRelativePath()))));
  }

  private void assertActionExecutions(
      ExecutionCountingActionFactory actionFactory,
      ChangeArtifact changeActionInput,
      Callable<Void> betweenBuilds,
      ExpectActionIs expectActionIs)
      throws Exception {
    // Set up the action's input, output, owner and most importantly the execution counter.
    Artifact actionInput = createSourceArtifact("foo/action-input.txt");
    Artifact actionOutput = createDerivedArtifact("foo/action-output.txt");
    AtomicInteger executionCounter = new AtomicInteger(0);

    scratch.file(actionInput.getPath().getPathString(), "foo");

    // Generating actions of artifacts are found by looking them up in the graph. The lookup value
    // must be present in the graph before execution.
    Action action = actionFactory.create(actionInput, actionOutput, executionCounter);
    registerAction(action);

    // Build the output for the first time.
    builder.buildArtifacts(
        reporter,
        ImmutableSet.of(actionOutput),
        null,
        null,
        null,
        null,
        executor,
        null,
        false,
        null,
        null);

    // Sanity check that our invalidation receiver is working correctly. We'll rely on it again.
    SkyKey actionKey = ActionExecutionValue.key(OWNER_KEY, 0);
    TrackingEvaluationProgressReceiver.EvaluatedEntry evaluatedAction =
        progressReceiver.getEvalutedEntry(actionKey);
    assertThat(evaluatedAction).isNotNull();
    SkyValue actionValue = evaluatedAction.value;

    // Mutate the action input if requested.
    maybeChangeFile(actionInput, changeActionInput);

    // Execute user code before next build.
    betweenBuilds.call();

    // Rebuild the output.
    progressReceiver.reset();
    builder.buildArtifacts(
        reporter,
        ImmutableSet.of(actionOutput),
        null,
        null,
        null,
        null,
        executor,
        null,
        false,
        null,
        null);

    if (expectActionIs.dirtied()) {
      assertThat(progressReceiver.wasInvalidated(actionKey)).isTrue();

      TrackingEvaluationProgressReceiver.EvaluatedEntry newEntry =
          progressReceiver.getEvalutedEntry(actionKey);
      assertThat(newEntry).isNotNull();
      if (expectActionIs.actuallyClean()) {
        // Action was dirtied but verified clean.
        assertThat(newEntry.state).isEqualTo(EvaluationState.CLEAN);
        assertThat(newEntry.value).isEqualTo(actionValue);
      } else {
        // Action was dirtied and rebuilt. It was either reexecuted or was an action cache hit,
        // doesn't matter here.
        assertThat(newEntry.state).isEqualTo(EvaluationState.BUILT);
        assertThat(newEntry.value).isNotEqualTo(actionValue);
      }
    } else {
      // Action was not dirtied.
      assertThat(progressReceiver.wasInvalidated(actionKey)).isFalse();
    }

    // Assert that the action was executed the right number of times. Whether the action execution
    // function was called again is up for the test method to verify.
    assertThat(executionCounter.get()).isEqualTo(expectActionIs.reexecuted() ? 2 : 1);
  }

  private RootedPath createSkyframeDepOfAction() throws Exception {
    scratch.file(rootDirectory.getRelative("action.dep").getPathString(), "blah");
    return RootedPath.toRootedPath(rootDirectory, PathFragment.create("action.dep"));
  }

  private void appendToFile(Path path) throws Exception {
    try (OutputStream stm = path.getOutputStream(/*append=*/ true)) {
      stm.write("blah".getBytes(StandardCharsets.UTF_8));
    }
  }

  @Test
  public void testCacheCheckingActionWithContentChangingInput() throws Exception {
    assertActionWithContentChangingInput(/* unconditionalExecution */ false);
  }

  @Test
  public void testCacheBypassingActionWithContentChangingInput() throws Exception {
    assertActionWithContentChangingInput(/* unconditionalExecution */ true);
  }

  private void assertActionWithContentChangingInput(final boolean unconditionalExecution)
      throws Exception {
    // Assert that a simple, non-skyframe-aware action is executed twice
    // if its input's content changes between builds.
    assertActionExecutions(
        new ExecutionCountingActionFactory() {
          @Override
          public ExecutionCountingAction create(
              Artifact input, Artifact output, AtomicInteger executionCounter) {
            return unconditionalExecution
                ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
                : new ExecutionCountingAction(input, output, executionCounter);
          }
        },
        ChangeArtifact.CHANGE_MTIME_AND_CONTENT,
        Callables.<Void>returning(null),
        ExpectActionIs.REEXECUTED);
  }

  @Test
  public void testCacheCheckingActionWithMtimeChangingInput() throws Exception {
    assertActionWithMtimeChangingInput(/* unconditionalExecution */ false);
  }

  @Test
  public void testCacheBypassingActionWithMtimeChangingInput() throws Exception {
    assertActionWithMtimeChangingInput(/* unconditionalExecution */ true);
  }

  private void assertActionWithMtimeChangingInput(final boolean unconditionalExecution)
      throws Exception {
    // Assert that a simple, non-skyframe-aware action is executed only once
    // if its input's mtime changes but its contents stay the same between builds.
    assertActionExecutions(
        new ExecutionCountingActionFactory() {
          @Override
          public ExecutionCountingAction create(
              Artifact input, Artifact output, AtomicInteger executionCounter) {
            return unconditionalExecution
                ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
                : new ExecutionCountingAction(input, output, executionCounter);
          }
        },
        ChangeArtifact.CHANGE_MTIME,
        Callables.<Void>returning(null),
        ExpectActionIs.DIRTIED_BUT_VERIFIED_CLEAN);
  }

  public void testActionWithNonChangingInput(final boolean unconditionalExecution)
      throws Exception {
    // Assert that a simple, non-skyframe-aware action is executed only once
    // if its input does not change at all between builds.
    assertActionExecutions(
        new ExecutionCountingActionFactory() {
          @Override
          public ExecutionCountingAction create(
              Artifact input, Artifact output, AtomicInteger executionCounter) {
            return unconditionalExecution
                ? new ExecutionCountingCacheBypassingAction(input, output, executionCounter)
                : new ExecutionCountingAction(input, output, executionCounter);
          }
        },
        ChangeArtifact.DONT_CHANGE,
        Callables.<Void>returning(null),
        ExpectActionIs.NOT_DIRTIED);
  }

  private void assertActionWithMaybeChangingInputAndChangingSkyframeDeps(
      ChangeArtifact changeInputFile) throws Exception {
    final RootedPath depPath = createSkyframeDepOfAction();
    final SkyKey skyframeDep = FileStateValue.key(depPath);

    // Assert that an action-cache-check-bypassing action is executed twice if its skyframe deps
    // change while its input does not. The skyframe dependency is established by making the action
    // skyframe-aware and updating the value between builds.
    assertActionExecutions(
        new ExecutionCountingActionFactory() {
          @Override
          public ExecutionCountingAction create(
              Artifact input, Artifact output, AtomicInteger executionCounter) {
            return new SkyframeAwareExecutionCountingAction(
                input, output, executionCounter, skyframeDep);
          }
        },
        changeInputFile,
        new Callable<Void>() {
          @Override
          public Void call() throws Exception {
            // Invalidate the dependency and change what its value will be in the next build. This
            // should enforce rebuilding of the action.
            appendToFile(depPath.asPath());
            differencer.invalidate(ImmutableList.of(skyframeDep));
            return null;
          }
        },
        ExpectActionIs.REEXECUTED);
  }

  @Test
  public void testActionWithNonChangingInputButChangingSkyframeDeps() throws Exception {
    assertActionWithMaybeChangingInputAndChangingSkyframeDeps(ChangeArtifact.DONT_CHANGE);
  }

  @Test
  public void testActionWithChangingInputMtimeAndChangingSkyframeDeps() throws Exception {
    assertActionWithMaybeChangingInputAndChangingSkyframeDeps(ChangeArtifact.CHANGE_MTIME);
  }

  @Test
  public void testActionWithChangingInputAndChangingSkyframeDeps() throws Exception {
    assertActionWithMaybeChangingInputAndChangingSkyframeDeps(
        ChangeArtifact.CHANGE_MTIME_AND_CONTENT);
  }

  @Test
  public void testActionWithNonChangingInputAndNonChangingSkyframeDeps() throws Exception {
    final SkyKey skyframeDep = FileStateValue.key(createSkyframeDepOfAction());

    // Assert that an action-cache-check-bypassing action is executed only once if neither its input
    // nor its Skyframe dependency changes between builds.
    assertActionExecutions(
        new ExecutionCountingActionFactory() {
          @Override
          public ExecutionCountingAction create(
              Artifact input, Artifact output, AtomicInteger executionCounter) {
            return new SkyframeAwareExecutionCountingAction(
                input, output, executionCounter, skyframeDep);
          }
        },
        ChangeArtifact.DONT_CHANGE,
        new Callable<Void>() {
          @Override
          public Void call() throws Exception {
            // Invalidate the dependency but leave its value up-to-date, so the action should not
            // be rebuilt.
            differencer.invalidate(ImmutableList.of(skyframeDep));
            return null;
          }
        },
        ExpectActionIs.DIRTIED_BUT_VERIFIED_CLEAN);
  }

  private abstract static class SingleOutputAction extends AbstractAction {
    SingleOutputAction(@Nullable Artifact input, Artifact output) {
      super(
          ActionsTestUtil.NULL_ACTION_OWNER,
          input == null ? ImmutableList.<Artifact>of() : ImmutableList.of(input),
          ImmutableList.of(output));
    }

    protected static final class Buffer {
      final int size;
      final byte[] data;

      Buffer(byte[] data, int size) {
        this.data = data;
        this.size = size;
      }
    }

    protected Buffer readInput() throws ActionExecutionException {
      byte[] input = new byte[100];
      int inputLen = 0;
      try (InputStream in = getPrimaryInput().getPath().getInputStream()) {
        inputLen = in.read(input, 0, input.length);
      } catch (IOException e) {
        throw new ActionExecutionException(e, this, false);
      }
      return new Buffer(input, inputLen);
    }

    protected void writeOutput(@Nullable Buffer buf, String data) throws ActionExecutionException {
      try (OutputStream out = getPrimaryOutput().getPath().getOutputStream()) {
        if (buf != null) {
          out.write(buf.data, 0, buf.size);
        }
        out.write(data.getBytes(StandardCharsets.UTF_8), 0, data.length());
      } catch (IOException e) {
        throw new ActionExecutionException(e, this, false);
      }
    }

    @Override
    public String getMnemonic() {
      return "MockActionMnemonic";
    }

    @Override
    protected String computeKey() {
      return new Fingerprint().addInt(42).hexDigestAndReset();
    }
  }

  private abstract static class SingleOutputSkyframeAwareAction extends SingleOutputAction
      implements SkyframeAwareAction {
    SingleOutputSkyframeAwareAction(@Nullable Artifact input, Artifact output) {
      super(input, output);
    }

    @Override
    public boolean executeUnconditionally() {
      return true;
    }

    @Override
    public boolean isVolatile() {
      return true;
    }
  }

  /**
   * Regression test to avoid a potential race condition in {@link ActionExecutionFunction}.
   *
   * <p>The test ensures that when ActionExecutionFunction executes a Skyframe-aware action
   * (implementor of {@link SkyframeAwareAction}), ActionExecutionFunction first requests the inputs
   * of the action and ensures they are built before requesting any of its Skyframe dependencies.
   *
   * <p>This strict ordering is very important to avoid the race condition, which could arise if the
   * compute method were too eager to request all dependencies: request input files but even if some
   * are missing, request also the skyframe-dependencies. The race is described in this method's
   * body.
   */
  @Test
  public void testRaceConditionBetweenInputAcquisitionAndSkyframeDeps() throws Exception {
    // Sequence of events on threads A and B, showing SkyFunctions and requested SkyKeys, leading
    // to an InconsistentFilesystemException:
    //
    // _______________[Thread A]_________________|_______________[Thread B]_________________
    // ActionExecutionFunction(gen2_action:      | idle
    //   genfiles/gen1 -> genfiles/foo/bar/gen2) |
    // ARTIFACT:genfiles/gen1                    |
    // MOCK_VALUE:dummy_argument                 |
    // env.valuesMissing():yes ==> return        |
    //                                           |
    // ArtifactFunction(genfiles/gen1)           | MockFunction()
    // CONFIGURED_TARGET://foo:gen1              | FILE:genfiles/foo
    // ACTION_EXECUTION:gen1_action              | env.valuesMissing():yes ==> return
    // env.valuesMissing():yes ==> return        |
    //                                           | FileFunction(genfiles/foo)
    // ActionExecutionFunction(gen1_action)      | FILE:genfiles
    // ARTIFACT:genfiles/gen0                    | env.valuesMissing():yes ==> return
    // env.valuesMissing():yes ==> return        |
    //                                           | FileFunction(genfiles)
    // ArtifactFunction(genfiles/gen0)           | FILE_STATE:genfiles
    // CONFIGURED_TARGET://foo:gen0              | env.valuesMissing():yes ==> return
    // ACTION_EXECUTION:gen0_action              |
    // env.valuesMissing():yes ==> return        | FileStateFunction(genfiles)
    //                                           | stat genfiles
    // ActionExecutionFunction(gen0_action)      | return FileStateValue:non-existent
    // create output directory: genfiles         |
    // working                                   | FileFunction(genfiles/foo)
    //                                           | FILE:genfiles
    //                                           | FILE_STATE:genfiles/foo
    //                                           | env.valuesMissing():yes ==> return
    //                                           |
    //                                           | FileStateFunction(genfiles/foo)
    //                                           | stat genfiles/foo
    //                                           | return FileStateValue:non-existent
    //                                           |
    // done, created genfiles/gen0               | FileFunction(genfiles/foo)
    // return ActionExecutionValue(gen0_action)  | FILE:genfiles
    //                                           | FILE_STATE:genfiles/foo
    // ArtifactFunction(genfiles/gen0)           | return FileValue(genfiles/foo:non-existent)
    // CONFIGURED_TARGET://foo:gen0              |
    // ACTION_EXECUTION:gen0_action              | MockFunction()
    // return ArtifactSkyKey(genfiles/gen0)      | FILE:genfiles/foo
    //                                           | FILE:genfiles/foo/bar/gen1
    // ActionExecutionFunction(gen1_action)      | env.valuesMissing():yes ==> return
    // ARTIFACT:genfiles/gen0                    |
    // create output directory: genfiles/foo/bar | FileFunction(genfiles/foo/bar/gen1)
    // done, created genfiles/foo/bar/gen1       | FILE:genfiles/foo/bar
    // return ActionExecutionValue(gen1_action)  | env.valuesMissing():yes ==> return
    //                                           |
    // idle                                      | FileFunction(genfiles/foo/bar)
    //                                           | FILE:genfiles/foo
    //                                           | FILE_STATE:genfiles/foo/bar
    //                                           | env.valuesMissing():yes ==> return
    //                                           |
    //                                           | FileStateFunction(genfiles/foo/bar)
    //                                           | stat genfiles/foo/bar
    //                                           | return FileStateValue:directory
    //                                           |
    //                                           | FileFunction(genfiles/foo/bar)
    //                                           | FILE:genfiles/foo
    //                                           | FILE_STATE:genfiles/foo/bar
    //                                           | throw InconsistentFilesystemException:
    //                                           |     genfiles/foo doesn't exist but
    //                                           |     genfiles/foo/bar does!

    Artifact genFile1 = createDerivedArtifact("foo/bar/gen1.txt");
    Artifact genFile2 = createDerivedArtifact("gen2.txt");

    registerAction(
        new SingleOutputAction(null, genFile1) {
          @Override
          public void execute(ActionExecutionContext actionExecutionContext)
              throws ActionExecutionException, InterruptedException {
            writeOutput(null, "gen1");
          }
        });

    registerAction(
        new SingleOutputSkyframeAwareAction(genFile1, genFile2) {
          @Override
          public void establishSkyframeDependencies(Environment env) throws ExceptionBase {
            assertThat(env.valuesMissing()).isFalse();
          }

          @Override
          public void execute(ActionExecutionContext actionExecutionContext)
              throws ActionExecutionException, InterruptedException {
            writeOutput(readInput(), "gen2");
          }
        });

    builder.buildArtifacts(
        reporter,
        ImmutableSet.of(genFile2),
        null,
        null,
        null,
        null,
        executor,
        null,
        false,
        null,
        null);
  }
}


text:
<?php
declare(strict_types=1);

namespace CallgrindToPlantUML\SequenceDiagram\Filter\Existence;

use CallgrindToPlantUML\SequenceDiagram\Call;

class NotDeeperThanFilter implements FilterInterface
{
    /** @var string */
    private $toClass;

    /** @var string|null */
    private $method;

    /** @var bool */
    private $deeperThanFilter;

    /** @var \CallgrindToPlantUML\SequenceDiagram\Call */
    private $filteringFromCall;

    /**
     * @param string $toClass
     * @param string|null $method
     */
    public function __construct(string $toClass, string $method = null)
    {
        $this->toClass = str_replace('.', '\\', $toClass);
        if (null !== $method) {
            $this->method = str_replace('()', '', $method);
        }
        $this->deeperThanFilter = false;
    }

    /**
     * If we are deeper than the filter class::method, return false, if not, return true.
     *
     * @param \CallgrindToPlantUML\SequenceDiagram\Call $call
     *
     * @return bool
     */
    public function isCallValid(Call $call): bool
    {
        if (!$this->deeperThanFilter) {
            if ($this->isTheCallToBeFiltered($call)) {
                $this->deeperThanFilter = true;
                $this->filteringFromCall = $call;
            }
        } else {
            if ($this->isTheFilteringReturnCall($call)) {
                $this->deeperThanFilter = false;
                $this->filteringFromCall = null;

                return $this->deeperThanFilter;
            }
        }

        return !$this->deeperThanFilter;
    }

    /**
     * Checks if this call is the one that we should not go deeper than.
     *
     * @param \CallgrindToPlantUML\SequenceDiagram\Call $call
     *
     * @return bool
     */
    private function isTheCallToBeFiltered(Call $call): bool
    {
        return !$call->isReturnCall() &&
            $this->classStartsWith($this->toClass, $call->getFromClass()) &&
            ($this->method === null || $call->getMethod() === $this->method);
    }

    /**
     * Checks if this call is the return call of the one that we should not go deeper than.
     *
     * @param \CallgrindToPlantUML\SequenceDiagram\Call $call
     *
     * @return bool
     */
    private function isTheFilteringReturnCall(Call $call): bool
    {
        return $call->isReturnCall() &&
            $call->getFromClass() === $this->filteringFromCall->getToClass() &&
            $call->getToClass() === $this->filteringFromCall->getFromClass() &&
            $call->getMethod() === $this->filteringFromCall->getMethod();
    }

    /**
     * Allow for partial matches, for example, if I want to say that I do not want to go deeper than everything that
     * is Doctrine instead of having to manually identify all classes.
     *
     * @param string $needle
     * @param string $haystack
     *
     * @return bool
     */
    private function classStartsWith(string $needle, string $haystack): bool
    {
        // If partial filter, check if classes start by same class name.
        if (substr($needle, -1) === '%') {
            $needle = substr($needle, 0, -1);

            return substr($haystack, 0, strlen($needle)) === $needle;
        }

        return $haystack === $needle;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

var resolveException = require("../lib/resolve-exception")
  , is               = require("./is");

module.exports = function (value/*, options*/) {
	if (is(value)) return value;
	return resolveException(value, "Cannot use %v", arguments[1]);
};


text: Before you begin, [sign up for a Vimeo Developer account](https://developer.vimeo.com/).


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Dostava je uvijek u onih 45 minuta, većinu puta brže dođu, u meksičkim jelima ima malo previše luka al su ukusna , ostala jela su predobra , preporučam bilo šta u umaku od gljiva</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-remiza</Source>
</CrawlItem>


text:
layout: post
date: '2016-06-02'
title: "Casablanca Bridal 2127 A Line Lace Wedding Dress"
category: Casablanca Bridal
tags: [Casablanca Bridal]
---
### Casablanca Bridal 2127 A Line Lace Wedding Dress
Just **$334.99**
###

Full A-line skirt with a Princess Sweetheart neckline and a sweetheart back neckline shape. The bodice has beaded lace and eyelash fringe scallop trim at the waist. Non-beaded lace appliqu

Buy it: [https://www.eudances.com/en/casablanca-bridal/399-casablanca-bridal-2127-a-line-lace-wedding-dress.html](https://www.eudances.com/en/casablanca-bridal/399-casablanca-bridal-2127-a-line-lace-wedding-dress.html)


text:
<?php

class Settings_Webforms_Delete_Action extends Settings_Vtiger_Index_Action {

	public function checkPermission(Vtiger_Request $request) {
		parent::checkPermission($request);

		$recordId = $request->get('record');
		$moduleModel = Vtiger_Module_Model::getInstance($request->getModule());

		$currentUserPrivilegesModel = Users_Privileges_Model::getCurrentUserPrivilegesModel();
		if(!$recordId || !$currentUserPrivilegesModel->hasModulePermission($moduleModel->getId())) {
			throw new AppException('LBL_PERMISSION_DENIED');
		}
	}

	public function process(Vtiger_Request $request) {
		$recordId = $request->get('record');
		$qualifiedModuleName = $request->getModule(false);

		$recordModel = Settings_Webforms_Record_Model::getInstanceById($recordId, $qualifiedModuleName);
		$moduleModel = $recordModel->getModule();

		$recordModel->delete();

		$returnUrl = $moduleModel->getListViewUrl();
		$response = new Vtiger_Response();
		$response->setResult($returnUrl);
		return $response;
	}

        public function validateRequest(Vtiger_Request $request) {
            $request->validateWriteAccess();
        }
}


text:
package org.wso2.developerstudio.codenvy.ext.esb.client;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;

public interface ESBExtensionResources extends ClientBundle {

	@Source("esb-extension.js") TextResource esbExtensionJS();

	@Source("jquery.min.js") TextResource jqueryLib();

	@Source("jquery.ui.min.js") TextResource jqueryUILib();

	@Source("jquery.jsPlumb-1.6.2-min.js") TextResource jsPlumbLib();

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Android Typing Password</title>
    <link rel="stylesheet" type="text/css" href="/css/app.css"/>
    <link rel="stylesheet" type="text/css" href="/css/graphic-key.css"/>

        <?php echo (isset($_SESSION['signin']) && $_SESSION['signin']) ? 'Hello, ' . $_SESSION['login'] . '! Logout' : '' ?>

    %body%

githubfork me on
<?php echo $flash; ?>


text:
require File.join(File.dirname(__FILE__), '..','..','..','puppet/provider/lnx_base')

Puppet::Type.type(:l2_port).provide(:sriov, :parent => Puppet::Provider::Lnx_base) do
  commands   :ethtool_cmd => 'ethtool',
             :pkill       => 'pkill'

  def self.instances
    rv = []
    ports = get_lnx_ports
    ports.each_pair do |if_name, if_props|
      debug("prefetching interface '#{if_name}'")

      props = {
        :ensure          => :present,
        :name            => if_name,
        :vendor_specific => {}
      }
      props.merge! if_props

      sriov_numvfs = self.get_sriov_numvfs(if_name)
      if sriov_numvfs and sriov_numvfs > 0
        props[:provider] = 'sriov'
        props[:vendor_specific] = {'sriov_numvfs' => sriov_numvfs.to_s}
      end

      props[:port_type] = props[:port_type].insert(0, props[:provider]).join(':')
      if props[:provider] == 'sriov'
        rv << new(props)
        debug("PREFETCH properties for '#{if_name}': #{props}")
      else
        debug("SKIP properties for '#{if_name}': #{props}")
      end
    end
    return rv
  end

  def self.sriov_numvfs_file(iface)
    "/sys/class/net/#{iface}/device/sriov_numvfs"
  end

  def self.get_sriov_numvfs(iface)
    File.read(self.sriov_numvfs_file(iface)).to_i if File.exists? self.sriov_numvfs_file(iface)
  end

  def sriov_numvfs
    self.class.get_sriov_numvfs(@resource[:interface])
  end

  def sriov_numvfs=(val)
    sriov_numvfs_file = self.class.sriov_numvfs_file(@resource[:interface])
    raise "'#{@resource[:interface]}' does not support sriov." unless File.exists? sriov_numvfs_file
    File.open(sriov_numvfs_file, "a") {|f| f << val}
  end

  def create
    debug("CREATE resource: #{@resource}")
    @old_property_hash = {}
    @property_flush = {}.merge! @resource
    self.class.interface_up(@resource[:interface])
  end

  def destroy
    debug("DESTROY resource: #{@resource}")
    self.sriov_numvfs = 0
    self.class.interface_down(@resource[:interface], true)
  end

  def flush
    unless @property_flush.empty?
    debug("FLUSH properties: #{@property_flush}")
      unless ['', 'absent'].include? @property_flush[:mtu].to_s
        self.class.set_mtu(@resource[:interface], @property_flush[:mtu])
      end
      vendor_specific = (@property_flush[:vendor_specific] || {})
      unless vendor_specific["sriov_numvfs"].nil?
        self.sriov_numvfs = 0
        self.sriov_numvfs = vendor_specific["sriov_numvfs"].to_i
      end
      @property_hash = resource.to_hash
    end
  end

  def vendor_specific
    @property_hash[:vendor_specific] || :absent
  end
  def vendor_specific=(val)
    old = @property_hash[:vendor_specific] || {}
    changes = val.to_a - old.to_a
    @property_flush[:vendor_specific] = Hash[changes]
  end

  def vlan_dev
    @property_hash[:vlan_dev] || :absent
  end
  def vlan_dev=(val)
    @property_flush[:vlan_dev] = val
  end

  def vlan_id
    @property_hash[:vlan_id] || :absent
  end
  def vlan_id=(val)
    @property_flush[:vlan_id] = val
  end

  def vlan_mode
    @property_hash[:vlan_mode] || :absent
  end
  def vlan_mode=(val)
    @property_flush[:vlan_mode] = val
  end

  def bond_master
    @property_hash[:bond_master] || :absent
  end
  def bond_master=(val)
    @property_flush[:bond_master] = val
  end
end
# vim: set ts=2 sw=2 et :


text:
'use strict';

/* eslint-disable no-var, object-shorthand, func-names, prefer-template, prefer-arrow-callback */

var _ = require('lodash');
var chalk = require('chalk');
var mkdirp = require('mkdirp');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

function jigsassifyName(name) {
  var kebabedName = _.kebabCase(name);
  var hasJigsass = kebabedName.slice(0, 8) === ('jigsass-');

  return hasJigsass ? kebabedName : 'jigsass-' + kebabedName;
}

module.exports = yeoman.Base.extend({
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the ' + chalk.red('JigSass Module Generator') + '! \n' +
      'Lets start scaffolding your module.'
    ));

    // Prompt the user
    var prompts = [ // eslint-disable-line vars-on-top
      {
        name: 'name',
        message: 'How would you like to name your module?',
        default: jigsassifyName(path.basename(process.cwd())),
        filter: jigsassifyName,
        validate: function (str) {
          return str.length > 0;
        },
      },
      {
        name: 'description',
        message: 'Description',
        default: '',
      },
      {
        name: 'homepage',
        message: 'Is there webpage for your module?',
        default: '',
      },
      {
        name: 'githubAccount',
        message: 'Which GitHub account or organization will host your module?',
        default: this.user.git.name(),
      },
      {
        name: 'authorName',
        message: 'Your Name, please',
        default: this.user.git.name(),
        store: true,
      },
      {
        name: 'authorEmail',
        message: 'Mind giving me your Email?',
        default: this.user.git.email(),
        store: true,
      },
      {
        name: 'license',
        message: 'Which license do you want to use?',
        default: 'MIT',
      },
      // {
      //   type: 'checkbox',
      //   name: 'deps',
      //   message: 'Would you like me to import one of these for you?',
      //   choices: [
      //     {
      //       name: 'jigsass-base',
      //       value: 'includeBase',
      //       checked: false,
      //       default: false
      //     },
      //     {
      //       name: 'jigsass-objects',
      //       value: 'includeObjects',
      //       checked: false,
      //       default: false
      //     },
      //     {
      //       name: 'jigsass-utils',
      //       value: 'includeUtils',
      //       checked: false,
      //       default: false
      //     },
      //   ]
      // },
      {
        name: 'includeTravis',
        type: 'confirm',
        message: 'Include Travis config?',
      },
    ];

    this.prompt(prompts, function (props) {
      for (var prop in props) {  // eslint-disable-line vars-on-top
        if (props.hasOwnProperty(prop)) {
          this[prop] = props[prop];
        }
      }

      this.moduleName = jigsassifyName(props.name);

      // Store the module name in title case
      this.moduleTitle = this.moduleName
        .replace(/-/g, ' ')
        .replace(/jigsass/i, 'JigSass')
        .replace(/(?:^|\s)(\w)/g, function (l) { return l.toUpperCase(); });

      // Store the module name in camel case
      this.moduleSafeName = _.camelCase(this.moduleName);

      done();
    }.bind(this));
  },

  writing: function () {
    var pkg = {
      name: this.moduleName,
      author: {
        name: this.authorName,
        email: this.authorEmail,
      },
      version: '0.0.0',
      main: 'scss/index.scss',
      style: 'scss/index.scss',
      files: ['scss'],
      private: true,
      repository: {
        type: 'git',
        url: this.githubAccount + '/' + this.moduleName,
      },
      bugs: {
        bugs: this.githubAccount + '/' + this.moduleName + '/issues',
      },
      keywords: [
        'jigsass',
        'sass',
        'scss',
        'css',
        'oocss',
        'atomic css',
        'eyeglass-module',
      ],
      eyeglass: {
        exports: false,
        needs: '^0.8.3',
        sassDir: 'scss',
      },
      scripts: {
        test: 'gulp sass:test',
        prepublish: 'gulp prepublish',
      },
      dependencies: {},
      devDependencies: {
        autoprefixer: '^6.3.3',
        'babel-core': '^6.5.2',
        'babel-preset-es2015': '^6.5.0',
        'babel-register': '^6.6.0',
        'browser-sync': '^2.11.1',
        chai: '^3.5.0',
        del: '^2.2.0',
        eyeglass: '^0.8.3',
        gulp: '^3.9.1',
        'gulp-load-plugins': '^1.2.0',
        'gulp-mocha': '^2.2.0',
        'gulp-plumber': '^1.1.0',
        'gulp-postcss': '^6.1.0',
        'gulp-sass': '^2.2.0',
        'gulp-util': '^3.0.7',
        mdcss: '^1.5.1',
        'mdcss-theme-jigsass': '^0.2.10',
        'postcss-reporter': '^1.3.3',
        'postcss-scss': '^0.1.5',
        'run-sequence': '^1.1.5',
        sassaby: '^2.1.1',
        sassdoc: '^2.1.20',
        'sassdoc-theme-jigsass': '^0.2.12',
        stylelint: '^5.2.1',
      },
    };

    // Append properties to package.json
    ['description', 'license', 'homepage'].forEach((prop) => {
      if (this[prop]) pkg[prop] = this[prop];
    });

    // Insert required dependencies to pkg
    // TODO: Uncomment when these are ready (and update version);
    // if (this.includeBase) pkg.dependencies['jigsass-base'] = '^0.0.0';
    // if (this.includeObjects) pkg.dependencies['jigsass-objects'] = '^0.0.0';
    // if (this.includeUtils) pkg.dependencies['jigsass-utils'] = '^0.0.0';

    // Write `package.json` to disk
    this.fs.writeJSON(this.destinationPath('package.json'), pkg);

    // Create folders
    mkdirp('scss');
    mkdirp('sgSrc');
    mkdirp('sgSrc/assets');
    mkdirp('test');
    mkdirp('docs');
    mkdirp('test/helpers');

    // Module files
    this.fs.copyTpl(
      this.templatePath('index.scss'),
      this.destinationPath('scss/index.scss'),
      {
        moduleName: this.moduleName,
        description: this.description,
        homepage: this.homepage,
        authorName: this.authorName,
        authorEmail: this.authorEmail,
      }
    //   {
      // }
    );

    // Documentation
    this.fs.copyTpl(
      this.templatePath('sg.scss'),
      this.destinationPath('sgSrc/sg.scss'),
      {
        moduleName: this.moduleName,
      }
    );
    this.fs.copyTpl(
      this.templatePath('README.md'),
      this.destinationPath('README.md'),
      {
        description: this.description,
        githubAccount: this.githubAccount,
        includeTravis: this.includeTravis,
        license: this.license,
        moduleName: this.moduleName,
        moduleTitle: this.moduleTitle,
      }
    );
    this.fs.copyTpl(
      this.templatePath('DOCS.md'),
      this.destinationPath('DOCS.md'),
      {
        description: this.description,
        githubAccount: this.githubAccount,
        includeTravis: this.includeTravis,
        license: this.license,
        moduleName: this.moduleName,
        moduleTitle: this.moduleTitle,
      }
    );
    this.fs.copy(
      this.templatePath('CHANGELOG.md'),
      this.destinationPath('CHANGELOG.md')
    );

    // Tests
    this.fs.copyTpl(
      this.templatePath('test.js'),
      this.destinationPath('test/test_' + this.moduleName + '.js'),
      { moduleName: this.moduleName }
    );
    this.fs.copy(
      this.templatePath('helper.js'),
      this.destinationPath('test/helper.js')
    );
    this.fs.copy(
      this.templatePath('importer.scss'),
      this.destinationPath('test/helpers/importer.scss')
    );
    this.fs.copy(
      this.templatePath('test-helpers.scss'),
      this.destinationPath('test/helpers/_test-helpers.scss')
    );

    // Config and dotfiles
    this.fs.copyTpl(
      this.templatePath('gulpfile.babel.js'),
      this.destinationPath('gulpfile.babel.js'),
      { moduleName: this.moduleName }
    );
    this.fs.copyTpl(
      this.templatePath('gh-pages.sh'),
      this.destinationPath('gh-pages.sh'),
      {
        githubAccount: this.githubAccount,
        moduleName: this.moduleName,
      }
    );
    this.fs.copy(
      this.templatePath('babelrc'),
      this.destinationPath('.babelrc')
    );
    this.fs.copy(
      this.templatePath('editorconfig'),
      this.destinationPath('.editorconfig')
    );
    this.fs.copy(
      this.templatePath('gitattributes'),
      this.destinationPath('.gitattributes')
    );
    this.fs.copy(
      this.templatePath('gitignore'),
      this.destinationPath('.gitignore')
    );
    this.fs.copy(
      this.templatePath('sassdocrc'),
      this.destinationPath('.sassdocrc')
    );
    this.fs.copy(
      this.templatePath('stylelintrc'),
      this.destinationPath('.stylelintrc')
    );

    if (this.includeTravis) {
      this.fs.copy(
        this.templatePath('travis.yml'),
        this.destinationPath('.travis.yml')
      );
    }
  },

  install: function () {
    this.npmInstall();
  },
});


text:
"""
This file contains output string messages used by MySQL Utilities.
"""

ERROR_USER_WITHOUT_PRIVILEGES = ("User '{user}' on '{host}@{port}' does not "
                                 "have sufficient privileges to "
                                 "{operation} (required: {req_privileges}).")

PARSE_ERR_DB_PAIR = ("Cannot parse the specified database(s): '{db_pair}'. "
                     "Please verify that the database(s) are specified in "
                     "a valid format (i.e., {db1_label}[:{db2_label}]) and "
                     "that backtick quotes are properly used when required.")

PARSE_ERR_DB_PAIR_EXT = ("%s The use of backticks is required if non "
                         "alphanumeric characters are used for database "
                         "names. Parsing the specified database results "
                         "in {db1_label} = '{db1_value}' and "
                         "{db2_label} = '{db2_value}'." % PARSE_ERR_DB_PAIR)

PARSE_ERR_DB_OBJ_PAIR = ("Cannot parse the specified database objects: "
                         "'{db_obj_pair}'. Please verify that the objects "
                         "are specified in a valid format (i.e., {db1_label}"
                         "[.{obj1_label}]:{db2_label}[.{obj2_label}]) and "
                         "that backtick quotes are properly used if "
                         "required.")

PARSE_ERR_DB_OBJ_PAIR_EXT = ("%s The use of backticks is required if non "
                             "alphanumeric characters are used for identifier "
                             "names. Parsing the specified objects results "
                             "in: {db1_label} = '{db1_value}', "
                             "{obj1_label} = '{obj1_value}', "
                             "{db2_label} = '{db2_value}' and "
                             "{obj2_label} = '{obj2_value}'."
                             % PARSE_ERR_DB_OBJ_PAIR)

PARSE_ERR_DB_OBJ_MISSING_MSG = ("Incorrect object compare argument, one "
                                "specific object is missing. Please verify "
                                "that both object are correctly specified. "
                                "{detail} Format should be: "
                                "{db1_label}[.{obj1_label}]"
                                ":{db2_label}[.{obj2_label}].")

PARSE_ERR_DB_OBJ_MISSING = ("No object has been specified for "
                            "{db_no_obj_label} '{db_no_obj_value}', while "
                            "object '{only_obj_value}' was specified for "
                            "{db_obj_label} '{db_obj_value}'.")

PARSE_ERR_DB_MISSING_CMP = "No databases specified to compare."

PARSE_ERR_OBJ_NAME_FORMAT = ("Cannot parse the specified qualified name "
                             "'{obj_name}' for {option}. Please verify that a "
                             "valid format is used (i.e., <db_name>"
                             "[.<tbl_name>]) and that backtick quotes are "
                             "properly used if required.")

PARSE_ERR_SPAN_KEY_SIZE_TOO_LOW = (
    "The value {s_value} specified for option --span-key-size is too small "
    "and would cause inaccurate results, please retry with a bigger value "
    "or the default value of {default}.")

PARSE_ERR_OPT_INVALID_CMD = "Invalid {opt} option for '{cmd}'."

PARSE_ERR_OPT_INVALID_CMD_TIP = ("%s Use {opt_tip} instead."
                                 % PARSE_ERR_OPT_INVALID_CMD)

PARSE_ERR_OPT_INVALID_DATE = "Invalid {0} date format (yyyy-mm-dd): {1}"

PARSE_ERR_OPT_INVALID_DATE_TIME = ("Invalid {0} date/time format "
                                   "(yyyy-mm-ddThh:mm:ss): {1}")

PARSE_ERR_OPT_INVALID_NUM_DAYS = ("Invalid number of days (must be an integer "
                                  "greater than zero) for {0} date: {1}")

PARSE_ERR_OPT_INVALID_VALUE = ("The value for option {option} is not valid: "
                               "'{value}'.")

PARSE_ERR_OPT_REQ_NON_NEGATIVE_VALUE = ("Option '{opt}' requires a "
                                        "non-negative value.")

PARSE_ERR_OPT_REQ_GREATER_VALUE = ("Option '{opt}' requires a value greater "
                                   "than {val}.")

PARSE_ERR_OPT_REQ_VALUE = "Option '{opt}' requires a non-empty value."

PARSE_ERR_OPTS_EXCLD = ("Options {opt1} and {opt2} cannot be used "
                        "together.")

PARSE_ERR_OPTS_REQ = "Option '{opt}' is required."

PARSE_ERR_OPTS_REQ_BY_CMD = ("'{cmd}' requires the following option(s): "
                             "{opts}.")

PARSE_ERR_DISCO_REQ_MASTER = ("Option --discover-slaves-login requires use of "
                              "--master.")

PARSE_ERR_SLAVE_DISCO_REQ = ("Option --discover-slaves-login or --slaves is "
                             "required.")

PARSE_ERR_OPTS_REQ_GREATER_OR_EQUAL = ("The {opt} option requires a value "
                                       "greater than or equal to {value}.")

WARN_OPT_NOT_REQUIRED = ("WARNING: The {opt} option is not required for "
                         "'{cmd}' (option ignored).")

WARN_OPT_NOT_REQUIRED_ONLY_FOR = ("%s Only used with the {only_cmd} command."
                                  % WARN_OPT_NOT_REQUIRED)

WARN_OPT_NOT_REQUIRED_FOR_TYPE = (
    "# WARNING: The {opt} option is not required for the {type} type "
    "(option ignored).")

WARN_OPT_ONLY_USED_WITH = ("# WARNING: The {opt} option is only used with "
                           "{used_with} (option ignored).")

WARN_OPT_USING_DEFAULT = ("WARNING: Using default value '{default}' for "
                          "option {opt}.")

ERROR_SAME_MASTER = ("The specified new master {n_master_host}:{n_master_port}"
                     " is the same as the "
                     "actual master {master_host}:{master_port}.")

SLAVES = "slaves"

CANDIDATES = "candidates"

ERROR_MASTER_IN_SLAVES = ("The master {master_host}:{master_port} "
                          "and one of the specified {slaves_candidates} "
                          "are the same {slave_host}:{slave_port}.")

SCRIPT_THRESHOLD_WARNING = ("WARNING: You have chosen to use external script "
                            "return code checking. Depending on which script "
                            "fails, this can leave the operation in an "
                            "undefined state. Please check your results "
                            "carefully if the operation aborts.")

HOST_IP_WARNING = ("You may be mixing host names and IP addresses. This may "
                   "result in negative status reporting if your DNS services "
                   "do not support reverse name lookup.")

ERROR_MIN_SERVER_VERSIONS = ("The {utility} requires server versions greater "
                             "or equal than {min_version}. Server version for "
                             "'{host}:{port}' is not supported.")

PARSE_ERR_SSL_REQ_SERVER = ("Options --ssl-ca, --ssl-cert and --ssl-key "
                            "requires use of --server.")

WARN_OPT_SKIP_INNODB = ("The use of InnoDB is mandatory since MySQL 5.7. The "
                        "former options like '--innodb=0/1/OFF/ON' or "
                        "'--skip-innodb' are ignored.")


text:
from __future__ import print_function
import sys
import os
from subprocess import check_call, Popen, PIPE
import time

from test_utils import PYTHON, LZCOMP, TEST_ENV, diff_q

INPUTS = """\
data/alice29.txt
data/asyoulik.txt
data/lcet10.txt
data/plrabn12.txt
../mtx/lzcomp.c
../mtx/mtxmem.h
../mtx/ahuff.c
%s
""" % LZCOMP

start = time.time()
for filename in INPUTS.splitlines():
    print('Roundtrip testing of file "%s"' % os.path.basename(filename))
    compressed = os.path.splitext(filename)[0] + ".comp"
    uncompressed = os.path.splitext(filename)[0] + ".decomp"
    comp_start = time.time()
    check_call([PYTHON, LZCOMP, "-f", "-i", filename, "-o", compressed],
               env=TEST_ENV)
    print("--- compression: %s seconds ---" % (time.time() - comp_start))
    decomp_start = time.time()
    check_call([PYTHON, LZCOMP, "-f", "-d", "-i", compressed, "-o",
                uncompressed], env=TEST_ENV)
    print("--- decompression: %s seconds ---" % (time.time() - decomp_start))
    if diff_q(filename, uncompressed) != 0:
        sys.exit(1)
    # Test the streaming version
    with open(filename, "rb") as infile, open(uncompressed, "wb") as outfile:
        p = Popen([PYTHON, LZCOMP], stdin=infile, stdout=PIPE, env=TEST_ENV)
        check_call([PYTHON, LZCOMP, "-d"], stdin=p.stdout, stdout=outfile,
                   env=TEST_ENV)
    if diff_q(filename, uncompressed) != 0:
        sys.exit(1)
    # clean up
    os.remove(compressed)
    os.remove(uncompressed)
print("--- TOTAL: %s seconds ---\n" % (time.time() - start))


text:
NameSpace Models.DMSSEC

Partial Public Class SecurityEventAction
   Inherits DMS.Base.Models.GenericEntity

#Region " Properties "

Public Overrides Property ID As String
   Get
      Return "{0}".FormatWith(ActionID)
   End Get
   Set(value as String)
      ActionID=ToIntegerDB(value)
   End Set
End Property

Private _ActionDescription As String = "" ' Column 2
Public Property ActionDescription As String
   Get
      Return _ActionDescription
   End Get
   Set(value as String)
      SetProperty(_ActionDescription,value,"ActionDescription")
   End Set
End Property

Private _ActionID As Integer = -1 ' Column 0
Public Property ActionID As Integer
   Get
      Return _ActionID
   End Get
   Set(value as Integer)
      SetProperty(_ActionID,value,"ActionID",{"ID"})
   End Set
End Property

Private _ActionType As String = "" ' Column 1
Public Property ActionType As String
   Get
      Return _ActionType
   End Get
   Set(value as String)
      SetProperty(_ActionType,value,"ActionType")
   End Set
End Property

#End Region

Public Async Function Delete(dbAccess as DMS.Base.Data.IDBAccess) As Task
   Await Delete(dbAccess,Me)
End Function

Public Overrides Sub LoadFromEntity(genericEntity As DMS.Base.Models.GenericEntity)
   If Me Is genericEntity Then
      Return
   End If
   If Not (TypeOf (genericEntity) Is SecurityEventAction) Then
      Return
   End If
   Dim Entity As SecurityEventAction = DirectCast(genericEntity, SecurityEventAction)

   Me.ActionID = Entity.ActionID
   Me.ActionType = Entity.ActionType
   Me.ActionDescription = Entity.ActionDescription
End Sub

Public Overrides Sub LoadFromReader(reader As IDataReader)
   Me.ActionID = ToIntegerDB(reader(0))
   Me.ActionType = ToStringDB(reader(1))
   Me.ActionDescription = ToStringDB(reader(2))
End Sub

Public Overrides Sub PopulateDataRow(ByRef dataRow As System.Data.DataRow)
   dataRow.Item(0) = Me.ActionID
   dataRow.Item(1) = Me.ActionType
   dataRow.Item(2) = Me.ActionDescription
End Sub

Public Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess) As Task
   Await Upsert(dbAccess, Me)
End Function

Public Overrides Function GetParameters() As IDictionary(Of String, Object)
   Dim Results As New Dictionary(Of String, Object)
Results.Add("ActionID", Me.ActionID)
Results.Add("ActionType", Me.ActionType)
Results.Add("ActionDescription", Me.ActionDescription)
   Return Results
End Function

#Region " Shared "

Private Shared _DBDetails As DMS.Base.Models.DBDetails = Nothing

Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of SecurityEventAction)) As Task
   Dim Tasks As New List(Of Task)
   For Each Entity As SecurityEventAction In entities
      Tasks.Add(Delete(dbAccess, Entity))
   Next
   Await Task.WhenAll(Tasks)
End Function

Public Shared Async Function Delete(dbAccess As DMS.Base.Data.IDBAccess, entity As SecurityEventAction) As Task
      Await dbAccess.ExecuteNonQuery(GetDBDetails.Delete, entity.GetParameters())
End Function

Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entities As IEnumerable(Of SecurityEventAction)) As Task
   If entities.Count = 1 Then
      Await Upsert(dbAccess, entities.FirstOrDefault())
   Else
         Dim DBDetails As DMS.Base.Models.DBDetails = GetDBDetails()
         Using DataTable As DataTable = GetDataTable()
            For Each Entity As SecurityEventAction In entities
               Dim DataRow As DataRow = DataTable.NewRow
               Entity.PopulateDataRow(DataRow)
               DataTable.Rows.Add(DataRow)
            Next
            Await dbAccess.Merge(DBDetails.CreateTemp, DBDetails.DropTemp, DataTable, DBDetails.Merge, DBDetails.TableName)
         End Using
   End If
End Function

Public Shared Async Function Upsert(dbAccess As DMS.Base.Data.IDBAccess, entity As SecurityEventAction) As Task
      Dim Parameters As IDictionary(Of String, Object) = entity.GetParameters()
      If String.IsNullOrEmpty(entity.ID) OrElse entity.ID.Equals("-1") OrElse ToIntegerDB(Await dbAccess.ExecuteScalar(GetDBDetails.CountSingle, Parameters)) <= 0 Then
         Await dbAccess.ExecuteNonQuery(GetDBDetails.Insert, Parameters)
      Else
         Await dbAccess.ExecuteNonQuery(GetDBDetails.Update, Parameters)
      End If
End Function

Public Shared Async Function GetAll(dbAccess As DMS.Base.Data.IDBAccess) As Threading.Tasks.Task(Of IEnumerable(Of SecurityEventAction))
      Return Await dbAccess.ExecuteReader(Of SecurityEventAction)(GetDBDetails.SelectAll)
End Function

Public Shared Function GetDataTable() As DataTable
   Dim DataTable As New DataTable
   DataTable.Columns.Add("ActionID")
   DataTable.Columns.Add("ActionType")
   DataTable.Columns.Add("ActionDescription")
   Return DataTable
End Function

Public Shared Function GetDBDetails() As DMS.Base.Models.DBDetails
   If _DBDetails Is Nothing Then
      _DBDetails = New DMS.Base.Models.DBDetails
      _DBDetails.CountAll = "SELECT COUNT(*) FROM [SecurityEventActions]"
      _DBDetails.CountSingle = "SELECT COUNT(*) FROM [SecurityEventActions] WHERE (([ActionID]=@ActionID))"
      _DBDetails.CreateTemp = "CREATE TABLE #SecurityEventActions ([ActionID] [int] NULL,[ActionType] [varchar](1) NULL,[ActionDescription] [varchar](255) NULL)"
      _DBDetails.Delete = "DELETE FROM [SecurityEventActions] WHERE (([ActionID]=@ActionID))"
      _DBDetails.DropTemp = "DROP TABLE #SecurityEventActions"
      _DBDetails.GetDataTable = New DMS.Base.Delegates.GetDataTable(AddressOf GetDataTable)
      _DBDetails.Insert = "INSERT INTO [SecurityEventActions] ([ActionID],[ActionType],[ActionDescription]) VALUES (@ActionID,@ActionType,@ActionDescription)"
      _DBDetails.Merge = "MERGE INTO [SecurityEventActions] As [Target] USING #SecurityEventActions As [Source] ON [Target].[ActionID]=[Source].[ActionID] WHEN MATCHED THEN UPDATE SET [Target].[ActionType]=[Source].[ActionType],[Target].[ActionDescription]=[Source].[ActionDescription] WHEN NOT MATCHED THEN INSERT ([ActionID],[ActionType],[ActionDescription]) VALUES ([Source].[ActionID],[Source].[ActionType],[Source].[ActionDescription]);"
      _DBDetails.ModelName = "SecurityEventAction"
      _DBDetails.SelectAll = "SELECT [ActionID],[ActionType],[ActionDescription] FROM [SecurityEventActions]"
      _DBDetails.TableName = "SecurityEventActions"
      _DBDetails.Update = "UPDATE [SecurityEventActions] SET [ActionType]=@ActionType,[ActionDescription]=@ActionDescription WHERE (([ActionID]=@ActionID))"
   End If
   Return _DBDetails
End Function

#End Region

End Class

End Namespace


text:
import React, { Component } from 'react'

class HomeHeader extends Component {
  constructor(props){
    super(props);
  }
  render(){
    return (

          quanbu shuju zhongx

    )
  }
}

export default HomeHeader


text:
package test;

import com.google.common.util.concurrent.ListenableFuture;
import dagger.producers.ProductionComponent;

import java.util.List;

@ProductionComponent(
    modules = DependentProducerModule.class,
    dependencies = {DependedComponent.class, DependedProductionComponent.class})
interface DependentComponent {
  ListenableFuture<List<String>> greetings();
}


text:
package erepnikov;

/**
 * Class Item
 *
 * @author Egor Repnikov
 * @since 27.06.2017
 */
public class Item {

    /**
     * identification of object
     */
    private String id;

    /**
     * object's name
     */
    private String name;

    /**
     * object's description
     */
    private String desc;

    /**
     * create info
     */
    private long create;

    /**
     *
     * @param name
     * @param desc
     * @param create
     */
    public Item(String name, String desc, long create) {
        this.name = name;
        this.desc = desc;
        this.create = create;
    }

    /**
     *
     * @return object's name
     */
    public String getName() {
        return this.name;
    }

    /**
     *
     * @return object's description
     */
    public String getDesc() {
        return this.desc;
    }

    /**
     *
     * @return object's create info
     */
    public long getCreated() {
        return this.create;
    }

    /**
     *
     * @return object's ID
     */
    public String getID() {
        return this.id;
    }

    /**
     *
     * @param id
     */
    public void setID(String id){
        this.id = id;
    }

    /**
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *
     * @param desc
     */
    public void setDescription(String desc) {
        this.desc = desc;
    }

    /**
     *
     * @param create
     */
    public void setCreate(long create) {
        this.create = create;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Item item = (Item) o;
        if (this.getID() != item.getID()) {
            return false;
        }
        if (this.getName() != null ? !this.getName().equals(item.getName()) : item.getName() != null) {
            return false;
        }
        if (this.getDesc() != null ? !this.getDesc().equals(item.getDesc()) : item.getDesc() != null) {
            return false;
        }
        return this.getCreated() == item.getCreated();
    }

    /**
     * @return HashCode
     */
    @Override
    public int hashCode() {
        final int multiplier = 31;
        int result = this.getID() != null ? getID().hashCode() : 0;
        result = multiplier * result + this.getName().hashCode();
        result = multiplier * result + this.getDesc().hashCode();
        result = multiplier * result + (int) this.getCreated();
        return result;
    }
}


text:
namespace AldursLab.WurmAssistant3.Areas.Timers
{
    partial class PlayerLayoutView
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
            this.label1 = new System.Windows.Forms.Label();
            this.buttonAdd = new System.Windows.Forms.Button();
            this.tableLayoutPanel1.SuspendLayout();
            this.tableLayoutPanel2.SuspendLayout();
            this.SuspendLayout();
            //
            // flowLayoutPanel1
            //
            this.flowLayoutPanel1.AutoSize = true;
            this.flowLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.flowLayoutPanel1.Location = new System.Drawing.Point(2, 20);
            this.flowLayoutPanel1.Margin = new System.Windows.Forms.Padding(2);
            this.flowLayoutPanel1.Name = "flowLayoutPanel1";
            this.flowLayoutPanel1.Size = new System.Drawing.Size(211, 1);
            this.flowLayoutPanel1.TabIndex = 0;
            //
            // tableLayoutPanel1
            //
            this.tableLayoutPanel1.AutoSize = true;
            this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.tableLayoutPanel1.ColumnCount = 1;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
            this.tableLayoutPanel1.Location = new System.Drawing.Point(2, 2);
            this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.RowCount = 2;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 18F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(215, 22);
            this.tableLayoutPanel1.TabIndex = 1;
            //
            // tableLayoutPanel2
            //
            this.tableLayoutPanel2.ColumnCount = 2;
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 52F));
            this.tableLayoutPanel2.Controls.Add(this.label1, 0, 0);
            this.tableLayoutPanel2.Controls.Add(this.buttonAdd, 1, 0);
            this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0);
            this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(0);
            this.tableLayoutPanel2.Name = "tableLayoutPanel2";
            this.tableLayoutPanel2.RowCount = 1;
            this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            this.tableLayoutPanel2.Size = new System.Drawing.Size(215, 18);
            this.tableLayoutPanel2.TabIndex = 1;
            //
            // label1
            //
            this.label1.AutoSize = true;
            this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.label1.Location = new System.Drawing.Point(2, 0);
            this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(159, 18);
            this.label1.TabIndex = 0;
            this.label1.Text = "playerName";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            //
            // buttonAdd
            //
            this.buttonAdd.Enabled = false;
            this.buttonAdd.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            this.buttonAdd.Location = new System.Drawing.Point(163, 0);
            this.buttonAdd.Margin = new System.Windows.Forms.Padding(0, 0, 2, 0);
            this.buttonAdd.Name = "buttonAdd";
            this.buttonAdd.Size = new System.Drawing.Size(50, 18);
            this.buttonAdd.TabIndex = 1;
            this.buttonAdd.Text = "+";
            this.buttonAdd.UseVisualStyleBackColor = true;
            this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
            //
            // PlayerLayoutView
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.Controls.Add(this.tableLayoutPanel1);
            this.Margin = new System.Windows.Forms.Padding(1);
            this.MinimumSize = new System.Drawing.Size(12, 13);
            this.Name = "PlayerLayoutView";
            this.Size = new System.Drawing.Size(217, 24);
            this.Load += new System.EventHandler(this.UControlPlayerLayout_Load);
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.tableLayoutPanel2.ResumeLayout(false);
            this.tableLayoutPanel2.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
        private System.Windows.Forms.Button buttonAdd;
    }
}


text:
module OneviewCookbook
  module API2000
    module C7000
      # ServerHardware API2000 C7000 provider
      class ServerHardwareProvider < OneviewCookbook::API1800::C7000::ServerHardwareProvider
      end
    end
  end
end


text:
source subr.sh

CONFIG_DIR="$(setup)"
CONFIG_PATH="$CONFIG_DIR/syndicate.conf"
RANDOM_PATH="$(mktemp "/tmp/testvolume-XXXXXX")"
rm "$RANDOM_PATH"

echo "config dir: $CONFIG_DIR"

RANDOM_VOLUME_NAME="$(basename "$RANDOM_PATH")"

$SYNDICATE -c "$CONFIG_PATH" create_volume name="$RANDOM_VOLUME_NAME" description="test create_volume" blocksize=4096 email="$SYNDICATE_ADMIN_EMAIL"
RC=$?

if [ $RC -ne 0 ]; then
   test_fail "Failed to create volume"
fi

$SYNDICATE -c "$CONFIG_PATH" update_volume "$RANDOM_VOLUME_NAME" description="foo" private=False file_quota=123456
RC=$?

if [ $RC -ne 0 ]; then
   test_fail "Failed to update volume"
fi

VOLUME_JSON="$($SYNDICATE -c "$CONFIG_PATH" list_volumes)"
RC=$?

if [ $RC -ne 0 ]; then
   test_fail "Failed to list volumes"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "description" | grep "foo")" ]; then
   test_fail "Failed to set volume description"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "private" | grep "False")" ]; then
   test_fail "Failed to set volume privacy"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "file_quota" | grep "123456")" ]; then
   test_fail "Failed to set volume file quota"
fi

VOLUME_JSON="$($SYNDICATE -c "$CONFIG_PATH" read_volume "$RANDOM_VOLUME_NAME")"
RC=$?

if [ $RC -ne 0 ]; then
   test_fail "Failed to list volumes"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "description" | grep "foo")" ]; then
   test_fail "Failed to set volume description"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "private" | grep "False")" ]; then
   test_fail "Failed to set volume privacy"
fi

if [ -z "$(echo "$VOLUME_JSON" | grep "file_quota" | grep "123456")" ]; then
   test_fail "Failed to set volume file quota"
fi

# cleanup
$SYNDICATE -c "$CONFIG_PATH" delete_volume "$RANDOM_VOLUME_NAME"
RC=$?

if [ $RC -ne 0 ]; then
   test_fail "Failed to clean up volume $RANDOM_VOLUME_NAME"
fi

test_success
exit 0


text:
package com.amudabadmus.myeapp;

import java.io.IOException;
import java.net.URL;
public class Test
{
    public static void main (String[] args) throws Exception
    {
        try {
            URL url = new URL("https://github.com/badmusamuda/E-App/tree/master/Quizzes/");
            System.out.println(url.getFile());
        }
        catch(IOException ex) {

            ex.printStackTrace(); // for now, simply output it.
        }
    }

}


text:
var Job = require('./Job');
var util = require('util');
var fixtures = require('./fixtures');

function Parent(input) {
	Job.call(this, fixtures.parentType, {
		input: input
	});
}
util.inherits(Parent, Job);

function Child(input) {
	Job.call(this, fixtures.childType, {
		input: input
	});
}
util.inherits(Child, Job);

module.exports = {
	Child: Child,
	Parent: Parent
};


text:
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse

from canvas import view_guards
from canvas.tests.tests_helpers import CanvasTestCase, FakeRequest, create_user, create_staff

class TestViewGuards(CanvasTestCase):
    def setUp(self):
        super(TestViewGuards, self).setUp()
        self.text = 'yeah ok'

        for guard_name in ['require_secure',
                           'require_staff',
                           'require_user',
                           'require_POST']:
            guard = getattr(view_guards, guard_name)
            @guard
            def foo(request):
                return HttpResponse(self.text)
            setattr(self, guard_name, foo)

    def test_secure_without_https(self):
        request = FakeRequest()
        response = self.require_secure(request)
        self.assertEqual(response.status_code, 302)

    def test_secure_with_https(self):
        request = FakeRequest()
        request.META['HTTP_X_FORWARDED_PROTO'] = 'https'
        response = self.require_secure(request)
        self.assertEqual(response.content, self.text)

    def test_POST_with_GET(self):
        request = FakeRequest()
        response = self.require_POST(request)
        self.assertEqual(response.status_code, 405) # Not Allowed.

    def test_POST_with_POST(self):
        request = FakeRequest()
        request.method = 'POST'
        response = self.require_POST(request)
        self.assertEqual(response.status_code, 200)

    def test_user_with_anon(self):
        request = FakeRequest()
        self.assertRaises(PermissionDenied, lambda: self.require_user(request))

    def test_user_with_user(self):
        request = FakeRequest(user=create_user())
        response = self.require_user(request)
        self.assertEqual(response.status_code, 200)

    def test_staff_with_anon(self):
        request = FakeRequest()
        self.assertRaises(PermissionDenied, lambda: self.require_staff(request))

    def test_staff_with_nonstaff_user(self):
        request = FakeRequest(user=create_user())
        self.assertRaises(PermissionDenied, lambda: self.require_staff(request))

    def test_staff_with_staff(self):
        request = FakeRequest(user=create_staff())
        response = self.require_staff(request)
        self.assertEqual(response.status_code, 200)


text:
/*
 * croquis.brushes.js
 * easily initalize brushes with this library
 * by @lazykuna
 */

Croquis.BrushImage = function(croquis, brushpaths, ulelement, onChangeEvent) {
	var self = this;
	self.onChange = onChangeEvent;
	self.imgs = [];

	for (i=0; i<brushpaths.length; i++) {
		var path = brushpaths[i];
	    var brushimg = document.createElement('img');
	    if (path == null) {
	    	// TODO
	    	brushimg.className = "nobrush";
	    	brushimg.style.setProperty("display", "block");
	    	brushimg.style.setProperty("border-radius", "23px");
	    	brushimg.style.setProperty("background-color", "black");
	    } else {
	    	console.log(path);
	   		brushimg.src = path;
	    }

	    var brushele = document.createElement('li');
	    brushele.className = i;
	    brushele.addEventListener('click', function () {
	    	var i = this.className;
	    	console.log(i);
	    	var p = brushpaths[i];
	    	var img = self.imgs[i];
	    	var brush = croquis.getTool();
	    	if (p == null) {
	    		brush.setImage(null);
	    	} else {
	    		brush.setImage(img);
	    	}

			if (self.onChange != null) {
				self.onChange(p);
			}
	    });

	    self.imgs.push(brushimg);

	    brushele.appendChild(brushimg);
		ulelement.appendChild(brushele);
	}
}


text:
'use strict';

const boom = require('boom');
const joi = require('joi');
const schema = require('screwdriver-data-schema');
const listSchema = joi.array().items(schema.models.template.get).label('List of templates');
const distinctSchema = joi.string()
    .valid(Object.keys(schema.models.template.base.describe().children))
    .label('Field to return unique results by');
const compactSchema = joi.string()
    .valid(['', 'false', 'true'])
    .label('Flag to return compact data');
const namespaceSchema = joi.reach(schema.models.template.base, 'namespace');
const namespacesSchema = joi.array().items(joi.object().keys({ namespace: namespaceSchema }));

module.exports = () => ({
    method: 'GET',
    path: '/templates',
    config: {
        description: 'Get templates with pagination',
        notes: 'Returns all template records',
        tags: ['api', 'templates'],
        auth: {
            strategies: ['token'],
            scope: ['user', 'build']
        },
        plugins: {
            'hapi-swagger': {
                security: [{ token: [] }]
            }
        },
        handler: (request, reply) => {
            const factory = request.server.app.templateFactory;
            const {
                count,
                distinct,
                compact,
                namespace,
                page,
                search,
                sort,
                sortBy
            } = request.query;
            const config = { sort };

            // Return distinct rows for that column name
            if (distinct) {
                config.params = { distinct };
                config.raw = true;
            }

            if (namespace) {
                config.params = { namespace };
            }

            if (sortBy) {
                config.sortBy = sortBy;
            }

            if (search) {
                let fieldsToSearch = ['name', 'namespace', 'description'];

                // Remove from fields to search if namespace is already a param
                if (config.params && config.params.namespace) {
                    fieldsToSearch = fieldsToSearch.filter(e => e !== 'namespace');
                }

                config.search = {
                    field: fieldsToSearch,
                    // Do a fuzzy search for template name
                    // See https://www.w3schools.com/sql/sql_like.asp for syntax
                    keyword: `%${search}%`
                };
            }

            // check if the call wants compact data
            if (compact === 'true') {
                // removing `config` trims most of the bytes
                config.exclude = ['config'];
                config.groupBy = ['namespace', 'name'];
            }

            if (page || count) {
                config.paginate = { page, count };
            }

            return factory
                .list(config)
                .then((templates) => {
                    if (config.raw) {
                        return reply(templates);
                    }

                    return reply(templates.map(p => p.toJson()));
                })
                .catch(err => reply(boom.boomify(err)));
        },
        response: {
            schema: joi.alternatives().try(listSchema, namespacesSchema)
        },
        validate: {
            query: schema.api.pagination.concat(
                joi.object({
                    namespace: namespaceSchema,
                    distinct: distinctSchema,
                    compact: compactSchema
                })
            )
        }
    }
});


text:
layout: post
title: Aceh, 7 Desember 2016
description: Puisi untuk Aceh
share: true
tag: puisi
---
Seperti kasih Tuhan,
bencana tak mengenal apa.
Menyatukan kita,
dalam sama rasa--sama doa.

Aceh, Bireuen, Pidie, Pidie Jaya.
Saudara kita--Indonesia,
dalam duka.

Mari sejenak,
heningkan cipta, ulurkan doa.

Kuatkan percaya,
bahwa selalu ada hikmah di setiap rencana-Nya.


text:
using namespace std;
using namespace utils;

// for convenience
using json = nlohmann::json;

// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s) {
  auto found_null = s.find("null");
  auto b1 = s.find_first_of("[");
  auto b2 = s.find_first_of("}");
  if (found_null != string::npos) {
    return "";
  } else if (b1 != string::npos && b2 != string::npos) {
    return s.substr(b1, b2 - b1 + 2);
  }
  return "";
}

double distance(double x1, double y1, double x2, double y2)
{
	return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{

	double closestLen = 100000; //large number
	int closestWaypoint = 0;

	for(int i = 0; i < maps_x.size(); i++)
	{
		double map_x = maps_x[i];
		double map_y = maps_y[i];
		double dist = distance(x,y,map_x,map_y);
		if(dist < closestLen)
		{
			closestLen = dist;
			closestWaypoint = i;
		}

	}

	return closestWaypoint;

}

int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{

	int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);

	double map_x = maps_x[closestWaypoint];
	double map_y = maps_y[closestWaypoint];

	double heading = atan2((map_y-y),(map_x-x));

	double angle = fabs(theta-heading);
  angle = min(2*pi() - angle, angle);

  if(angle > pi()/4)
  {
    closestWaypoint++;
  if (closestWaypoint == maps_x.size())
  {
    closestWaypoint = 0;
  }
  }

  return closestWaypoint;
}

// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
	int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);

	int prev_wp;
	prev_wp = next_wp-1;
	if(next_wp == 0)
	{
		prev_wp  = maps_x.size()-1;
	}

	double n_x = maps_x[next_wp]-maps_x[prev_wp];
	double n_y = maps_y[next_wp]-maps_y[prev_wp];
	double x_x = x - maps_x[prev_wp];
	double x_y = y - maps_y[prev_wp];

	// find the projection of x onto n
	double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
	double proj_x = proj_norm*n_x;
	double proj_y = proj_norm*n_y;

	double frenet_d = distance(x_x,x_y,proj_x,proj_y);

	//see if d value is positive or negative by comparing it to a center point

	double center_x = 1000-maps_x[prev_wp];
	double center_y = 2000-maps_y[prev_wp];
	double centerToPos = distance(center_x,center_y,x_x,x_y);
	double centerToRef = distance(center_x,center_y,proj_x,proj_y);

	if(centerToPos <= centerToRef)
	{
		frenet_d *= -1;
	}

	// calculate s value
	double frenet_s = 0;
	for(int i = 0; i < prev_wp; i++)
	{
		frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
	}

	frenet_s += distance(0,0,proj_x,proj_y);

	return {frenet_s,frenet_d};

}

int main() {
  uWS::Hub h;

  // Load up map values for waypoint's x,y,s and d normalized normal vectors
  vector<double> map_waypoints_x;
  vector<double> map_waypoints_y;
  vector<double> map_waypoints_s;
  vector<double> map_waypoints_dx;
  vector<double> map_waypoints_dy;

  // Waypoint map to read from
  string map_file_ = "../data/highway_map.csv";
  // The max s value before wrapping around the track back to 0
  double max_s = 6945.554;

	int lane = 1; // start at middle lane
	double ref_vel = 0; // mhp

  ifstream in_map_(map_file_.c_str(), ifstream::in);

  string line;
  while (getline(in_map_, line)) {
  	istringstream iss(line);
  	double x;
  	double y;
  	float s;
  	float d_x;
  	float d_y;
  	iss >> x;
  	iss >> y;
  	iss >> s;
  	iss >> d_x;
  	iss >> d_y;
  	map_waypoints_x.push_back(x);
  	map_waypoints_y.push_back(y);
  	map_waypoints_s.push_back(s);
  	map_waypoints_dx.push_back(d_x);
  	map_waypoints_dy.push_back(d_y);
  }

  h.onMessage(	[&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,&map_waypoints_dx,&map_waypoints_dy,&lane,&ref_vel]
								(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
    // "42" at the start of the message means there's a websocket message event.
    // The 4 signifies a websocket message
    // The 2 signifies a websocket event
    //auto sdata = string(data).substr(0, length);
    //cout << sdata << endl;
    if (length && length > 2 && data[0] == '4' && data[1] == '2') {

      auto s = hasData(data);

      if (s != "") {
        auto j = json::parse(s);

        string event = j[0].get<string>();

        if (event == "telemetry") {
          // j[1] is the data JSON object

        	// Main car's localization Data
          	double car_x = j[1]["x"];
          	double car_y = j[1]["y"];
          	double car_s = j[1]["s"];
          	double car_d = j[1]["d"];
          	double car_yaw = j[1]["yaw"];
          	double car_speed = j[1]["speed"];

          	// Previous path data given to the Planner
          	auto previous_path_x = j[1]["previous_path_x"];
          	auto previous_path_y = j[1]["previous_path_y"];
          	// Previous path's end s and d values
          	double end_path_s = j[1]["end_path_s"];
          	double end_path_d = j[1]["end_path_d"];

          	// Sensor Fusion Data, a list of all other cars on the same side of the road.
          	auto sensor_fusion = j[1]["sensor_fusion"];

          	json msgJson;

						NextValsCalculator nextValsCalculator;
						NextVals nextVals = nextValsCalculator.Calculate(
							previous_path_x, previous_path_y,
							car_x, car_y, car_s, car_d, car_yaw,
							map_waypoints_x, map_waypoints_y, map_waypoints_s,
							lane, ref_vel,
							sensor_fusion,
							end_path_s, end_path_d
						);

          	// TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds
          	msgJson["next_x"] = nextVals.next_x_vals_;
          	msgJson["next_y"] = nextVals.next_y_vals_;

          	auto msg = "42[\"control\","+ msgJson.dump()+"]";

          	//this_thread::sleep_for(chrono::milliseconds(1000));
          	ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);

        }
      } else {
        // Manual driving
        std::string msg = "42[\"manual\",{}]";
        ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
      }
    }
  });

  // We don't need this since we're not using HTTP but if it's removed the
  // program
  // doesn't compile :-(
  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data,
                     size_t, size_t) {
    const std::string s = "
Hello world!
";
    if (req.getUrl().valueLength == 1) {
      res->end(s.data(), s.length());
    } else {
      // i guess this should be done more gracefully?
      res->end(nullptr, 0);
    }
  });

  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
    std::cout << "Connected!!!" << std::endl;
  });

  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
                         char *message, size_t length) {
    ws.close();
    std::cout << "Disconnected" << std::endl;
  });

  int port = 4567;
  if (h.listen(port)) {
    std::cout << "Listening to port " << port << std::endl;
  } else {
    std::cerr << "Failed to listen to port" << std::endl;
    return -1;
  }
  h.run();
}


text:
var makeHttpRequest = function (method, url) {
    var xhr = new XMLHttpRequest();
    if("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest !== "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }

    if(xhr === null) {
        throw new Error("could not create XD request");
    }
    return xhr;
};

var getQueryVariable = function (variable, url)
{
    var query = url.split("?")[1];
    if(query !== undefined) {
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable) {
                return pair[1];
            }
        }
    }
    return(false);
};

var evalJSON = function (json) {
    return eval( "(" + json + ")" );
}


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.vfs;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.testutil.ManualClock;
import com.google.devtools.build.lib.testutil.TestUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;

/**
 * Tests for the {@link JavaIoFileSystem}. That file system by itself is not capable of creating
 * symlinks; use the unix one to create them, so that the test can check that the file system
 * handles their existence correctly.
 */
public class JavaIoFileSystemTest extends SymlinkAwareFileSystemTest {

  private ManualClock clock;

  @Override
  public FileSystem getFreshFileSystem(DigestHashFunction digestHashFunction) {
    clock = new ManualClock();
    return new JavaIoFileSystem(clock, digestHashFunction);
  }

  // Tests are inherited from the FileSystemTest

  // JavaIoFileSystem incorrectly throws a FileNotFoundException for all IO errors. This means that
  // statIfFound incorrectly suppresses those errors.
  @Override
  @Test
  public void testBadPermissionsThrowsExceptionOnStatIfFound() {}

  @Test
  public void testSetLastModifiedTime() throws Exception {
    Path file = xEmptyDirectory.getChild("new-file");
    FileSystemUtils.createEmptyFile(file);

    file.setLastModifiedTime(1000L);
    assertThat(file.getLastModifiedTime()).isEqualTo(1000L);
    file.setLastModifiedTime(0L);
    assertThat(file.getLastModifiedTime()).isEqualTo(0L);

    clock.advanceMillis(42000L);
    file.setLastModifiedTime(-1L);
    assertThat(file.getLastModifiedTime()).isEqualTo(42000L);
  }

  @Override
  protected boolean isHardLinked(Path a, Path b) throws IOException {
    return Files.readAttributes(
            Paths.get(a.toString()), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
        .fileKey()
        .equals(
            Files.readAttributes(
                    Paths.get(b.toString()), BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
                .fileKey());
  }

  /**
   * This test has a large number of threads racing to create the same subdirectories.
   *
   *
We create N number of distinct directory trees, eg. the tree "0-0/0-1/0-2/0-3/0-4" followed
   * by the tree "1-0/1-1/1-2/1-3/1-4" etc. If there is race we should quickly get a deadlock.
   *
   *
A timeout of this test is likely because of a deadlock.
   */
  @Test
  public void testCreateDirectoriesThreadSafety() throws Exception {
    int threadCount = 200;
    int directoryCreationCount = 500; // We create this many sets of directories
    int subDirectoryCount = 5; // Each directory tree is this deep
    ListeningExecutorService executor =
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadCount));
    List<ListenableFuture<IOException>> futures = new ArrayList<>();
    for (int threadIndex = 0; threadIndex < threadCount; ++threadIndex) {
      futures.add(
          executor.submit(
              () -> {
                try {
                  for (int loopi = 0; loopi < directoryCreationCount; ++loopi) {
                    List<Path> subDirs =
                        getSubDirectories(xEmptyDirectory, loopi, subDirectoryCount);
                    Path lastDir = Iterables.getLast(subDirs);
                    lastDir.createDirectoryAndParents();
                  }
                } catch (IOException e) {
                  return e;
                }
                return null;
              }));
    }
    ListenableFuture<List<IOException>> all = Futures.allAsList(futures);
    // If the test times out here then there's likely to be a deadlock
    List<IOException> exceptions =
        all.get(TestUtils.WAIT_TIMEOUT_MILLISECONDS, TimeUnit.MILLISECONDS);
    Optional<IOException> error = exceptions.stream().filter(Objects::nonNull).findFirst();
    if (error.isPresent()) {
      throw error.get();
    }
  }

  private static List<Path> getSubDirectories(Path base, int loopi, int subDirectoryCount) {
    Path path = base;
    List<Path> subDirs = new ArrayList<>();
    for (int subDirIndex = 0; subDirIndex < subDirectoryCount; ++subDirIndex) {
      path = path.getChild(String.format("%d-%d", loopi, subDirIndex));
      subDirs.add(path);
    }
    return subDirs;
  }
}