text:
// Copyright 2011 Google Inc. 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.

#include "build.h"

#include "build_log.h"
#include "graph.h"
#include "test.h"

/// Fixture for tests involving Plan.
// Though Plan doesn't use State, it's useful to have one around
// to create Nodes and Edges.
struct PlanTest : public StateTestWithBuiltinRules {
  Plan plan_;
};

TEST_F(PlanTest, Basic) {
  AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n");
  GetNode("mid")->MarkDirty();
  GetNode("out")->MarkDirty();
  string err;
  EXPECT_TRUE(plan_.AddTarget(GetNode("out"), &err));
  ASSERT_EQ("", err);
  ASSERT_TRUE(plan_.more_to_do());

  Edge* edge = plan_.FindWork();
  ASSERT_TRUE(edge);
  ASSERT_EQ("in",  edge->inputs_[0]->path());
  ASSERT_EQ("mid", edge->outputs_[0]->path());

  ASSERT_FALSE(plan_.FindWork());

  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);
  ASSERT_EQ("mid", edge->inputs_[0]->path());
  ASSERT_EQ("out", edge->outputs_[0]->path());

  plan_.EdgeFinished(edge);

  ASSERT_FALSE(plan_.more_to_do());
  edge = plan_.FindWork();
  ASSERT_EQ(0, edge);
}

// Test that two outputs from one rule can be handled as inputs to the next.
TEST_F(PlanTest, DoubleOutputDirect) {
  AssertParse(&state_,
"build out: cat mid1 mid2\n"
"build mid1 mid2: cat in\n");
  GetNode("mid1")->MarkDirty();
  GetNode("mid2")->MarkDirty();
  GetNode("out")->MarkDirty();

  string err;
  EXPECT_TRUE(plan_.AddTarget(GetNode("out"), &err));
  ASSERT_EQ("", err);
  ASSERT_TRUE(plan_.more_to_do());

  Edge* edge;
  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat in
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat mid1 mid2
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_FALSE(edge);  // done
}

// Test that two outputs from one rule can eventually be routed to another.
TEST_F(PlanTest, DoubleOutputIndirect) {
  AssertParse(&state_,
"build out: cat b1 b2\n"
"build b1: cat a1\n"
"build b2: cat a2\n"
"build a1 a2: cat in\n");
  GetNode("a1")->MarkDirty();
  GetNode("a2")->MarkDirty();
  GetNode("b1")->MarkDirty();
  GetNode("b2")->MarkDirty();
  GetNode("out")->MarkDirty();
  string err;
  EXPECT_TRUE(plan_.AddTarget(GetNode("out"), &err));
  ASSERT_EQ("", err);
  ASSERT_TRUE(plan_.more_to_do());

  Edge* edge;
  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat in
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat a1
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat a2
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat b1 b2
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_FALSE(edge);  // done
}

// Test that two edges from one output can both execute.
TEST_F(PlanTest, DoubleDependent) {
  AssertParse(&state_,
"build out: cat a1 a2\n"
"build a1: cat mid\n"
"build a2: cat mid\n"
"build mid: cat in\n");
  GetNode("mid")->MarkDirty();
  GetNode("a1")->MarkDirty();
  GetNode("a2")->MarkDirty();
  GetNode("out")->MarkDirty();

  string err;
  EXPECT_TRUE(plan_.AddTarget(GetNode("out"), &err));
  ASSERT_EQ("", err);
  ASSERT_TRUE(plan_.more_to_do());

  Edge* edge;
  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat in
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat mid
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat mid
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_TRUE(edge);  // cat a1 a2
  plan_.EdgeFinished(edge);

  edge = plan_.FindWork();
  ASSERT_FALSE(edge);  // done
}

TEST_F(PlanTest, DependencyCycle) {
  AssertParse(&state_,
"build out: cat mid\n"
"build mid: cat in\n"
"build in: cat pre\n"
"build pre: cat out\n");
  GetNode("out")->MarkDirty();
  GetNode("mid")->MarkDirty();
  GetNode("in")->MarkDirty();
  GetNode("pre")->MarkDirty();

  string err;
  EXPECT_FALSE(plan_.AddTarget(GetNode("out"), &err));
  ASSERT_EQ("dependency cycle: out -> mid -> in -> pre -> out", err);
}

struct BuildTest : public StateTestWithBuiltinRules,
                   public CommandRunner {
  BuildTest() : config_(MakeConfig()),
                builder_(&state_, config_, NULL, &fs_),
                now_(1), last_command_(NULL), status_(config_) {
    builder_.command_runner_.reset(this);
    AssertParse(&state_,
"build cat1: cat in1\n"
"build cat2: cat in1 in2\n"
"build cat12: cat cat1 cat2\n");

    fs_.Create("in1", now_, "");
    fs_.Create("in2", now_, "");
  }

  ~BuildTest() {
    builder_.command_runner_.release();
  }

  // Mark a path dirty.
  void Dirty(const string& path);

  // CommandRunner impl
  virtual bool CanRunMore();
  virtual bool StartCommand(Edge* edge);
  virtual Edge* WaitForCommand(ExitStatus* status, string* output);
  virtual vector<Edge*> GetActiveEdges();
  virtual void Abort();

  BuildConfig MakeConfig() {
    BuildConfig config;
    config.verbosity = BuildConfig::QUIET;
    return config;
  }

  BuildConfig config_;
  VirtualFileSystem fs_;
  Builder builder_;
  int now_;

  vector<string> commands_ran_;
  Edge* last_command_;
  BuildStatus status_;
};

void BuildTest::Dirty(const string& path) {
  Node* node = GetNode(path);
  node->MarkDirty();

  // If it's an input file, mark that we've already stat()ed it and
  // it's missing.
  if (!node->in_edge())
    node->MarkMissing();
}

bool BuildTest::CanRunMore() {
  // Only run one at a time.
  return last_command_ == NULL;
}

bool BuildTest::StartCommand(Edge* edge) {
  assert(!last_command_);
  commands_ran_.push_back(edge->EvaluateCommand());
  if (edge->rule().name() == "cat"  ||
      edge->rule().name() == "cat_rsp" ||
      edge->rule().name() == "cc" ||
      edge->rule().name() == "touch" ||
      edge->rule().name() == "touch-interrupt") {
    for (vector<Node*>::iterator out = edge->outputs_.begin();
         out != edge->outputs_.end(); ++out) {
      fs_.Create((*out)->path(), now_, "");
    }
  } else if (edge->rule().name() == "true" ||
             edge->rule().name() == "fail" ||
             edge->rule().name() == "interrupt") {
    // Don't do anything.
  } else {
    printf("unknown command\n");
    return false;
  }

  last_command_ = edge;
  return true;
}

Edge* BuildTest::WaitForCommand(ExitStatus* status, string* /* output */) {
  if (Edge* edge = last_command_) {
    if (edge->rule().name() == "interrupt" ||
        edge->rule().name() == "touch-interrupt") {
      *status = ExitInterrupted;
      return NULL;
    }

    if (edge->rule().name() == "fail")
      *status = ExitFailure;
    else
      *status = ExitSuccess;
    last_command_ = NULL;
    return edge;
  }
  *status = ExitFailure;
  return NULL;
}

vector<Edge*> BuildTest::GetActiveEdges() {
  vector<Edge*> edges;
  if (last_command_)
    edges.push_back(last_command_);
  return edges;
}

void BuildTest::Abort() {
  last_command_ = NULL;
}

TEST_F(BuildTest, NoWork) {
  string err;
  EXPECT_TRUE(builder_.AlreadyUpToDate());
}

TEST_F(BuildTest, OneStep) {
  // Given a dirty target with one ready input,
  // we should rebuild the target.
  Dirty("cat1");
  string err;
  EXPECT_TRUE(builder_.AddTarget("cat1", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);

  ASSERT_EQ(1u, commands_ran_.size());
  EXPECT_EQ("cat in1 > cat1", commands_ran_[0]);
}

TEST_F(BuildTest, OneStep2) {
  // Given a target with one dirty input,
  // we should rebuild the target.
  Dirty("cat1");
  string err;
  EXPECT_TRUE(builder_.AddTarget("cat1", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);

  ASSERT_EQ(1u, commands_ran_.size());
  EXPECT_EQ("cat in1 > cat1", commands_ran_[0]);
}

TEST_F(BuildTest, TwoStep) {
  string err;
  EXPECT_TRUE(builder_.AddTarget("cat12", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);
  ASSERT_EQ(3u, commands_ran_.size());
  // Depending on how the pointers work out, we could've ran
  // the first two commands in either order.
  EXPECT_TRUE((commands_ran_[0] == "cat in1 > cat1" &&
               commands_ran_[1] == "cat in1 in2 > cat2") ||
              (commands_ran_[1] == "cat in1 > cat1" &&
               commands_ran_[0] == "cat in1 in2 > cat2"));

  EXPECT_EQ("cat cat1 cat2 > cat12", commands_ran_[2]);

  now_++;

  // Modifying in2 requires rebuilding one intermediate file
  // and the final file.
  fs_.Create("in2", now_, "");
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("cat12", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(5u, commands_ran_.size());
  EXPECT_EQ("cat in1 in2 > cat2", commands_ran_[3]);
  EXPECT_EQ("cat cat1 cat2 > cat12", commands_ran_[4]);
}

TEST_F(BuildTest, TwoOutputs) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule touch\n"
"  command = touch $out\n"
"build out1 out2: touch in.txt\n"));

  fs_.Create("in.txt", now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
  EXPECT_EQ("touch out1 out2", commands_ran_[0]);
}

// Test case from
//   https://github.com/martine/ninja/issues/148
TEST_F(BuildTest, MultiOutIn) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule touch\n"
"  command = touch $out\n"
"build in1 otherfile: touch in\n"
"build out: touch in | in1\n"));

  fs_.Create("in", now_, "");
  fs_.Create("in1", ++now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("out", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);
}

TEST_F(BuildTest, Chain) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build c2: cat c1\n"
"build c3: cat c2\n"
"build c4: cat c3\n"
"build c5: cat c4\n"));

  fs_.Create("c1", now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("c5", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);
  ASSERT_EQ(4u, commands_ran_.size());

  err.clear();
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("c5", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());

  now_++;

  fs_.Create("c3", now_, "");
  err.clear();
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("c5", &err));
  ASSERT_EQ("", err);
  EXPECT_FALSE(builder_.AlreadyUpToDate());
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(2u, commands_ran_.size());  // 3->4, 4->5
}

TEST_F(BuildTest, MissingInput) {
  // Input is referenced by build file, but no rule for it.
  string err;
  Dirty("in1");
  EXPECT_FALSE(builder_.AddTarget("cat1", &err));
  EXPECT_EQ("'in1', needed by 'cat1', missing and no known rule to make it",
            err);
}

TEST_F(BuildTest, MissingTarget) {
  // Target is not referenced by build file.
  string err;
  EXPECT_FALSE(builder_.AddTarget("meow", &err));
  EXPECT_EQ("unknown target: 'meow'", err);
}

TEST_F(BuildTest, MakeDirs) {
  string err;

#ifdef _WIN32
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_, "build subdir\\dir2\\file: cat in1\n"));
  EXPECT_TRUE(builder_.AddTarget("subdir\\dir2\\file", &err));
#else
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_, "build subdir/dir2/file: cat in1\n"));
  EXPECT_TRUE(builder_.AddTarget("subdir/dir2/file", &err));
#endif

  EXPECT_EQ("", err);
  now_ = 0;  // Make all stat()s return file not found.
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(2u, fs_.directories_made_.size());
  EXPECT_EQ("subdir", fs_.directories_made_[0]);
#ifdef _WIN32
  EXPECT_EQ("subdir\\dir2", fs_.directories_made_[1]);
#else
  EXPECT_EQ("subdir/dir2", fs_.directories_made_[1]);
#endif
}

TEST_F(BuildTest, DepFileMissing) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n  command = cc $in\n  depfile = $out.d\n"
"build foo.o: cc foo.c\n"));
  fs_.Create("foo.c", now_, "");

  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, fs_.files_read_.size());
  EXPECT_EQ("foo.o.d", fs_.files_read_[0]);
}

TEST_F(BuildTest, DepFileOK) {
  string err;
  int orig_edges = state_.edges_.size();
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n  command = cc $in\n  depfile = $out.d\n"
"build foo.o: cc foo.c\n"));
  Edge* edge = state_.edges_.back();

  fs_.Create("foo.c", now_, "");
  GetNode("bar.h")->MarkDirty();  // Mark bar.h as missing.
  fs_.Create("foo.o.d", now_, "foo.o: blah.h bar.h\n");
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, fs_.files_read_.size());
  EXPECT_EQ("foo.o.d", fs_.files_read_[0]);

  // Expect three new edges: one generating foo.o, and two more from
  // loading the depfile.
  ASSERT_EQ(orig_edges + 3, (int)state_.edges_.size());
  // Expect our edge to now have three inputs: foo.c and two headers.
  ASSERT_EQ(3u, edge->inputs_.size());

  // Expect the command line we generate to only use the original input.
  ASSERT_EQ("cc foo.c", edge->EvaluateCommand());
}

TEST_F(BuildTest, DepFileParseError) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n  command = cc $in\n  depfile = $out.d\n"
"build foo.o: cc foo.c\n"));
  fs_.Create("foo.c", now_, "");
  fs_.Create("foo.o.d", now_, "randomtext\n");
  EXPECT_FALSE(builder_.AddTarget("foo.o", &err));
  EXPECT_EQ("expected depfile 'foo.o.d' to mention 'foo.o', got 'randomtext'",
            err);
}

TEST_F(BuildTest, OrderOnlyDeps) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n  command = cc $in\n  depfile = $out.d\n"
"build foo.o: cc foo.c || otherfile\n"));
  Edge* edge = state_.edges_.back();

  fs_.Create("foo.c", now_, "");
  fs_.Create("otherfile", now_, "");
  fs_.Create("foo.o.d", now_, "foo.o: blah.h bar.h\n");
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  ASSERT_EQ("", err);

  // One explicit, two implicit, one order only.
  ASSERT_EQ(4u, edge->inputs_.size());
  EXPECT_EQ(2, edge->implicit_deps_);
  EXPECT_EQ(1, edge->order_only_deps_);
  // Verify the inputs are in the order we expect
  // (explicit then implicit then orderonly).
  EXPECT_EQ("foo.c", edge->inputs_[0]->path());
  EXPECT_EQ("blah.h", edge->inputs_[1]->path());
  EXPECT_EQ("bar.h", edge->inputs_[2]->path());
  EXPECT_EQ("otherfile", edge->inputs_[3]->path());

  // Expect the command line we generate to only use the original input.
  ASSERT_EQ("cc foo.c", edge->EvaluateCommand());

  // explicit dep dirty, expect a rebuild.
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());

  now_++;

  // implicit dep dirty, expect a rebuild.
  fs_.Create("blah.h", now_, "");
  fs_.Create("bar.h", now_, "");
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());

  now_++;

  // order only dep dirty, no rebuild.
  fs_.Create("otherfile", now_, "");
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());

  // implicit dep missing, expect rebuild.
  fs_.RemoveFile("bar.h");
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
}

TEST_F(BuildTest, RebuildOrderOnlyDeps) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n  command = cc $in\n"
"rule true\n  command = true\n"
"build oo.h: cc oo.h.in\n"
"build foo.o: cc foo.c || oo.h\n"));

  fs_.Create("foo.c", now_, "");
  fs_.Create("oo.h.in", now_, "");

  // foo.o and order-only dep dirty, build both.
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(2u, commands_ran_.size());

  // all clean, no rebuild.
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());

  // order-only dep missing, build it only.
  fs_.RemoveFile("oo.h");
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
  ASSERT_EQ("cc oo.h.in", commands_ran_[0]);

  now_++;

  // order-only dep dirty, build it only.
  fs_.Create("oo.h.in", now_, "");
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("foo.o", &err));
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
  ASSERT_EQ("cc oo.h.in", commands_ran_[0]);
}

TEST_F(BuildTest, Phony) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat bar.cc\n"
"build all: phony out\n"));
  fs_.Create("bar.cc", now_, "");

  EXPECT_TRUE(builder_.AddTarget("all", &err));
  ASSERT_EQ("", err);

  // Only one command to run, because phony runs no command.
  EXPECT_FALSE(builder_.AlreadyUpToDate());
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
}

TEST_F(BuildTest, PhonyNoWork) {
  string err;
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build out: cat bar.cc\n"
"build all: phony out\n"));
  fs_.Create("bar.cc", now_, "");
  fs_.Create("out", now_, "");

  EXPECT_TRUE(builder_.AddTarget("all", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());
}

TEST_F(BuildTest, Fail) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule fail\n"
"  command = fail\n"
"build out1: fail\n"));

  string err;
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  ASSERT_EQ("", err);

  EXPECT_FALSE(builder_.Build(&err));
  ASSERT_EQ(1u, commands_ran_.size());
  ASSERT_EQ("subcommand failed", err);
}

TEST_F(BuildTest, SwallowFailures) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule fail\n"
"  command = fail\n"
"build out1: fail\n"
"build out2: fail\n"
"build out3: fail\n"
"build all: phony out1 out2 out3\n"));

  // Swallow two failures, die on the third.
  config_.failures_allowed = 3;

  string err;
  EXPECT_TRUE(builder_.AddTarget("all", &err));
  ASSERT_EQ("", err);

  EXPECT_FALSE(builder_.Build(&err));
  ASSERT_EQ(3u, commands_ran_.size());
  ASSERT_EQ("subcommands failed", err);
}

TEST_F(BuildTest, SwallowFailuresLimit) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule fail\n"
"  command = fail\n"
"build out1: fail\n"
"build out2: fail\n"
"build out3: fail\n"
"build final: cat out1 out2 out3\n"));

  // Swallow ten failures; we should stop before building final.
  config_.failures_allowed = 11;

  string err;
  EXPECT_TRUE(builder_.AddTarget("final", &err));
  ASSERT_EQ("", err);

  EXPECT_FALSE(builder_.Build(&err));
  ASSERT_EQ(3u, commands_ran_.size());
  ASSERT_EQ("cannot make progress due to previous errors", err);
}

struct BuildWithLogTest : public BuildTest {
  BuildWithLogTest() {
    builder_.SetBuildLog(&build_log_);
  }

  BuildLog build_log_;
};

TEST_F(BuildWithLogTest, NotInLogButOnDisk) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule cc\n"
"  command = cc\n"
"build out1: cc in\n"));

  // Create input/output that would be considered up to date when
  // not considering the command line hash.
  fs_.Create("in", now_, "");
  fs_.Create("out1", now_, "");
  string err;

  // Because it's not in the log, it should not be up-to-date until
  // we build again.
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  EXPECT_FALSE(builder_.AlreadyUpToDate());

  commands_ran_.clear();
  state_.Reset();

  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_TRUE(builder_.AlreadyUpToDate());
}

TEST_F(BuildWithLogTest, RestatTest) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule true\n"
"  command = true\n"
"  restat = 1\n"
"rule cc\n"
"  command = cc\n"
"  restat = 1\n"
"build out1: cc in\n"
"build out2: true out1\n"
"build out3: cat out2\n"));

  fs_.Create("out1", now_, "");
  fs_.Create("out2", now_, "");
  fs_.Create("out3", now_, "");

  now_++;

  fs_.Create("in", now_, "");

  // Do a pre-build so that there's commands in the log for the outputs,
  // otherwise, the lack of an entry in the build log will cause out3 to rebuild
  // regardless of restat.
  string err;
  EXPECT_TRUE(builder_.AddTarget("out3", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  commands_ran_.clear();
  state_.Reset();

  now_++;

  fs_.Create("in", now_, "");
  // "cc" touches out1, so we should build out2.  But because "true" does not
  // touch out2, we should cancel the build of out3.
  EXPECT_TRUE(builder_.AddTarget("out3", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(2u, commands_ran_.size());

  // If we run again, it should be a no-op, because the build log has recorded
  // that we've already built out2 with an input timestamp of 2 (from out1).
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out3", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());

  now_++;

  fs_.Create("in", now_, "");

  // The build log entry should not, however, prevent us from rebuilding out2
  // if out1 changes.
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out3", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(2u, commands_ran_.size());
}

TEST_F(BuildWithLogTest, RestatMissingFile) {
  // If a restat rule doesn't create its output, and the output didn't
  // exist before the rule was run, consider that behavior equivalent
  // to a rule that doesn't modify its existent output file.

  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule true\n"
"  command = true\n"
"  restat = 1\n"
"rule cc\n"
"  command = cc\n"
"build out1: true in\n"
"build out2: cc out1\n"));

  fs_.Create("in", now_, "");
  fs_.Create("out2", now_, "");

  // Do a pre-build so that there's commands in the log for the outputs,
  // otherwise, the lack of an entry in the build log will cause out2 to rebuild
  // regardless of restat.
  string err;
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ("", err);
  commands_ran_.clear();
  state_.Reset();

  now_++;
  fs_.Create("in", now_, "");
  fs_.Create("out2", now_, "");

  // Run a build, expect only the first command to run.
  // It doesn't touch its output (due to being the "true" command), so
  // we shouldn't run the dependent build.
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(1u, commands_ran_.size());
}

// Test scenario, in which an input file is removed, but output isn't changed
// https://github.com/martine/ninja/issues/295
TEST_F(BuildWithLogTest, RestatMissingInput) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
    "rule true\n"
    "  command = true\n"
    "  depfile = $out.d\n"
    "  restat = 1\n"
    "rule cc\n"
    "  command = cc\n"
    "build out1: true in\n"
    "build out2: cc out1\n"));

  // Create all necessary files
  fs_.Create("in", now_, "");

  // The implicit dependencies and the depfile itself
  // are newer than the output
  TimeStamp restat_mtime = ++now_;
  fs_.Create("out1.d", now_, "out1: will.be.deleted restat.file\n");
  fs_.Create("will.be.deleted", now_, "");
  fs_.Create("restat.file", now_, "");

  // Run the build, out1 and out2 get built
  string err;
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(2u, commands_ran_.size());

  // See that an entry in the logfile is created, capturing
  // the right mtime
  BuildLog::LogEntry * log_entry = build_log_.LookupByOutput("out1");
  ASSERT_TRUE(NULL != log_entry);
  ASSERT_EQ(restat_mtime, log_entry->restat_mtime);

  // Now remove a file, referenced from depfile, so that target becomes
  // dirty, but the output does not change
  fs_.RemoveFile("will.be.deleted");

  // Trigger the build again - only out1 gets built
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(1u, commands_ran_.size());

  // Check that the logfile entry remains correctly set
  log_entry = build_log_.LookupByOutput("out1");
  ASSERT_TRUE(NULL != log_entry);
  ASSERT_EQ(restat_mtime, log_entry->restat_mtime);
}

struct BuildDryRun : public BuildWithLogTest {
  BuildDryRun() {
    config_.dry_run = true;
  }
};

TEST_F(BuildDryRun, AllCommandsShown) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule true\n"
"  command = true\n"
"  restat = 1\n"
"rule cc\n"
"  command = cc\n"
"  restat = 1\n"
"build out1: cc in\n"
"build out2: true out1\n"
"build out3: cat out2\n"));

  fs_.Create("out1", now_, "");
  fs_.Create("out2", now_, "");
  fs_.Create("out3", now_, "");

  now_++;

  fs_.Create("in", now_, "");

  // "cc" touches out1, so we should build out2.  But because "true" does not
  // touch out2, we should cancel the build of out3.
  string err;
  EXPECT_TRUE(builder_.AddTarget("out3", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(3u, commands_ran_.size());
}

// Test that RSP files are created when & where appropriate and deleted after
// successful execution.
TEST_F(BuildTest, RspFileSuccess)
{
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
    "rule cat_rsp\n"
    "  command = cat $rspfile > $out\n"
    "  rspfile = $rspfile\n"
    "  rspfile_content = $long_command\n"
    "build out1: cat in\n"
    "build out2: cat_rsp in\n"
    "  rspfile = out2.rsp\n"
    "  long_command = Some very long command\n"));

  fs_.Create("out1", now_, "");
  fs_.Create("out2", now_, "");
  fs_.Create("out3", now_, "");

  now_++;

  fs_.Create("in", now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);

  size_t files_created = fs_.files_created_.size();
  size_t files_removed = fs_.files_removed_.size();

  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(2u, commands_ran_.size()); // cat + cat_rsp

  // The RSP file was created
  ASSERT_EQ(files_created + 1, fs_.files_created_.size());
  ASSERT_EQ(1u, fs_.files_created_.count("out2.rsp"));

  // The RSP file was removed
  ASSERT_EQ(files_removed + 1, fs_.files_removed_.size());
  ASSERT_EQ(1u, fs_.files_removed_.count("out2.rsp"));
}

// Test that RSP file is created but not removed for commands, which fail
TEST_F(BuildTest, RspFileFailure) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
    "rule fail\n"
    "  command = fail\n"
    "  rspfile = $rspfile\n"
    "  rspfile_content = $long_command\n"
    "build out: fail in\n"
    "  rspfile = out.rsp\n"
    "  long_command = Another very long command\n"));

  fs_.Create("out", now_, "");
  now_++;
  fs_.Create("in", now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("out", &err));
  ASSERT_EQ("", err);

  size_t files_created = fs_.files_created_.size();
  size_t files_removed = fs_.files_removed_.size();

  EXPECT_FALSE(builder_.Build(&err));
  ASSERT_EQ("subcommand failed", err);
  ASSERT_EQ(1u, commands_ran_.size());

  // The RSP file was created
  ASSERT_EQ(files_created + 1, fs_.files_created_.size());
  ASSERT_EQ(1u, fs_.files_created_.count("out.rsp"));

  // The RSP file was NOT removed
  ASSERT_EQ(files_removed, fs_.files_removed_.size());
  ASSERT_EQ(0u, fs_.files_removed_.count("out.rsp"));

  // The RSP file contains what it should
  ASSERT_EQ("Another very long command", fs_.files_["out.rsp"].contents);
}

// Test that contens of the RSP file behaves like a regular part of
// command line, i.e. triggers a rebuild if changed
TEST_F(BuildWithLogTest, RspFileCmdLineChange) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
    "rule cat_rsp\n"
    "  command = cat $rspfile > $out\n"
    "  rspfile = $rspfile\n"
    "  rspfile_content = $long_command\n"
    "build out: cat_rsp in\n"
    "  rspfile = out.rsp\n"
    "  long_command = Original very long command\n"));

  fs_.Create("out", now_, "");
  now_++;
  fs_.Create("in", now_, "");

  string err;
  EXPECT_TRUE(builder_.AddTarget("out", &err));
  ASSERT_EQ("", err);

  // 1. Build for the 1st time (-> populate log)
  EXPECT_TRUE(builder_.Build(&err));
  ASSERT_EQ(1u, commands_ran_.size());

  // 2. Build again (no change)
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out", &err));
  EXPECT_EQ("", err);
  ASSERT_TRUE(builder_.AlreadyUpToDate());

  // 3. Alter the entry in the logfile
  // (to simulate a change in the command line between 2 builds)
  BuildLog::LogEntry * log_entry = build_log_.LookupByOutput("out");
  ASSERT_TRUE(NULL != log_entry);
  ASSERT_NO_FATAL_FAILURE(AssertHash(
        "cat out.rsp > out;rspfile=Original very long command",
        log_entry->command_hash));
  log_entry->command_hash++;  // Change the command hash to something else.
  // Now expect the target to be rebuilt
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out", &err));
  EXPECT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ(1u, commands_ran_.size());
}

TEST_F(BuildTest, InterruptCleanup) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"rule interrupt\n"
"  command = interrupt\n"
"rule touch-interrupt\n"
"  command = touch-interrupt\n"
"build out1: interrupt in1\n"
"build out2: touch-interrupt in2\n"));

  fs_.Create("out1", now_, "");
  fs_.Create("out2", now_, "");
  now_++;
  fs_.Create("in1", now_, "");
  fs_.Create("in2", now_, "");

  // An untouched output of an interrupted command should be retained.
  string err;
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  EXPECT_EQ("", err);
  EXPECT_FALSE(builder_.Build(&err));
  EXPECT_EQ("interrupted by user", err);
  builder_.Cleanup();
  EXPECT_EQ(now_-1, fs_.Stat("out1"));
  err = "";

  // A touched output of an interrupted command should be deleted.
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  EXPECT_EQ("", err);
  EXPECT_FALSE(builder_.Build(&err));
  EXPECT_EQ("interrupted by user", err);
  builder_.Cleanup();
  EXPECT_EQ(0, fs_.Stat("out2"));
}

TEST_F(BuildTest, PhonyWithNoInputs) {
  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
"build nonexistent: phony\n"
"build out1: cat || nonexistent\n"
"build out2: cat nonexistent\n"));
  fs_.Create("out1", now_, "");
  fs_.Create("out2", now_, "");

  // out1 should be up to date even though its input is dirty, because its
  // order-only dependency has nothing to do.
  string err;
  EXPECT_TRUE(builder_.AddTarget("out1", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.AlreadyUpToDate());

  // out2 should still be out of date though, because its input is dirty.
  err.clear();
  commands_ran_.clear();
  state_.Reset();
  EXPECT_TRUE(builder_.AddTarget("out2", &err));
  ASSERT_EQ("", err);
  EXPECT_TRUE(builder_.Build(&err));
  EXPECT_EQ("", err);
  ASSERT_EQ(1u, commands_ran_.size());
}

TEST_F(BuildTest, StatusFormatReplacePlaceholder) {
  EXPECT_EQ("[%/s0/t0/r0/u0/f0]",
            status_.FormatProgressStatus("[%%/s%s/t%t/r%r/u%u/f%f]"));
}


text: Unknown script types should not be loaded nor executed. If this test fails, an extra line will appear in the output with the script's MIME type.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Magento\SecondModule\Model;

class Model
{
    /**
     * @return void
     */
    public function test()
    {
        __('Model');
    }
}


text:
class User < ActiveRecord::Base
  has_secure_password
  validates_presence_of :password, :on => :create
  before_create :set_auth_token
  has_many :notes

  private
    def set_auth_token
      return if auth_token.present?

      begin
        self.auth_token = SecureRandom.hex
      end while self.class.exists?(auth_token: self.auth_token)
  end
end


text:
import config  from './index';

const globals = config.get('globals');
const paths   = config.get('utils_paths');

const webpackConfig = {
  entry: paths.src('entry'),
  output: {
    path: paths.project(config.get('dir_dist')),
    filename: 'main.js'
  },
  plugins: [],
  module: {
    preLoaders: [
      {
        test: /\.js$/,
        loader: 'eslint',
        include: paths.project(config.get('dir_src')),
      },
    ],
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
    ],
  },
  eslint: {
    configFile: paths.project('.eslintrc'),
    failOnError: globals.__PROD__,
    emitWarning: globals.__DEV__,
  },
};

export default webpackConfig;


text:
<?php
/**
 * Rendering ajax_table twig extension
 *
 * @author Pavel Pechreny ppecheny@gmail.com
 */
namespace SD\CommonBundle\Twig;

/**
 * AjaxTableExtension
 */
class AjaxTableExtension extends \Twig_Extension
{
    /**
     * @var \Twig_Environment
     */
    protected $environment;

    /**
     * {@inheritDoc}
     */
    public function initRuntime(\Twig_Environment $environment)
    {
        $this->environment = $environment;
    }

    /**
     * {@inheritDoc}
     */
    public function getName()
    {
        return 'ajax_table';
    }

    /**
     * {@inheritDoc}
     */
    public function getFunctions()
    {
        return array(
            'ajax_table_render' => new \Twig_Function_Method($this, 'render', array('is_safe' => array('html')))
        );
    }

    /**
     * {@inheritDoc}
     */
    public function render($params)
    {
        return $this->environment->render('SDCommonBundle:AjaxTable:index.html.twig', array(
            'params' => $params
        ));
    }
}


text:
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Compilation.Validation;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DotVVM.Framework.Controls
{

    [ControlMarkupOptions(AllowContent = false, DefaultContentProperty = nameof(ContentTemplate))]
    public class GridViewTemplateColumn : GridViewColumn
    {

        [MarkupOptions(AllowBinding = false, MappingMode = MappingMode.InnerElement, Required = true)]
        public ITemplate? ContentTemplate
        {
            get { return (ITemplate?)GetValue(ContentTemplateProperty); }
            set { SetValue(ContentTemplateProperty, value); }
        }
        public static readonly DotvvmProperty ContentTemplateProperty
            = DotvvmProperty.Register<ITemplate?, GridViewTemplateColumn>(c => c.ContentTemplate, null);

        public override void CreateControls(IDotvvmRequestContext context, DotvvmControl container)
        {
            ContentTemplate.NotNull("GridViewTemplateColumn.ContentTemplate must be set")
                           .BuildContent(context, container);
        }
    }
}


text:
require 'faraday'
require 'faraday_middleware'
require 'faraday/multipart'

Dir[File.expand_path('../resources/*.rb', __FILE__)].each { |f| require f }
require File.expand_path('../response/base.rb', __FILE__)
require File.expand_path('../recurring_frequencies.rb', __FILE__)
Dir[File.expand_path('../response/*.rb', __FILE__)].each { |f| require f }

module RockRMS
  class Client
    include RecurringFrequencies
    include RockRMS::Client::Attribute
    include RockRMS::Client::AttributeValue
    include RockRMS::Client::Batch
    include RockRMS::Client::BinaryFile
    include RockRMS::Client::Block
    include RockRMS::Client::BlockType
    include RockRMS::Client::Fund
    include RockRMS::Client::Campus
    include RockRMS::Client::DefinedType
    include RockRMS::Client::DefinedValue
    include RockRMS::Client::Gateway
    include RockRMS::Client::Group
    include RockRMS::Client::GroupMember
    include RockRMS::Client::History
    include RockRMS::Client::Page
    include RockRMS::Client::PaymentDetail
    include RockRMS::Client::Person
    include RockRMS::Client::PhoneNumber
    include RockRMS::Client::RecurringDonation
    include RockRMS::Client::RecurringDonationDetail
    include RockRMS::Client::Refund
    include RockRMS::Client::RefundReason
    include RockRMS::Client::Registration
    include RockRMS::Client::SavedPaymentMethod
    include RockRMS::Client::ServiceJob
    include RockRMS::Client::Transaction
    include RockRMS::Client::TransactionDetail
    include RockRMS::Client::TransactionImage
    include RockRMS::Client::UserLogin
    include RockRMS::Client::Utility
    include RockRMS::Client::WorkflowActionType
    include RockRMS::Client::WorkflowActivityType
    include RockRMS::Client::WorkflowType

    attr_reader :url, :username, :password, :logger, :cookie, :connection, :adapter, :ssl

    def initialize(url:, username:, password:, logger: true, adapter: Faraday.default_adapter, ssl: nil)
      @url      = "#{url}/api/"
      @username = username
      @password = password
      @logger   = logger
      @adapter  = adapter
      @ssl      = ssl
      @cookie   = auth['set-cookie']
    end

    def delete(path, options = {})
      connection.delete(path, options).body
    end

    def get(path, options = {})
      connection.get(path, options).body
    end

    def patch(path, options = {})
      connection.patch(path, options).body
    end

    def post(path, options = {})
      connection.post(path, options).body
    end

    def put(path, options = {})
      connection.put(path, options).body
    end

    private

    def auth
      begin
        auth_request('Auth/Login')
      rescue Faraday::ParsingError => e
        if e.message.include?('Document Moved')
          auth_request('auth/login')
        else
          raise e
        end
      end
    end

    def auth_request(path)
      connection.post(
        path,
        'Username'  => username,
        'Password'  => password,
        'Persisted' => true
      )
    end

    def connection
      headers = {
        accept: 'application/json',
        'User-Agent' => "rock-rms-ruby-gem/v#{RockRMS::VERSION}"
      }

      headers['Cookie'] = cookie if cookie

      client_opts = {
        url: url,
        headers: headers
      }

      client_opts[:ssl] = ssl if ssl

      Faraday.new(client_opts) do |conn|
        conn.request   :multipart
        conn.request   :json
        conn.response  :logger if logger
        conn.response  :oj
        conn.use       FaradayMiddleware::RockRMSErrorHandler
        conn.adapter   adapter
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.gradle.api.tasks.incremental (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style">

org.gradle.api.tasks.incremental

Interfaces

IncrementalTaskInputs

InputFileDetails


text:
// ***********************************************************************
// Assembly         : ACBr.Net.NFSe
// Author           : RFTD
// Created          : 05-22-2018
//
// Last Modified By : RFTD
// Last Modified On : 05-22-2018
// ***********************************************************************
// <copyright file="ProviderBetha.cs" company="ACBr.Net">
//		        		   The MIT License (MIT)
//	     		    Copyright (c) 2016 Grupo ACBr.Net
//
//	 Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//	 The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//	 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using ACBr.Net.Core.Extensions;
using ACBr.Net.DFe.Core;
using ACBr.Net.DFe.Core.Serializer;
using ACBr.Net.NFSe.Configuracao;
using ACBr.Net.NFSe.Nota;

namespace ACBr.Net.NFSe.Providers.Betha
{
    internal sealed class ProviderBetha : ProviderABRASF
    {
        #region Constructors

        public ProviderBetha(ConfigNFSe config, ACBrMunicipioNFSe municipio) : base(config, municipio)
        {
            Name = "Betha";
        }

        #endregion Constructors

        #region Methods

        #region Services

        public override RetornoWebservice Enviar(int lote, NotaFiscalCollection notas)

        {
            var retornoWebservice = new RetornoWebservice();

            if (lote == 0) retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Lote não informado." });
            if (notas.Count == 0) retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "RPS não informado." });
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            var xmlLoteRps = new StringBuilder();

            foreach (var nota in notas)
            {
                var xmlRps = GetXmlRps(nota, false, false);
                xmlLoteRps.Append(xmlRps);
                GravarRpsEmDisco(xmlRps, $"Rps-{nota.IdentificacaoRps.DataEmissao:yyyyMMdd}-{nota.IdentificacaoRps.Numero}.xml", nota.IdentificacaoRps.DataEmissao);
            }

            var xmlLote = new StringBuilder();
            xmlLote.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            xmlLote.Append($"<EnviarLoteRpsEnvio {GetNamespace()}>");
            xmlLote.Append($"<LoteRps Id=\"L{lote}\" xmlns=\"\">");
            xmlLote.Append($"<NumeroLote>{lote}</NumeroLote>");
            xmlLote.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            xmlLote.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            xmlLote.Append($"<QuantidadeRps>{notas.Count}</QuantidadeRps>");
            xmlLote.Append("<ListaRps>");
            xmlLote.Append(xmlLoteRps);
            xmlLote.Append("</ListaRps>");
            xmlLote.Append("</LoteRps>");
            xmlLote.Append("</EnviarLoteRpsEnvio>");
            retornoWebservice.XmlEnvio = xmlLote.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            retornoWebservice.XmlEnvio = XmlSigning.AssinarXmlTodos(retornoWebservice.XmlEnvio, "Rps", "InfRps", Certificado);
            retornoWebservice.XmlEnvio = XmlSigning.AssinarXml(retornoWebservice.XmlEnvio, "EnviarLoteRpsEnvio", "LoteRps", Certificado);

            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"lote-{lote}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.Enviar));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.Enviar))
                {
                    retornoWebservice.XmlRetorno = cliente.RecepcionarLoteRps(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }
            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"lote-{lote}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            var xmlRoot = xmlRet.ElementAnyNs("EnviarLoteRpsEnvioResponse");
            MensagemErro(retornoWebservice, xmlRoot, "EnviarLoteRpsResposta");
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            retornoWebservice.NumeroLote = xmlRoot.ElementAnyNs("NumeroLote")?.GetValue<string>() ?? string.Empty;
            retornoWebservice.DataLote = xmlRoot.ElementAnyNs("DataRecebimento")?.GetValue<DateTime>() ?? DateTime.MinValue;
            retornoWebservice.Protocolo = xmlRoot.ElementAnyNs("Protocolo")?.GetValue<string>() ?? string.Empty;
            retornoWebservice.Sucesso = !retornoWebservice.NumeroLote.IsEmpty();

            if (!retornoWebservice.Sucesso) return retornoWebservice;

            // ReSharper disable once SuggestVarOrType_SimpleTypes
            foreach (NotaFiscal nota in notas)
            {
                nota.NumeroLote = retornoWebservice.NumeroLote;
            }

            return retornoWebservice;
        }

        public override RetornoWebservice EnviarSincrono(int lote, NotaFiscalCollection notas)
        {
            throw new NotImplementedException("Função não implementada/suportada neste Provedor !");
        }

        public override RetornoWebservice CancelaNFSe(string codigoCancelamento, string numeroNFSe, string motivo, NotaFiscalCollection notas)
        {
            var retornoWebservice = new RetornoWebservice();

            if (numeroNFSe.IsEmpty() || codigoCancelamento.IsEmpty())
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Número da NFSe/Codigo de cancelamento não informado para cancelamento." });
                return retornoWebservice;
            }

            var loteBuilder = new StringBuilder();
            loteBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            loteBuilder.Append($"<CancelarNfseEnvio {GetNamespace()}>");
            loteBuilder.Append("<Pedido xmlns=\"\">");
            loteBuilder.Append($"<InfPedidoCancelamento Id=\"N{numeroNFSe}\">");
            loteBuilder.Append("<IdentificacaoNfse>");
            loteBuilder.Append($"<Numero>{numeroNFSe}</Numero>");
            loteBuilder.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            loteBuilder.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            loteBuilder.Append($"<CodigoMunicipio>{Configuracoes.PrestadorPadrao.Endereco.CodigoMunicipio}</CodigoMunicipio>");
            loteBuilder.Append("</IdentificacaoNfse>");
            loteBuilder.Append($"<CodigoCancelamento>{codigoCancelamento}</CodigoCancelamento>");
            loteBuilder.Append("</InfPedidoCancelamento>");
            loteBuilder.Append("</Pedido>");
            loteBuilder.Append("</CancelarNfseEnvio>");
            retornoWebservice.XmlEnvio = loteBuilder.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            retornoWebservice.XmlEnvio = XmlSigning.AssinarXml(retornoWebservice.XmlEnvio, "Pedido", "InfPedidoCancelamento", Certificado);
            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"CanNFSe-{numeroNFSe}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.CancelaNFSe));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.CancelaNFSe))
                {
                    retornoWebservice.XmlRetorno = cliente.CancelarNFSe(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }
            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"CanNFSe-{numeroNFSe}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            MensagemErro(retornoWebservice, xmlRet.Root, "CancelarNfseReposta");
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            var confirmacaoCancelamento = xmlRet.Root.ElementAnyNs("CancelarNfseReposta");
            retornoWebservice.DataLote = confirmacaoCancelamento.ElementAnyNs("DataHora")?.GetValue<DateTime>() ?? DateTime.MinValue;
            retornoWebservice.Sucesso = confirmacaoCancelamento.ElementAnyNs("Sucesso")?.GetValue<bool>() ?? false;

            // Se a nota fiscal cancelada existir na coleção de Notas Fiscais, atualiza seu status:
            var nota = notas.FirstOrDefault(x => x.IdentificacaoNFSe.Numero.Trim() == numeroNFSe);
            if (nota == null) return retornoWebservice;

            nota.Situacao = SituacaoNFSeRps.Cancelado;
            nota.Cancelamento.Pedido.CodigoCancelamento = codigoCancelamento;
            nota.Cancelamento.DataHora = confirmacaoCancelamento.ElementAnyNs("DataHora")?.GetValue<DateTime>() ?? DateTime.MinValue;
            nota.Cancelamento.MotivoCancelamento = motivo;

            return retornoWebservice;
        }

        public override RetornoWebservice ConsultarSituacao(int lote, string protocolo)
        {
            var retornoWebservice = new RetornoWebservice();

            // Monta mensagem de envio
            var loteBuilder = new StringBuilder();
            loteBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            loteBuilder.Append($"<ConsultarSituacaoLoteRpsEnvio {GetNamespace()}>");
            loteBuilder.Append("<Prestador xmlns=\"\">");
            loteBuilder.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            loteBuilder.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            loteBuilder.Append("</Prestador>");
            loteBuilder.Append($"<Protocolo xmlns=\"\">{protocolo}</Protocolo>");
            loteBuilder.Append("</ConsultarSituacaoLoteRpsEnvio>");
            retornoWebservice.XmlEnvio = loteBuilder.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"ConsultarSituacao-{DateTime.Now:yyyyMMddssfff}-{protocolo}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.ConsultarSituacao));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.ConsultarSituacao))
                {
                    retornoWebservice.XmlRetorno = cliente.ConsultarSituacaoLoteRps(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }

            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"ConsultarSituacao-{DateTime.Now:yyyyMMddssfff}-{lote}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            MensagemErro(retornoWebservice, xmlRet.Root, "ConsultarSituacaoLoteRpsResposta");

            retornoWebservice.NumeroLote = xmlRet.Root?.ElementAnyNs("ConsultarSituacaoLoteRpsResposta")?.ElementAnyNs("NumeroLote")?.GetValue<string>() ?? string.Empty;
            retornoWebservice.Situacao = xmlRet.Root?.ElementAnyNs("ConsultarSituacaoLoteRpsResposta")?.ElementAnyNs("Situacao")?.GetValue<string>() ?? string.Empty;
            retornoWebservice.Sucesso = !retornoWebservice.Erros.Any();
            return retornoWebservice;
        }

        public override RetornoWebservice ConsultarLoteRps(int lote, string protocolo, NotaFiscalCollection notas)
        {
            var retornoWebservice = new RetornoWebservice();

            var loteBuilder = new StringBuilder();
            loteBuilder.Append($"<ConsultarLoteRpsEnvio {GetNamespace()}>");
            loteBuilder.Append("<Prestador xmlns=\"\">");
            loteBuilder.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            loteBuilder.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            loteBuilder.Append("</Prestador>");
            loteBuilder.Append($"<Protocolo xmlns=\"\">{protocolo}</Protocolo>");
            loteBuilder.Append("</ConsultarLoteRpsEnvio>");
            retornoWebservice.XmlEnvio = loteBuilder.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"ConsultarLote-{DateTime.Now:yyyyMMddssfff}-{protocolo}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.ConsultarLoteRps));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.ConsultarLoteRps))
                {
                    retornoWebservice.XmlRetorno = cliente.ConsultarLoteRps(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }
            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"ConsultarLote-{DateTime.Now:yyyyMMddssfff}-{lote}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            MensagemErro(retornoWebservice, xmlRet.Root, "ConsultarLoteRpsResposta");
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            var retornoLote = xmlRet.Root.ElementAnyNs("ConsultarLoteRpsResposta");
            var listaNfse = retornoLote?.ElementAnyNs("ListaNfse");

            if (listaNfse == null)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Lista de NFSe não encontrada! (ListaNfse)" });
                return retornoWebservice;
            }

            retornoWebservice.Sucesso = true;

            foreach (var compNfse in listaNfse.ElementsAnyNs("CompNfse"))
            {
                var nfse = compNfse.ElementAnyNs("Nfse").ElementAnyNs("InfNfse");
                var numeroNFSe = nfse.ElementAnyNs("Numero")?.GetValue<string>() ?? string.Empty;
                var chaveNFSe = nfse.ElementAnyNs("CodigoVerificacao")?.GetValue<string>() ?? string.Empty;
                var dataNFSe = nfse.ElementAnyNs("DataEmissao")?.GetValue<DateTime>() ?? DateTime.Now;
                var numeroRps = nfse?.ElementAnyNs("IdentificacaoRps")?.ElementAnyNs("Numero")?.GetValue<string>() ?? string.Empty;
                GravarNFSeEmDisco(compNfse.AsString(true), $"NFSe-{numeroNFSe}-{chaveNFSe}-.xml", dataNFSe);

                var nota = notas.FirstOrDefault(x => x.IdentificacaoRps.Numero == numeroRps);
                if (nota == null)
                {
                    notas.Load(compNfse.ToString());
                }
                else
                {
                    nota.IdentificacaoNFSe.Numero = numeroNFSe;
                    nota.IdentificacaoNFSe.Chave = chaveNFSe;
                }
            }
            return retornoWebservice;
        }

        public override RetornoWebservice ConsultaNFSeRps(string numero, string serie, TipoRps tipo, NotaFiscalCollection notas)
        {
            var retornoWebservice = new RetornoWebservice();

            if (numero.IsEmpty())
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Número da NFSe não informado para a consulta." });
                return retornoWebservice;
            }

            var loteBuilder = new StringBuilder();
            loteBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            loteBuilder.Append($"<ConsultarNfsePorRpsEnvio {GetNamespace()}>");
            loteBuilder.Append("<IdentificacaoRps xmlns=\"\">");
            loteBuilder.Append($"<Numero>{numero}</Numero>");
            loteBuilder.Append($"<Serie>{serie}</Serie>");
            loteBuilder.Append($"<Tipo>{(int)tipo + 1}</Tipo>");
            loteBuilder.Append("</IdentificacaoRps>");
            loteBuilder.Append("<Prestador xmlns=\"\">");
            loteBuilder.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            loteBuilder.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            loteBuilder.Append("</Prestador>");
            loteBuilder.Append("</ConsultarNfsePorRpsEnvio>");
            retornoWebservice.XmlEnvio = loteBuilder.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"ConNotaRps-{numero}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.ConsultaNFSeRps));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.ConsultaNFSeRps))
                {
                    retornoWebservice.XmlRetorno = cliente.ConsultarNFSePorRps(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }
            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"ConNotaRps-{numero}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            MensagemErro(retornoWebservice, xmlRet.Root, "ConsultarNfseRpsResposta");
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            var compNfse = xmlRet.Root.ElementAnyNs("ConsultarNfseRpsResposta")?.ElementAnyNs("CompNfse");
            if (compNfse == null)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Nota Fiscal não encontrada! (CompNfse)" });
                return retornoWebservice;
            }

            // Carrega a nota fiscal na coleção de Notas Fiscais
            var nota = LoadXml(compNfse.AsString());
            notas.Add(nota);

            retornoWebservice.Sucesso = true;
            return retornoWebservice;
        }

        public override RetornoWebservice ConsultaNFSe(DateTime? inicio, DateTime? fim, string numeroNfse, int pagina, string cnpjTomador,
            string imTomador, string nomeInter, string cnpjInter, string imInter, string serie, NotaFiscalCollection notas)
        {
            var retornoWebservice = new RetornoWebservice();

            var loteBuilder = new StringBuilder();
            loteBuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            loteBuilder.Append($"<ConsultarNfseEnvio {GetNamespace()}>");
            loteBuilder.Append("<Prestador xmlns=\"\">");
            loteBuilder.Append($"<Cnpj>{Configuracoes.PrestadorPadrao.CpfCnpj.ZeroFill(14)}</Cnpj>");
            loteBuilder.Append($"<InscricaoMunicipal>{Configuracoes.PrestadorPadrao.InscricaoMunicipal}</InscricaoMunicipal>");
            loteBuilder.Append("</Prestador>");

            if (!numeroNfse.IsEmpty())
                loteBuilder.Append($"<NumeroNfse xmlns=\"\">{numeroNfse}</NumeroNfse>");

            if (inicio.HasValue && fim.HasValue)
            {
                loteBuilder.Append("<PeriodoEmissao xmlns=\"\">");
                loteBuilder.Append($"<DataInicial>{inicio:yyyy-MM-dd}</DataInicial>");
                loteBuilder.Append($"<DataFinal>{fim:yyyy-MM-dd}</DataFinal>");
                loteBuilder.Append("</PeriodoEmissao>");
            }

            if (!cnpjTomador.IsEmpty() || !imTomador.IsEmpty())
            {
                loteBuilder.Append("<Tomador xmlns=\"\">");
                loteBuilder.Append("<CpfCnpj>");
                loteBuilder.Append(cnpjTomador.IsCNPJ()
                    ? $"<Cnpj>{cnpjTomador.ZeroFill(14)}</Cnpj>"
                    : $"<Cpf>{cnpjTomador.ZeroFill(11)}</Cpf>");
                loteBuilder.Append("</CpfCnpj>");
                if (!imTomador.IsEmpty()) loteBuilder.Append($"<InscricaoMunicipal>{imTomador}</InscricaoMunicipal>");
                loteBuilder.Append("</Tomador>");
            }

            if (!nomeInter.IsEmpty() && !cnpjInter.IsEmpty())
            {
                loteBuilder.Append("<IntermediarioServico xmlns=\"\">");
                loteBuilder.Append($"<RazaoSocial>{nomeInter}</RazaoSocial>");
                loteBuilder.Append(cnpjInter.IsCNPJ()
                    ? $"<Cnpj>{cnpjInter.ZeroFill(14)}</Cnpj>"
                    : $"<Cpf>{cnpjInter.ZeroFill(11)}</Cpf>");
                loteBuilder.Append("</CpfCnpj>");
                if (!imInter.IsEmpty()) loteBuilder.Append($"<InscricaoMunicipal>{imInter}</InscricaoMunicipal>");
                loteBuilder.Append("</IntermediarioServico>");
            }

            loteBuilder.Append("</ConsultarNfseEnvio>");
            retornoWebservice.XmlEnvio = loteBuilder.ToString();

            if (Configuracoes.Geral.RetirarAcentos)
            {
                retornoWebservice.XmlEnvio = retornoWebservice.XmlEnvio.RemoveAccent();
            }

            GravarArquivoEmDisco(retornoWebservice.XmlEnvio, $"ConNota-{DateTime.Now:yyyyMMddssfff}-{numeroNfse}-env.xml");

            // Verifica Schema
            ValidarSchema(retornoWebservice, GetSchema(TipoUrl.ConsultaNFSe));
            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            // Recebe mensagem de retorno
            try
            {
                using (var cliente = GetClient(TipoUrl.ConsultaNFSe))
                {
                    retornoWebservice.XmlRetorno = cliente.ConsultarNFSe(GerarCabecalho(), retornoWebservice.XmlEnvio);
                }
            }
            catch (Exception ex)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = ex.Message });
                return retornoWebservice;
            }
            GravarArquivoEmDisco(retornoWebservice.XmlRetorno, $"ConNota-{DateTime.Now:yyyyMMddssfff}-{numeroNfse}-ret.xml");

            // Analisa mensagem de retorno
            var xmlRet = XDocument.Parse(retornoWebservice.XmlRetorno);
            MensagemErro(retornoWebservice, xmlRet.Root, "ConsultarNfseResposta");

            if (retornoWebservice.Erros.Any()) return retornoWebservice;

            var retornoLote = xmlRet.Root.ElementAnyNs("ConsultarNfseResposta");
            var listaNfse = retornoLote?.ElementAnyNs("ListaNfse");
            if (listaNfse == null)
            {
                retornoWebservice.Erros.Add(new Evento { Codigo = "0", Descricao = "Lista de NFSe não encontrada! (ListaNfse)" });
                return retornoWebservice;
            }

            foreach (var compNfse in listaNfse.ElementsAnyNs("CompNfse"))
            {
                // Carrega a nota fiscal na coleção de Notas Fiscais
                var nota = LoadXml(compNfse.AsString());
                notas.Add(nota);
            }

            retornoWebservice.Sucesso = true;

            return retornoWebservice;
        }

        #endregion Services

        #region Protected Methods

        protected override IABRASFClient GetClient(TipoUrl tipo)
        {
            switch (tipo)
            {
                case TipoUrl.CancelaNFSe: return new BethaServiceClient(this, tipo, null);
                case TipoUrl.ConsultaNFSeRps: return new BethaServiceClient(this, tipo, null);
                case TipoUrl.ConsultaNFSe: return new BethaServiceClient(this, tipo, null);
                default: return new BethaServiceClient(this, tipo);
            }
        }

        protected override string GetNamespace()
        {
            return "xmlns=\"http://www.betha.com.br/e-nota-contribuinte-ws\"";
        }

        protected override string GetSchema(TipoUrl tipo)
        {
            switch (tipo)
            {
                case TipoUrl.Enviar: return "servico_enviar_lote_rps_envio_v01.xsd";
                case TipoUrl.ConsultarSituacao: return "servico_consultar_situacao_lote_rps_envio_v01.xsd";
                case TipoUrl.ConsultarLoteRps: return "servico_consultar_lote_rps_envio_v01.xsd";
                case TipoUrl.ConsultaNFSeRps: return "servico_consultar_nfse_rps_envio_v01.xsd";
                case TipoUrl.ConsultaNFSe: return "servico_consultar_nfse_envio_v01.xsd";
                case TipoUrl.CancelaNFSe: return "servico_cancelar_nfse_envio_v01.xsd";
                default: throw new ArgumentOutOfRangeException(nameof(tipo), tipo, @"Valor incorreto ou serviço não suportado.");
            }
        }

        #endregion Protected Methods

        #endregion Methods
    }
}


text:
package com.infinities.keystone4j.jpa.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.infinities.keystone4j.common.Hints;
import com.infinities.keystone4j.jpa.AbstractDao;
import com.infinities.keystone4j.model.assignment.Project;

public class ProjectDao extends AbstractDao<Project> {

	public ProjectDao() {
		super(Project.class);
	}

	public Project findByName(String name, String domainid) {

		EntityManager em = getEntityManager();
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Project> cq = cb.createQuery(getEntityType());
		Root<Project> root = cq.from(getEntityType());
		Path<String> path = root.get("name");
		List<Predicate> predicates = Lists.newArrayList();
		Predicate namePredicate = cb.equal(path, name);
		predicates.add(namePredicate);
		if (!Strings.isNullOrEmpty(domainid)) {
			Predicate domainidPredicate = cb.equal(root.get("domain").get("id"), domainid);
			predicates.add(domainidPredicate);
		}
		cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
		cq.select(root);

		TypedQuery<Project> q = em.createQuery(cq);
		Project project = q.getSingleResult();
		return project;
	}

	public List<Project> listProjectsInDomain(String domainid) {
		EntityManager em = getEntityManager();

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Project> cq = cb.createQuery(getEntityType());
		Root<Project> root = cq.from(getEntityType());
		List<Predicate> predicates = Lists.newArrayList();
		Predicate domainidPredicate = cb.equal(root.get("domain").get("id"), domainid);
		predicates.add(domainidPredicate);
		cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
		cq.select(root);

		TypedQuery<Project> q = em.createQuery(cq);
		List<Project> projects = q.getResultList();
		return projects;
	}

	public List<Project> listProject(Hints hints) throws SecurityException, IllegalArgumentException,
			IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		return filterLimitQuery(Project.class, hints);
	}

	public List<Project> listProjectsInDomains(Set<String> domainIds) {
		EntityManager em = getEntityManager();

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Project> cq = cb.createQuery(getEntityType());
		Root<Project> root = cq.from(getEntityType());
		List<Predicate> predicates = Lists.newArrayList();
		Predicate domainidPredicate = root.get("domain").get("id").in(domainIds);
		predicates.add(domainidPredicate);
		cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
		cq.select(root);

		TypedQuery<Project> q = em.createQuery(cq);
		List<Project> projects = q.getResultList();
		return projects;
	}

	public List<Project> listProjectsInProjectIds(Set<String> ids) {
		EntityManager em = getEntityManager();

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Project> cq = cb.createQuery(getEntityType());
		Root<Project> root = cq.from(getEntityType());
		List<Predicate> predicates = Lists.newArrayList();
		Predicate idPredicate = root.get("id").in(ids);
		predicates.add(idPredicate);
		cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
		cq.select(root);

		TypedQuery<Project> q = em.createQuery(cq);
		List<Project> projects = q.getResultList();
		return projects;
	}

	public List<Project> getChildren(List<String> projectIds) {
		EntityManager em = getEntityManager();

		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Project> cq = cb.createQuery(getEntityType());
		Root<Project> root = cq.from(getEntityType());
		List<Predicate> predicates = Lists.newArrayList();
		Predicate idPredicate = root.get("parent").get("id").in(projectIds);
		predicates.add(idPredicate);
		cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
		cq.select(root);

		TypedQuery<Project> q = em.createQuery(cq);
		List<Project> projects = q.getResultList();
		return projects;
	}
}


text:
package ca.eandb.jmist.util;

import java.util.Arrays;

import ca.eandb.jmist.math.MathUtil;

/**
 * Static utility methods for working with arrays.
 * @author Brad Kimmel
 */
public final class ArrayUtil {

  /**
   * Resets all elements of the given array to zero.
   * @param array The array of doubles to zero the values of.
   *     This may be null, in which case nothing is done.
   * @return A reference to array.
   */
  public static double[] reset(double[] array) {
    if (array != null) {
      Arrays.fill(array, 0.0);
    }
    return array;
  }

  /**
   * Resets all elements of the given array to zero.
   * @param array The array of ints to zero the values of.
   *     This may be null, in which case nothing is done.
   * @return A reference to array.
   */
  public static int[] reset(int[] array) {
    if (array != null) {
      Arrays.fill(array, 0);
    }
    return array;
  }

  /**
   * Returns an array of zeros of the specified length.
   * @param array The array of doubles to zero and return.  If
   *     null, a new array will be created.  Otherwise, all
   *     elements will be set to zero and this array will be returned.
   * @param length The length of the array to return.
   * @return An array of the specified length that is all zeros.
   * @throws IllegalArgumentException if array is not
   *     null and array.length != length.
   */
  public static double[] initialize(double[] array, int length) {
    if (array == null) {
      return new double[length];
    } else if (array.length != length) {
      throw new IllegalArgumentException(String.format(
          "Invalid array length: expected %d but got %d.", length,
          array.length));
    }
    return ArrayUtil.reset(array);
  }

  /**
   * Returns an array of zeros of the specified length.
   * @param array The array of ints to zero and return.  If
   *     null, a new array will be created.  Otherwise, all
   *     elements will be set to zero and this array will be returned.
   * @param length The length of the array to return.
   * @return An array of the specified length that is all zeros.
   * @throws IllegalArgumentException if array is not
   *     null and array.length != length.
   */
  public static int[] initialize(int[] array, int length) {
    if (array == null) {
      return new int[length];
    } else if (array.length != length) {
      throw new IllegalArgumentException(String.format(
          "Invalid array length: expected %d but got %d.", length,
          array.length));
    }
    return ArrayUtil.reset(array);
  }

  /**
   * Returns an array of doubles, all equal to the specified
   * value, of the specified length.
   * @param array The array of doubles to zero and return.  If
   *     null, a new array will be created.  Otherwise, all
   *     elements will be set to zero and this array will be returned.
   * @param length The length of the array to return.
   * @param value The value to initialize each element of the array to.
   * @return An array of the specified length that is all zeros.
   * @throws IllegalArgumentException if array is not
   *     null and array.length != length.
   */
  public static double[] initialize(double[] array, int length, double value) {
    if (array == null) {
      array = new double[length];
    } else if (array.length != length) {
      throw new IllegalArgumentException(String.format(
          "Invalid array length: expected %d but got %d.", length,
          array.length));
    }
    return ArrayUtil.setAll(array, value);
  }

  /**
   * Returns an array of ints, all equal to the specified
   * value, of the specified length.
   * @param array The array of ints to zero and return.  If
   *     null, a new array will be created.  Otherwise, all
   *     elements will be set to zero and this array will be returned.
   * @param length The length of the array to return.
   * @param value The value to initialize each element of the array to.
   * @return An array of the specified length that is all zeros.
   * @throws IllegalArgumentException if array is not
   *     null and array.length != length.
   */
  public static int[] initialize(int[] array, int length, int value) {
    if (array == null) {
      array = new int[length];
    } else if (array.length != length) {
      throw new IllegalArgumentException(String.format(
          "Invalid array length: expected %d but got %d.", length,
          array.length));
    }
    return ArrayUtil.setAll(array, value);
  }

  /**
   * Populates a contiguous range within an array of doubles
   * with the values from another array of doubles.
   * @param array The array of doubles to populate.
   * @param start The index into array of the first element to
   *     populate.
   * @param values An array of doubles to populate part of
   *     array with.
   * @return A reference to array.
   */
  public static double[] setRange(double[] array, int start, double[] values) {
    assert(array.length <= start + values.length);
    for (int i = 0, j = start; i < values.length; i++, j++) {
      array[j] = values[i];
    }
    return array;
  }

  /**
   * Copies a range of values from one array into another array.
   * @param target The array of doubles to receive the values.
   * @param targetStart The index into target at which to start
   *     copying values into (this array will be modified).
   * @param source The array of doubles from which to copy.
   * @param sourceStart The index into source at which to start
   *     copying values.
   * @param length The number of values to copy from source to
   *     target.
   * @return A reference to target.
   */
  public static double[] setRange(double[] target, int targetStart,
      double[] source, int sourceStart, int length) {
    assert(target.length <= targetStart + length);
    assert(source.length <= sourceStart + length);
    for (int i = sourceStart, j = targetStart, n = 0; n < length; i++, j++, n++) {
      target[j] = source[i];
    }
    return target;
  }

  /**
   * Sets all of the values in the specified array of doubles to
   * the same value.
   * @param array The array of doubles the elements of which are
   *     to be set (the elements of this array will be modified).
   * @param value The value to set each element of array to.
   * @return A reference to array.
   */
  public static double[] setAll(double[] array, double value) {
    Arrays.fill(array, value);
    return array;
  }

  /**
   * Sets all of the values in the specified array of ints to
   * the same value.
   * @param array The array of ints the elements of which are to
   *     be set (the elements of this array will be modified).
   * @param value The value to set each element of array to.
   * @return A reference to array.
   */
  public static int[] setAll(int[] array, int value) {
    Arrays.fill(array, value);
    return array;
  }

  /**
   * Fills an array with values uniformly within a specified range.
   * @param array The array to populate.
   * @param first The value to assign to the first element of
   *     array.
   * @param last The value to assign to the last element of the
   *     array.
   * @return A reference to array, populated with the values
   *     array[i] == first + (i / (array.length - 1)) * last,
   *     for 0 <= i < array.length.
   */
  public static double[] fillRange(double[] array, double first, double last) {
    if (array == null) {
      throw new IllegalArgumentException("array is null");
    }

    for (int i = 0; i < array.length; i++) {
      double t = i / (double) (array.length - 1);
      array[i] = first + t * (last - first);
    }
    return array;
  }

  /**
   * Fills an array with each value within a specified range.
   * @param array The array to populate (must be null or of length
   *     equal to max(0, end - start)).
   * @param start The value to assign to the first element of the
   *     array.
   * @param end One more than the value to assign to the last element of the
   *     array.
   * @return A reference to array, populated with the values
   *     start (inclusive) through end (exclusive).
   * @throws IllegalArgumentException if array != null and
   *     array.length != max(0, end - start).
   */
  public static int[] fillRange(int[] array, int start, int end) {
    return fillRange(array, start, end, 1);
  }

  /**
   * Fills an array with each value within a specified range.
   * @param array The array to populate (must be null or of length
   *     equal to max(0, ceil((end - start) / step))).
   * @param start The value to assign to the first element of the
   *     array.
   * @param end One more than the value to assign to the last element of the
   *     array.
   * @param step The difference between successive elements in the array.
   * @return A reference to array, populated with the values
   *     start (inclusive) through end (exclusive).
   * @throws IllegalArgumentException if array != null and
   *     array.length != max(0, ceil((end - start) / step)).
   */
  public static int[] fillRange(int[] array, int start, int end, int step) {
    if (step == 0) {
      throw new IllegalArgumentException("step must be non-zero.");
    }

    int length = Math.max(0, MathUtil.divRoundUp(end - start, step));
    array = ArrayUtil.initialize(array, length);
    for (int i = 0, value = start; i < array.length; i++, value += step) {
      array[i] = value;
    }
    return array;
  }

  /**
   * Creates a new array populated with values spaced uniformly in the
   * specified range.
   * @param first The value to assign to the first element of the array.
   * @param last The value to assign to the last element of the array.
   * @param length The length of the array.
   * @return An array of the given length, populated with the values
   *     array[i] == first + (i / (length - 1)) * last, for
   *     0 <= i < length.
   */
  public static double[] range(double first, double last, int length) {
    return ArrayUtil.fillRange(new double[length], first, last);
  }

  /**
   * Creates a new array populated with values in the specified range.
   * @param start The value to assign to the first element of the array.
   * @param end One more than the value to assign to the last element of the
   *     array.
   * @return An array of the length end - start, populated with the
   *     values from start to end.  If
   *     end <= start, an empty array is returned.
   */
  public static int[] range(int start, int end) {
    return range(start, end, 1);
  }

  /**
   * Creates a new array populated with values in the specified range.
   * @param start The value to assign to the first element of the array.
   * @param end One more than the value to assign to the last element of the
   *     array.
   * @param step The difference between successive elements.
   * @return An array of the values from start (inclusive) to
   *     end (exclusive) with successive values differing by
   *     step.  If (end - start) * step <= 0, an
   *     empty array is returned.
   * @throws IllegalArgumentException if step == 0.
   */
  public static int[] range(int start, int end, int step) {
    return ArrayUtil.fillRange((int[]) null, start, end, step);
  }

  /**
   * Swaps two elements of an array.
   * @param arr The array whose elements to swap.
   * @param a The index of the first element.
   * @param b The index of the second element.
   */
  public static void swap(int[] arr, int a, int b) {
    int temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  }

  /**
   * Swaps two elements of an array.
   * @param arr The array whose elements to swap.
   * @param a The index of the first element.
   * @param b The index of the second element.
   */
  public static void swap(float[] arr, int a, int b) {
    float temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  }

  /**
   * Swaps two elements of an array.
   * @param arr The array whose elements to swap.
   * @param a The index of the first element.
   * @param b The index of the second element.
   */
  public static void swap(double[] arr, int a, int b) {
    double temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
  }

  /**
   * Default constructor.  This constructor is private because this class
   * cannot be instantiated.
   */
  private ArrayUtil() {
    /* do nothing */
  }

}


text:
package org.rabix.bindings.draft3.processor.callback;

import java.io.File;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Set;

import org.rabix.bindings.draft3.bean.Draft3Job;
import org.rabix.bindings.draft3.processor.Draft3PortProcessor;
import org.rabix.bindings.draft3.processor.Draft3PortProcessorException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.bindings.model.FileValue;
import org.rabix.bindings.transformer.FileTransformer;

public class Draft3PortProcessorHelper {

  private final Draft3Job draft3Job;
  private final Draft3PortProcessor portProcessor;

  public Draft3PortProcessorHelper(Draft3Job draft3Job) {
    this.draft3Job = draft3Job;
    this.portProcessor = new Draft3PortProcessor(draft3Job);
  }

  public Set<FileValue> getInputFiles(Map<String, Object> inputs, FilePathMapper fileMapper, Map<String, Object> config) throws Draft3PortProcessorException {
    if (fileMapper != null) {
      Draft3FilePathMapProcessorCallback fileMapperCallback = new Draft3FilePathMapProcessorCallback(fileMapper, config);
      inputs = portProcessor.processInputs(inputs, fileMapperCallback);
    }

    Draft3FileValueProcessorCallback callback = new Draft3FileValueProcessorCallback(draft3Job, null, true);
    try {
      portProcessor.processInputs(inputs, callback);
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to get input files.", e);
    }
    return callback.getFileValues();
  }

  public Set<FileValue> getOutputFiles(Map<String, Object> outputs, Set<String> visiblePorts) throws Draft3PortProcessorException {
    Draft3FileValueProcessorCallback callback = new Draft3FileValueProcessorCallback(draft3Job, visiblePorts, false);
    try {
      portProcessor.processOutputs(outputs, callback);
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to get output files.", e);
    }
    return callback.getFileValues();
  }

  public Map<String, Object> updateInputFiles(Map<String, Object> inputs, FileTransformer fileTransformer) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3FileValueUpdateProcessorCallback(fileTransformer));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> updateOutputFiles(Map<String, Object> outputs, FileTransformer fileTransformer) throws Draft3PortProcessorException {
    try {
      return portProcessor.processOutputs(outputs, new Draft3FileValueUpdateProcessorCallback(fileTransformer));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> setFileSize(Map<String, Object> inputs) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3FileSizeProcessorCallback());
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input file size", e);
    }
  }

  public Map<String, Object> loadInputContents(Map<String, Object> inputs) throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3LoadContentsPortProcessorCallback());
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to load input contents.", e);
    }
  }
  public Map<String, Object> stageInputFiles(Map<String, Object> inputs, File workingDir)
      throws Draft3PortProcessorException {
    try {
      return portProcessor.processInputs(inputs, new Draft3StageInputProcessorCallback(workingDir));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to stage inputs.", e);
    }
  }

  public Map<String, Object> setFileProperties(Map<String, Object> inputs) throws Draft3PortProcessorException {
    try {
      String appFileLocation = this.draft3Job.getApp().getAppFileLocation();
      return portProcessor.processInputs(inputs, new Draft3FilePropertiesProcessorCallback(Paths.get(appFileLocation == null ? "." : appFileLocation).toAbsolutePath().normalize()));
    } catch (Draft3PortProcessorException e) {
      throw new Draft3PortProcessorException("Failed to set input properties.", e);
    }
  }
}


text:
<?php

/**
 * Validates a url
 *
 * @package    Simplecart
 * @subpackage Validate
 * @author     spekkionu
 * @license    New BSD http://www.opensource.org/licenses/bsd-license.php
 */
class Validate_Url extends Zend_Validate_Abstract
{

    const INVALID = 'urlInvalid';

    protected $_messageTemplates = array(
      self::INVALID => "'%value%' is not a valid URL.",
    );

    /**
     * Validates the Url
     * @param string $value
     * @return bool
     */
    public function isValid($value)
    {
        $valueString = (string) $value;
        $this->_setValue($valueString);

        if (!Zend_Uri::check($value)) {
            $this->_error(self::INVALID);
            return false;
        }
        return true;
    }
}


text:
from __future__ import absolute_import, print_function

from requests.exceptions import RequestException
from sentry import http
from sentry.utils import json

from .constants import API_DOMAIN

class GitHubApiError(Exception):
    def __init__(self, message='', status=0):
        super(GitHubApiError, self).__init__(message)
        self.status = status

class GitHubClient(object):
    def __init__(self, client_id, client_secret):
        self.client_id = client_id
        self.client_secret = client_secret
        self.http = http.build_session()

    def _request(self, path, access_token):
        params = {
            'client_id': self.client_id,
            'client_secret': self.client_secret,
        }

        headers = {
            'Authorization': 'token {0}'.format(access_token),
        }

        try:
            req = self.http.get('https://{0}/{1}'.format(API_DOMAIN, path.lstrip('/')),
                params=params,
                headers=headers,
            )
        except RequestException as e:
            raise GitHubApiError(unicode(e), status=getattr(e, 'status_code', 0))
        if req.status_code < 200 or req.status_code >= 300:
            raise GitHubApiError(req.content, status=req.status_code)
        return json.loads(req.content)

    def get_org_list(self, access_token):
        return self._request('/user/orgs', access_token)

    def get_user(self, access_token):
        return self._request('/user', access_token)

    def get_user_emails(self, access_token):
        return self._request('/user/emails', access_token)

    def is_org_member(self, access_token, org_id):
        org_list = self.get_org_list(access_token)
        org_id = str(org_id)
        for o in org_list:
            if str(o['id']) == org_id:
                return True
        return False


text:
var DashboardItem = {
  Context: null,
  itemSettings: null,
  Init: function(dashboardItemParam, targetElement, teamCityApi, dataStore, context) {
    this.itemSettings = dashboardItemParam;
    this.$targetElement = $(targetElement);
    this.teamCityApi = teamCityApi;
    this.dataStore = dataStore;
    this.Context = context;
    return this;
  },
  InitDashboardItemEventListeners: function($dashboardItemElement) {
    var that = this,
      resizerButtonsFadeTime = 500;
    $dashboardItemElement.hover(function(e) {
      e.stopPropagation();
      var $lowestTarget = $(this).hasClass("grid-item") ? $(this) : $(this).parents(".grid-item").first();
      $lowestTarget.children(".resizer-buttons").stop().animate({ opacity: 1 }, resizerButtonsFadeTime);
      $lowestTarget.parents(".grid-item").children(".resizer-buttons").stop().animate({ opacity: 0 }, resizerButtonsFadeTime);
    }, function(e) {
      var $lowestTarget = $(this).hasClass("grid-item") ? $(this) : $(this).parents(".grid-item").first();
      $lowestTarget.children(".resizer-buttons").stop().animate({ opacity: 0 }, resizerButtonsFadeTime);
      $lowestTarget.parents(".grid-item").first().children(".resizer-buttons").stop().animate({ opacity: 1 }, resizerButtonsFadeTime);
    });

    $dashboardItemElement.children(".resizer-buttons").children(".resizer-button").on("click", function() {
      that.ResizeDashboardItem($(this));
    });
  },
  SetItemWidth: function(dasboardItem) {
    dasboardItem.width = dasboardItem.width ? dasboardItem.width : "large";
    if (dasboardItem.width === "small") {
      dasboardItem.colSize = "col-xs-4 small";
    } else if (dasboardItem.width === "medium") {
      dasboardItem.colSize = "col-xs-6 medium";
    } else if (dasboardItem.width === "large") {
      dasboardItem.colSize = "col-xs-12 large";
    }

    return dasboardItem;
  },
  ResizeDashboardItem: function($clickedResizer) {
    var that = this,
      $thisGridItem = $clickedResizer.parents(".grid-item").first(),
      thisGridItemWidthBefore = $thisGridItem.outerWidth();

    $thisGridItem.removeClass("small")
      .removeClass("medium")
      .removeClass("large")
      .removeClass("col-xs-12")
      .removeClass("col-xs-6")
      .removeClass("col-xs-4");
    if ($clickedResizer.hasClass("small-resizer-button")) {
      $thisGridItem.addClass("small").addClass("col-xs-4");
      that.itemSettings.width = "small";
    } else if ($clickedResizer.hasClass("med-resizer-button")) {
      $thisGridItem.addClass("medium").addClass("col-xs-6");
      that.itemSettings.width = "medium";
    } else if ($clickedResizer.hasClass("large-resizer-button")) {
      $thisGridItem.addClass("large").addClass("col-xs-12");
      that.itemSettings.width = "large";
    }

    that.SaveSize();
    var thisGridItemWidthAfter = $thisGridItem.outerWidth();

    that.ReversePackery($("#dashboard-grid-container").find(".grid-item-contents"));
    var $packeryGrid = $("#dashboard-grid-container").packery();

    $thisGridItem.addClass("animating-grid-item");
    $thisGridItem.css("width", thisGridItemWidthBefore).animate({ width: thisGridItemWidthAfter }, 500, "easeOutExpo", function() {
      $thisGridItem.css("width", "");
    });

    $packeryGrid.on("layoutComplete", function() {
      if ($(event.currentTarget).hasClass("animating-grid-item")) {
        $(event.currentTarget).removeClass("animating-grid-item");
        $packeryGrid.off("layoutComplete");
        var originalScrollTop = $(window).scrollTop();
        var topOfLaidOutItem = $thisGridItem.offset().top;
        var bottomOfLaidOutItem = topOfLaidOutItem + $thisGridItem.outerHeight();
        var windowHeight = $(window).height();
        var newScrollTop = originalScrollTop >= topOfLaidOutItem ? topOfLaidOutItem : bottomOfLaidOutItem - (originalScrollTop + windowHeight);
        console.log(newScrollTop);
        $("body").animate({
          scrollTop: newScrollTop
        }, 500, "easeOutExpo");
      }
    });
  },
  ReversePackery: function(listOfContainers) {
    for (var i = listOfContainers.length - 1; i > -1; i--) {
      $(listOfContainers[i]).packery("layout");
    }
  }
}


text:
<?php

namespace Modules\Formbuilder\Entities;

use DB;
use Illuminate\Database\Eloquent\Model;
use Log;
use Modules\Formbuilder\Events\FormbuilderEvent;
use Modules\Formbuilder\Shortcodes\FormbuilderShortcode;

class FormsSubmits extends Model
{
    protected $table = 'formbuilder__form_submits';
    protected $fillable = ['form_id', 'locale', 'client_ip'];
    public $unSaveField = ['_token', 'formbuilder_id'];

    public function formSubmitData()
    {
        return $this->hasMany('Modules\Formbuilder\Entities\FormSubmitData', 'submit_id', 'id');
    }

    public static function submitData($data, $dataFiles)
    {
        $bResult = false;
        $formId = array_get($data, 'formbuilder_id');
        $locale = array_get($data, 'formbuilder_locale');
        $clientIp = array_get($data, 'client_ip');
        $formBuilder = Forms::find($formId);
        if ($formBuilder->id) {
            DB::beginTransaction();
            try {
                $formSubmit = new self();
                $formSubmit->form_id    = $formId;
                $formSubmit->locale    = $locale;
                $formSubmit->client_ip    = $clientIp;
                $formSubmit->save();
                $formSubmitId = $formSubmit->id;
                $order = 0;
                foreach ($data as $key => $value) {
                    if (!in_array($key, $formSubmit->unSaveField)) {
                        $formSubmitData = new FormSubmitData();
                        $formSubmitData->submit_id = $formSubmitId;
                        $formSubmitData->field_name = $key;
                        $formSubmitData->field_value = $value;
                        $formSubmitData->field_order = $order;
                        $formSubmitData->save();
                        ++$order;
                        FormbuilderShortcode::registerSubmitShortcode($key, $value);
                    }
                }
                foreach ($dataFiles as $key => $value) {
                    if (!in_array($key, $formSubmit->unSaveField)) {
                        $formSubmitData = new FormSubmitData();
                        $formSubmitData->submit_id = $formSubmitId;
                        $formSubmitData->field_name = $key;
                        $formSubmitData->field_value = $value;
                        $formSubmitData->field_order = $order;
                        $formSubmitData->is_file = 1;
                        $formSubmitData->save();
                        ++$order;
                        FormbuilderShortcode::registerSubmitShortcode($key, $value);
                    }
                }
                DB::commit();
                $formMail = new FormMail();
                $formMail->sendMail($formSubmitId, $locale);
                event(new FormbuilderEvent('submit_form', $data));
                $bResult = true;
            } catch (\Exception $ex) {
                Log::info($ex);
                DB::rollback();
            }
        }

        return $bResult;
    }
}


text:
/*
	¹®ÀÚ¿ Á¶ÀÛ Å¬·¡½º¡¡~stringx.h~		Ver. [2000/02/11]
*/
#ifndef	__STRINGX_H
#define	__STRINGX_H

#pragma warning(disable:4786)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string>
#include <list>
#include <map>
#include <stack>

using namespace std;

class stringx{
  public:
	typedef	string::size_type	size_type;

  protected:
	string		str;

// ¹®ÀÚ¿ Á¶ÀÛ ½ºÅÂƽ ·çƾ
  public:
	static size_type	strlen(char* s);

// string Á¶ÀÛ ·çƾ
  public:
	void		set(string s){ str=s; }
	string		get(){ return str; }
	stringx&	operator=(string& s){ set(s); return *this; }
	stringx&	operator=(char* s){ set(s); return *this; }
	string		operator()(){ return get(); }
				operator string(){ return get(); }

	string		substr(size_type pos, size_type n);
	string		copy(size_type pos, size_type n){ return substr(pos, n); }
	string		cut(size_type pos, size_type n);
	string		left(size_type pos){ return substr(0, pos); }
	string		right(size_type pos){ return substr(pos+1, str.size() -pos-1); }
//	void		fromdigit();
	string		tolower();
	string		toupper();
	size_type	lastdelimiter(char* s);
//	size_type	find(string s, size_type pos=0);
//	size_type	search(string s, size_type pos=0){ return find(s, pos); }
//	void		replace();
	long		tolong(){ return atol(str.c_str()); }
	double		todouble(){ return atof(str.c_str()); }
};

#endif


text:
package com.example.xcoredemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class FragmentDemoActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstatnceState) {
		super.onCreate(savedInstatnceState);
		setContentView(R.layout.activity_demo_fragment);
	}

}