text:
// Copyright 2012 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <stdlib.h>
#include <wchar.h>

#include "src/v8.h"

#include "src/api-inl.h"
#include "src/compiler.h"
#include "src/disasm.h"
#include "src/heap/factory.h"
#include "src/interpreter/interpreter.h"
#include "src/objects-inl.h"
#include "test/cctest/cctest.h"

namespace v8 {
namespace internal {

static Handle<Object> GetGlobalProperty(const char* name) {
  Isolate* isolate = CcTest::i_isolate();
  return JSReceiver::GetProperty(isolate, isolate->global_object(), name)
      .ToHandleChecked();
}

static void SetGlobalProperty(const char* name, Object* value) {
  Isolate* isolate = CcTest::i_isolate();
  Handle<Object> object(value, isolate);
  Handle<String> internalized_name =
      isolate->factory()->InternalizeUtf8String(name);
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Runtime::SetObjectProperty(isolate, global, internalized_name, object,
                             LanguageMode::kSloppy, StoreOrigin::kMaybeKeyed)
      .Check();
}

static Handle<JSFunction> Compile(const char* source) {
  Isolate* isolate = CcTest::i_isolate();
  Handle<String> source_code = isolate->factory()->NewStringFromUtf8(
      CStrVector(source)).ToHandleChecked();
  Handle<SharedFunctionInfo> shared =
      Compiler::GetSharedFunctionInfoForScript(
          isolate, source_code, Compiler::ScriptDetails(),
          v8::ScriptOriginOptions(), nullptr, nullptr,
          v8::ScriptCompiler::kNoCompileOptions,
          ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE)
          .ToHandleChecked();
  return isolate->factory()->NewFunctionFromSharedFunctionInfo(
      shared, isolate->native_context());
}

static double Inc(Isolate* isolate, int x) {
  const char* source = "result = %d + 1;";
  EmbeddedVector<char, 512> buffer;
  SNPrintF(buffer, source, x);

  Handle<JSFunction> fun = Compile(buffer.start());
  if (fun.is_null()) return -1;

  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
  return GetGlobalProperty("result")->Number();
}

TEST(Inc) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  CHECK_EQ(4.0, Inc(CcTest::i_isolate(), 3));
}

static double Add(Isolate* isolate, int x, int y) {
  Handle<JSFunction> fun = Compile("result = x + y;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
  SetGlobalProperty("y", Smi::FromInt(y));
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
  return GetGlobalProperty("result")->Number();
}

TEST(Add) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  CHECK_EQ(5.0, Add(CcTest::i_isolate(), 2, 3));
}

static double Abs(Isolate* isolate, int x) {
  Handle<JSFunction> fun = Compile("if (x < 0) result = -x; else result = x;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("x", Smi::FromInt(x));
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
  return GetGlobalProperty("result")->Number();
}

TEST(Abs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  CHECK_EQ(3.0, Abs(CcTest::i_isolate(), -3));
}

static double Sum(Isolate* isolate, int n) {
  Handle<JSFunction> fun =
      Compile("s = 0; while (n > 0) { s += n; n -= 1; }; result = s;");
  if (fun.is_null()) return -1;

  SetGlobalProperty("n", Smi::FromInt(n));
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Execution::Call(isolate, fun, global, 0, nullptr).Check();
  return GetGlobalProperty("result")->Number();
}

TEST(Sum) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  CHECK_EQ(5050.0, Sum(CcTest::i_isolate(), 100));
}

TEST(Print) {
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> context = CcTest::NewContext(PRINT_EXTENSION);
  v8::Context::Scope context_scope(context);
  const char* source = "for (n = 0; n < 100; ++n) print(n, 1, 2);";
  Handle<JSFunction> fun = Compile(source);
  if (fun.is_null()) return;
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
}

// The following test method stems from my coding efforts today. It
// tests all the functionality I have added to the compiler today
TEST(Stuff) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  const char* source =
    "r = 0;\n"
    "a = new Object;\n"
    "if (a == a) r+=1;\n"  // 1
    "if (a != new Object()) r+=2;\n"  // 2
    "a.x = 42;\n"
    "if (a.x == 42) r+=4;\n"  // 4
    "function foo() { var x = 87; return x; }\n"
    "if (foo() == 87) r+=8;\n"  // 8
    "function bar() { var x; x = 99; return x; }\n"
    "if (bar() == 99) r+=16;\n"  // 16
    "function baz() { var x = 1, y, z = 2; y = 3; return x + y + z; }\n"
    "if (baz() == 6) r+=32;\n"  // 32
    "function Cons0() { this.x = 42; this.y = 87; }\n"
    "if (new Cons0().x == 42) r+=64;\n"  // 64
    "if (new Cons0().y == 87) r+=128;\n"  // 128
    "function Cons2(x, y) { this.sum = x + y; }\n"
    "if (new Cons2(3,4).sum == 7) r+=256;";  // 256

  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
  Handle<JSObject> global(CcTest::i_isolate()->context()->global_object(),
                          fun->GetIsolate());
  Execution::Call(CcTest::i_isolate(), fun, global, 0, nullptr).Check();
  CHECK_EQ(511.0, GetGlobalProperty("r")->Number());
}

TEST(UncaughtThrow) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());

  const char* source = "throw 42;";
  Handle<JSFunction> fun = Compile(source);
  CHECK(!fun.is_null());
  Isolate* isolate = fun->GetIsolate();
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  CHECK(Execution::Call(isolate, fun, global, 0, nullptr).is_null());
  CHECK_EQ(42.0, isolate->pending_exception()->Number());
}

// Tests calling a builtin function from C/C++ code, and the builtin function
// performs GC. It creates a stack frame looks like following:
//   | C (PerformGC) |
//   |   JS-to-C     |
//   |      JS       |
//   |   C-to-JS     |
TEST(C2JSFrames) {
  FLAG_expose_gc = true;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> context =
    CcTest::NewContext(PRINT_EXTENSION | GC_EXTENSION);
  v8::Context::Scope context_scope(context);

  const char* source = "function foo(a) { gc(), print(a); }";

  Handle<JSFunction> fun0 = Compile(source);
  CHECK(!fun0.is_null());
  Isolate* isolate = fun0->GetIsolate();

  // Run the generated code to populate the global object with 'foo'.
  Handle<JSObject> global(isolate->context()->global_object(), isolate);
  Execution::Call(isolate, fun0, global, 0, nullptr).Check();

  Handle<Object> fun1 =
      JSReceiver::GetProperty(isolate, isolate->global_object(), "foo")
          .ToHandleChecked();
  CHECK(fun1->IsJSFunction());

  Handle<Object> argv[] = {isolate->factory()->InternalizeOneByteString(
      STATIC_CHAR_VECTOR("hello"))};
  Execution::Call(isolate,
                  Handle<JSFunction>::cast(fun1),
                  global,
                  arraysize(argv),
                  argv).Check();
}

// Regression 236. Calling InitLineEnds on a Script with undefined
// source resulted in crash.
TEST(Regression236) {
  CcTest::InitializeVM();
  Isolate* isolate = CcTest::i_isolate();
  Factory* factory = isolate->factory();
  v8::HandleScope scope(CcTest::isolate());

  Handle<Script> script = factory->NewScript(factory->empty_string());
  script->set_source(ReadOnlyRoots(CcTest::heap()).undefined_value());
  CHECK_EQ(-1, Script::GetLineNumber(script, 0));
  CHECK_EQ(-1, Script::GetLineNumber(script, 100));
  CHECK_EQ(-1, Script::GetLineNumber(script, -1));
}

TEST(GetScriptLineNumber) {
  LocalContext context;
  v8::HandleScope scope(CcTest::isolate());
  v8::ScriptOrigin origin = v8::ScriptOrigin(v8_str("test"));
  const char function_f[] = "function f() {}";
  const int max_rows = 1000;
  const int buffer_size = max_rows + sizeof(function_f);
  ScopedVector<char> buffer(buffer_size);
  memset(buffer.start(), '\n', buffer_size - 1);
  buffer[buffer_size - 1] = '\0';

  for (int i = 0; i < max_rows; ++i) {
    if (i > 0)
      buffer[i - 1] = '\n';
    MemCopy(&buffer[i], function_f, sizeof(function_f) - 1);
    v8::Local<v8::String> script_body = v8_str(buffer.start());
    v8::Script::Compile(context.local(), script_body, &origin)
        .ToLocalChecked()
        ->Run(context.local())
        .ToLocalChecked();
    v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
        context->Global()->Get(context.local(), v8_str("f")).ToLocalChecked());
    CHECK_EQ(i, f->GetScriptLineNumber());
  }
}

TEST(FeedbackVectorPreservedAcrossRecompiles) {
  if (i::FLAG_always_opt || !i::FLAG_opt) return;
  i::FLAG_allow_natives_syntax = true;
  CcTest::InitializeVM();
  if (!CcTest::i_isolate()->use_optimizer()) return;
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();

  // Make sure function f has a call that uses a type feedback slot.
  CompileRun("function fun() {};"
             "fun1 = fun;"
             "function f(a) { a(); } f(fun1);");

  Handle<JSFunction> f = Handle<JSFunction>::cast(
      v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
          CcTest::global()->Get(context, v8_str("f")).ToLocalChecked())));

  // Verify that we gathered feedback.
  Handle<FeedbackVector> feedback_vector(f->feedback_vector(), f->GetIsolate());
  CHECK(!feedback_vector->is_empty());
  FeedbackSlot slot_for_a(0);
  MaybeObject* object = feedback_vector->Get(slot_for_a);
  {
    HeapObject* heap_object;
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
    CHECK(heap_object->IsJSFunction());
  }

  CompileRun("%OptimizeFunctionOnNextCall(f); f(fun1);");

  // Verify that the feedback is still "gathered" despite a recompilation
  // of the full code.
  CHECK(f->IsOptimized());
  object = f->feedback_vector()->Get(slot_for_a);
  {
    HeapObject* heap_object;
    CHECK(object->GetHeapObjectIfWeak(&heap_object));
    CHECK(heap_object->IsJSFunction());
  }
}

TEST(FeedbackVectorUnaffectedByScopeChanges) {
  if (i::FLAG_always_opt || !i::FLAG_lazy) {
    return;
  }
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::Context> context = CcTest::isolate()->GetCurrentContext();

  CompileRun("function builder() {"
             "  call_target = function() { return 3; };"
             "  return (function() {"
             "    eval('');"
             "    return function() {"
             "      'use strict';"
             "      call_target();"
             "    }"
             "  })();"
             "}"
             "morphing_call = builder();");

  Handle<JSFunction> f = Handle<JSFunction>::cast(v8::Utils::OpenHandle(
      *v8::Local<v8::Function>::Cast(CcTest::global()
                                         ->Get(context, v8_str("morphing_call"))
                                         .ToLocalChecked())));

  // If we are compiling lazily then it should not be compiled, and so no
  // feedback vector allocated yet.
  CHECK(!f->shared()->is_compiled());

  CompileRun("morphing_call();");

  // Now a feedback vector is allocated.
  CHECK(f->shared()->is_compiled());
  CHECK(!f->feedback_vector()->is_empty());
}

// Test that optimized code for different closures is actually shared.
TEST(OptimizedCodeSharing1) {
  FLAG_stress_compaction = false;
  FLAG_allow_natives_syntax = true;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  for (int i = 0; i < 3; i++) {
    LocalContext env;
    env->Global()
        ->Set(env.local(), v8_str("x"), v8::Integer::New(CcTest::isolate(), i))
        .FromJust();
    CompileRun(
        "function MakeClosure() {"
        "  return function() { return x; };"
        "}"
        "var closure0 = MakeClosure();"
        "var closure1 = MakeClosure();"  // We only share optimized code
                                         // if there are at least two closures.
        "%DebugPrint(closure0());"
        "%OptimizeFunctionOnNextCall(closure0);"
        "%DebugPrint(closure0());"
        "closure1();"
        "var closure2 = MakeClosure(); closure2();");
    Handle<JSFunction> fun1 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
            env->Global()
                ->Get(env.local(), v8_str("closure1"))
                .ToLocalChecked())));
    Handle<JSFunction> fun2 = Handle<JSFunction>::cast(
        v8::Utils::OpenHandle(*v8::Local<v8::Function>::Cast(
            env->Global()
                ->Get(env.local(), v8_str("closure2"))
                .ToLocalChecked())));
    CHECK(fun1->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
    CHECK(fun2->IsOptimized() || !CcTest::i_isolate()->use_optimizer());
    CHECK_EQ(fun1->code(), fun2->code());
  }
}

TEST(CompileFunctionInContext) {
  if (i::FLAG_always_opt) return;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var r = 10;");
  v8::Local<v8::Object> math = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("Math")).ToLocalChecked());
  v8::ScriptCompiler::Source script_source(v8_str(
      "a = PI * r * r;"
      "x = r * cos(PI);"
      "y = r * sin(PI / 2);"));
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   0, nullptr, 1, &math)
          .ToLocalChecked();
  CHECK(!fun.IsEmpty());

  i::DisallowCompilation no_compile(CcTest::i_isolate());
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("a")).FromJust());
  v8::Local<v8::Value> a =
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked();
  CHECK(a->IsNumber());
  CHECK(env->Global()->Has(env.local(), v8_str("x")).FromJust());
  v8::Local<v8::Value> x =
      env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
  CHECK(x->IsNumber());
  CHECK(env->Global()->Has(env.local(), v8_str("y")).FromJust());
  v8::Local<v8::Value> y =
      env->Global()->Get(env.local(), v8_str("y")).ToLocalChecked();
  CHECK(y->IsNumber());
  CHECK_EQ(314.1592653589793, a->NumberValue(env.local()).FromJust());
  CHECK_EQ(-10.0, x->NumberValue(env.local()).FromJust());
  CHECK_EQ(10.0, y->NumberValue(env.local()).FromJust());
}

TEST(CompileFunctionInContextComplex) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun(
      "var x = 1;"
      "var y = 2;"
      "var z = 4;"
      "var a = {x: 8, y: 16};"
      "var b = {x: 32};");
  v8::Local<v8::Object> ext[2];
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
  ext[1] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("b")).ToLocalChecked());
  v8::ScriptCompiler::Source script_source(v8_str("result = x + y + z"));
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   0, nullptr, 2, ext)
          .ToLocalChecked();
  CHECK(!fun.IsEmpty());
  fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
  CHECK(result->IsNumber());
  CHECK_EQ(52.0, result->NumberValue(env.local()).FromJust());
}

TEST(CompileFunctionInContextArgs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23};");
  v8::Local<v8::Object> ext[1];
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
  v8::ScriptCompiler::Source script_source(v8_str("result = x + b"));
  v8::Local<v8::String> arg = v8_str("b");
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
  CHECK_EQ(1, fun->Get(env.local(), v8_str("length"))
                  .ToLocalChecked()
                  ->ToInt32(env.local())
                  .ToLocalChecked()
                  ->Value());
  v8::Local<v8::Value> b_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &b_value).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
  CHECK(result->IsNumber());
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
}

TEST(CompileFunctionInContextComments) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  CompileRun("var a = {x: 23, y: 1, z: 2};");
  v8::Local<v8::Object> ext[1];
  ext[0] = v8::Local<v8::Object>::Cast(
      env->Global()->Get(env.local(), v8_str("a")).ToLocalChecked());
  v8::ScriptCompiler::Source script_source(
      v8_str("result = /* y + */ x + b // + z"));
  v8::Local<v8::String> arg = v8_str("b");
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   1, &arg, 1, ext)
          .ToLocalChecked();
  CHECK(!fun.IsEmpty());
  v8::Local<v8::Value> b_value = v8::Number::New(CcTest::isolate(), 42.0);
  fun->Call(env.local(), env->Global(), 1, &b_value).ToLocalChecked();
  CHECK(env->Global()->Has(env.local(), v8_str("result")).FromJust());
  v8::Local<v8::Value> result =
      env->Global()->Get(env.local(), v8_str("result")).ToLocalChecked();
  CHECK(result->IsNumber());
  CHECK_EQ(65.0, result->NumberValue(env.local()).FromJust());
}

TEST(CompileFunctionInContextNonIdentifierArgs) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptCompiler::Source script_source(v8_str("result = 1"));
  v8::Local<v8::String> arg = v8_str("b }");
  CHECK(v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 1, &arg, 0, nullptr)
            .IsEmpty());
}

TEST(CompileFunctionInContextRenderCallSite) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  static const char* source1 =
      "try {"
      "  var a = [];"
      "  a[0]();"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect1 = "TypeError: a[0] is not a function";
  static const char* source2 =
      "try {"
      "  (function() {"
      "    var a = [];"
      "    a[0]();"
      "  })()"
      "} catch (e) {"
      "  return e.toString();"
      "}";
  static const char* expect2 = "TypeError: a[0] is not a function";
  {
    v8::ScriptCompiler::Source script_source(v8_str(source1));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    CHECK(!fun.IsEmpty());
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect1))
              .FromJust());
  }
  {
    v8::ScriptCompiler::Source script_source(v8_str(source2));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect2))
              .FromJust());
  }
}

TEST(CompileFunctionInContextQuirks) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  {
    static const char* source =
        "[x, y] = ['ab', 'cd'];"
        "return x + y";
    static const char* expect = "abcd";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::Local<v8::Function> fun =
        v8::ScriptCompiler::CompileFunctionInContext(
            env.local(), &script_source, 0, nullptr, 0, nullptr)
            .ToLocalChecked();
    v8::Local<v8::Value> result =
        fun->Call(env.local(), env->Global(), 0, nullptr).ToLocalChecked();
    CHECK(result->IsString());
    CHECK(v8::Local<v8::String>::Cast(result)
              ->Equals(env.local(), v8_str(expect))
              .FromJust());
  }
  {
    static const char* source = "'use strict'; var a = 077";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
  {
    static const char* source = "{ let x; { var x } }";
    v8::ScriptCompiler::Source script_source(v8_str(source));
    v8::TryCatch try_catch(CcTest::isolate());
    CHECK(v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr)
              .IsEmpty());
    CHECK(try_catch.HasCaught());
  }
}

TEST(CompileFunctionInContextScriptOrigin) {
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());
  LocalContext env;
  v8::ScriptOrigin origin(v8_str("test"),
                          v8::Integer::New(CcTest::isolate(), 22),
                          v8::Integer::New(CcTest::isolate(), 41));
  v8::ScriptCompiler::Source script_source(v8_str("throw new Error()"), origin);
  v8::Local<v8::Function> fun =
      v8::ScriptCompiler::CompileFunctionInContext(env.local(), &script_source,
                                                   0, nullptr, 0, nullptr)
          .ToLocalChecked();
  CHECK(!fun.IsEmpty());
  v8::TryCatch try_catch(CcTest::isolate());
  CcTest::isolate()->SetCaptureStackTraceForUncaughtExceptions(true);
  CHECK(fun->Call(env.local(), env->Global(), 0, nullptr).IsEmpty());
  CHECK(try_catch.HasCaught());
  CHECK(!try_catch.Exception().IsEmpty());
  v8::Local<v8::StackTrace> stack =
      v8::Exception::GetStackTrace(try_catch.Exception());
  CHECK(!stack.IsEmpty());
  CHECK_GT(stack->GetFrameCount(), 0);
  v8::Local<v8::StackFrame> frame = stack->GetFrame(CcTest::isolate(), 0);
  CHECK_EQ(23, frame->GetLineNumber());
  CHECK_EQ(42 + strlen("throw "), static_cast<unsigned>(frame->GetColumn()));
}

void TestCompileFunctionInContextToStringImpl() {
#define CHECK_NOT_CAUGHT(__local_context__, try_catch, __op__)                \
  do {                                                                        \
    const char* op = (__op__);                                                \
    v8::Local<v8::Context> context = (__local_context__);                     \
    if (try_catch.HasCaught()) {                                              \
      v8::String::Utf8Value error(                                            \
          CcTest::isolate(),                                                  \
          try_catch.Exception()->ToString(context).ToLocalChecked());         \
      V8_Fatal(__FILE__, __LINE__,                                            \
               "Unexpected exception thrown during %s:\n\t%s\n", op, *error); \
    }                                                                         \
  } while (false)

  {  // NOLINT
    CcTest::InitializeVM();
    v8::HandleScope scope(CcTest::isolate());
    LocalContext env;

    // Regression test for v8:6190
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(22), v8_int(41));
      v8::ScriptCompiler::Source script_source(v8_str("return event"), origin);

      v8::Local<v8::String> params[] = {v8_str("event")};
      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, arraysize(params), params, 0,
              nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
          "function (event) {\n"
          "return event\n"
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }

    // With no parameters:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());
      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
          "function () {\n"
          "return 0\n"
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }

    // With a name:
    {
      v8::ScriptOrigin origin(v8_str("test"), v8_int(17), v8_int(31));
      v8::ScriptCompiler::Source script_source(v8_str("return 0"), origin);

      v8::TryCatch try_catch(CcTest::isolate());
      v8::MaybeLocal<v8::Function> maybe_fun =
          v8::ScriptCompiler::CompileFunctionInContext(
              env.local(), &script_source, 0, nullptr, 0, nullptr);

      CHECK_NOT_CAUGHT(env.local(), try_catch,
                       "v8::ScriptCompiler::CompileFunctionInContext");

      v8::Local<v8::Function> fun = maybe_fun.ToLocalChecked();
      CHECK(!fun.IsEmpty());
      CHECK(!try_catch.HasCaught());

      fun->SetName(v8_str("onclick"));

      v8::Local<v8::String> result =
          fun->ToString(env.local()).ToLocalChecked();
      v8::Local<v8::String> expected = v8_str(
          "function onclick() {\n"
          "return 0\n"
          "}");
      CHECK(expected->Equals(env.local(), result).FromJust());
    }
  }
#undef CHECK_NOT_CAUGHT
}

TEST(CompileFunctionInContextFunctionToString) {
  TestCompileFunctionInContextToStringImpl();
}

TEST(InvocationCount) {
  FLAG_allow_natives_syntax = true;
  FLAG_always_opt = false;
  CcTest::InitializeVM();
  v8::HandleScope scope(CcTest::isolate());

  CompileRun(
      "function bar() {};"
      "function foo() { return bar(); };"
      "foo();");
  Handle<JSFunction> foo = Handle<JSFunction>::cast(GetGlobalProperty("foo"));
  CHECK_EQ(1, foo->feedback_vector()->invocation_count());
  CompileRun("foo()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("bar()");
  CHECK_EQ(2, foo->feedback_vector()->invocation_count());
  CompileRun("foo(); foo()");
  CHECK_EQ(4, foo->feedback_vector()->invocation_count());
}

TEST(ShallowEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  return x + x;"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(4, result->Int32Value(env.local()).FromJust());
  }
}

TEST(DeepEagerCompilation) {
  i::FLAG_always_opt = false;
  CcTest::InitializeVM();
  LocalContext env;
  i::Isolate* isolate = CcTest::i_isolate();
  v8::HandleScope scope(CcTest::isolate());
  v8::Local<v8::String> source = v8_str(
      "function f(x) {"
      "  function g(x) {"
      "    function h(x) {"
      "      return x ** x;"
      "    }"
      "    return h(x) * h(x);"
      "  }"
      "  return g(x) + g(x);"
      "}"
      "f(2)");
  v8::ScriptCompiler::Source script_source(source);
  v8::Local<v8::Script> script =
      v8::ScriptCompiler::Compile(env.local(), &script_source,
                                  v8::ScriptCompiler::kEagerCompile)
          .ToLocalChecked();
  {
    v8::internal::DisallowCompilation no_compile_expected(isolate);
    v8::Local<v8::Value> result = script->Run(env.local()).ToLocalChecked();
    CHECK_EQ(32, result->Int32Value(env.local()).FromJust());
  }
}

}  // namespace internal
}  // namespace v8


text:
using System;
using System.Collections.Generic;

using SharpNav.Collections.Generic;
using SharpNav.Geometry;

using SharpNav.Pathfinding;

#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif

namespace SharpNav.Crowds
{
	public class PathCorridor
	{
		#region Fields

		private Vector3 pos;
		private Vector3 target;

		private Path path;

		#endregion

		#region Constructors

		public PathCorridor()
		{
			this.path = new Path();
		}

		#endregion

		#region Properties

		public Vector3 Pos
		{
			get
			{
				return pos;
			}
		}

		public Vector3 Target
		{
			get
			{
				return target;
			}
		}

		public Path NavPath
		{
			get
			{
				return path;
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// Resets the path to the first polygon.
		/// </summary>
		/// <param name="reference">The starting polygon reference</param>
		/// <param name="pos">Starting position</param>
		public void Reset(NavPolyId reference, Vector3 pos)
		{
			this.pos = pos;
			this.target = pos;
			path.Clear();
			path.Add(reference);
		}

		/// <summary>
		/// The current corridor position is expected to be within the first polygon in the path. The target
		/// is expected to be in the last polygon.
		/// </summary>
		/// <param name="target">The target</param>
		/// <param name="path">The polygon path</param>
		public void SetCorridor(Vector3 target, Path path)
		{
			this.target = target;
			this.path = path;
		}

		/// <summary>
		/// Move along the NavMeshQuery and update the position
		/// </summary>
		/// <param name="npos">Current position</param>
		/// <param name="navquery">The NavMeshQuery</param>
		/// <returns>True if position changed, false if not</returns>
		public bool MovePosition(Vector3 npos, NavMeshQuery navquery)
		{
			const int MaxVisited = 16;

			Vector3 result = new Vector3();
			List<NavPolyId> visited = new List<NavPolyId>(MaxVisited);
			NavPoint startPoint = new NavPoint(path[0], pos);

			//move along navmesh and update new position
			bool status = navquery.MoveAlongSurface(ref startPoint, ref npos, out result, visited);

			if (status == true)
			{
				MergeCorridorStartMoved(path, visited);

				//adjust the position to stay on top of the navmesh
				float h = pos.Y;
				navquery.GetPolyHeight(path[0], result, ref h);
				result.Y = h;
				pos = result;
				return true;
			}

			return false;
		}

		public void FindCorners(StraightPath corners, NavMeshQuery navquery)
		{
			const float MinTargetDist = 0.01f;

			navquery.FindStraightPath(pos, target, path, corners, 0);

			//prune points in the beginning of the path which are too close
			while (corners.Count > 0)
			{
				if (((corners[0].Flags & StraightPathFlags.OffMeshConnection) != 0) ||
					Vector3Extensions.Distance2D(corners[0].Point.Position, pos) > MinTargetDist)
					break;

				corners.RemoveAt(0);
			}

			//prune points after an off-mesh connection
			for (int i = 0; i < corners.Count; i++)
			{
				if ((corners[i].Flags & StraightPathFlags.OffMeshConnection) != 0)
				{
					corners.RemoveRange(i + 1, corners.Count - i);
					break;
				}
			}
		}

		/// <summary>
		/// Use a local area path search to try to reoptimize this corridor
		/// </summary>
		/// <param name="navquery">The NavMeshQuery</param>
		/// <returns>True if optimized, false if not</returns>
		public bool OptimizePathTopology(NavMeshQuery navquery, NavQueryFilter filter)
		{
			if (path.Count < 3)
				return false;

			const int MaxIter = 32;
			const int MaxRes = 32;

			Path res = new Path();
			int numRes = 0;
			int tempInt = 0;
			NavPoint startPoint = new NavPoint(path[0], pos);
			NavPoint endPoint = new NavPoint(path[path.Count - 1], target);
			navquery.InitSlicedFindPath(ref startPoint, ref endPoint, filter, FindPathOptions.None);
			navquery.UpdateSlicedFindPath(MaxIter, ref tempInt);
			bool status = navquery.FinalizedSlicedPathPartial(path, res);

			if (status == true && numRes > 0)
			{
				MergeCorridorStartShortcut(path, res);
				return true;
			}

			return false;
		}

		/// <summary>
		/// Use an efficient local visibility search to try to optimize the corridor between the current position and the next.
		/// </summary>
		/// <param name="next">The next postion</param>
		/// <param name="pathOptimizationRange">The range</param>
		/// <param name="navquery">The NavMeshQuery</param>
		public void OptimizePathVisibility(Vector3 next, float pathOptimizationRange, NavMeshQuery navquery)
		{
			//clamp the ray to max distance
			Vector3 goal = next;
			float dist = Vector3Extensions.Distance2D(pos, goal);

			//if too close to the goal, do not try to optimize
			if (dist < 0.01f)
				return;

			dist = Math.Min(dist + 0.01f, pathOptimizationRange);

			//adjust ray length
			Vector3 delta = goal - pos;
			goal = pos + delta * (pathOptimizationRange / dist);

			NavPoint startPoint = new NavPoint(path[0], pos);
			Path raycastPath = new Path();
			RaycastHit hit;

			navquery.Raycast(ref startPoint, ref goal, RaycastOptions.None, out hit, raycastPath);
			if (raycastPath.Count > 1 && hit.T > 0.99f)
			{
				MergeCorridorStartShortcut(raycastPath, raycastPath);
			}
		}

		/// <summary>
		/// Merge two paths after the start is changed
		/// </summary>
		/// <param name="path">The current path</param>
		/// <param name="npath">Current path length</param>
		/// <param name="maxPath">Maximum path length allowed</param>
		/// <param name="visited">The visited polygons</param>
		/// <param name="nvisited">Visited path length</param>
		/// <returns>New path length</returns>
		public int MergeCorridorStartMoved(Path path, List<NavPolyId> visited)
		{
			int furthestPath = -1;
			int furthestVisited = -1;

			//find furthest common polygon
			for (int i = path.Count - 1; i >= 0; i--)
			{
				bool found = false;
				for (int j = visited.Count - 1; j >= 0; j--)
				{
					if (path[i] == visited[j])
					{
						furthestPath = i;
						furthestVisited = j;
						found = true;
					}
				}

				if (found)
					break;
			}

			//if no intersection found just return current path
			if (furthestPath == -1 || furthestVisited == -1)
				return path.Count;

			//concatenate paths

			//adjust beginning of buffer to include the visited
			int req = visited.Count - furthestVisited;
			int orig = Math.Min(furthestPath + 1, path.Count);
			int size = Math.Max(0, path.Count - orig);
			if (req + size > path.Count)
				size = path.Count - req;
			if (size > 0)
			{
				for (int i = 0; i < size; i++)
					path[req + i] = path[orig + i];
			}

			//store visited
			for (int i = 0; i < req; i++)
				path[i] = visited[(visited.Count - 1) - i];

			return req + size;
		}

		/// <summary>
		/// Merge two paths when a shorter path is found
		/// </summary>
		/// <param name="path">The current path</param>
		/// <param name="npath">Current path length</param>
		/// <param name="maxPath">Maximum path length allowed</param>
		/// <param name="visited">The visited polygons</param>
		/// <param name="nvisited">Visited path length</param>
		/// <returns>New path length</returns>
		public int MergeCorridorStartShortcut(Path corridorPath, Path visitedPath)
		{
			int furthestPath = -1;
			int furthestVisited = -1;

			//find furthest common polygon
			for (int i = corridorPath.Count - 1; i >= 0; i--)
			{
				bool found = false;
				for (int j = visitedPath.Count - 1; j >= 0; j--)
				{
					if (path[i] == visitedPath[j])
					{
						furthestPath = i;
						furthestVisited = j;
						found = true;
					}
				}

				if (found)
					break;
			}

			//if no intersection found, return current path
			if (furthestPath == -1 || furthestVisited == -1)
				return corridorPath.Count;

			//concatenate paths
			//adjust beginning of the buffer to include the visited
			int req = furthestVisited;
			if (req <= 0)
				return corridorPath.Count;

			int orig = furthestPath;
			int size = Math.Max(0, corridorPath.Count - orig);
			if (req + size > path.Count)
				size = path.Count - req;
			for (int i = 0; i < size; i++)
				path[req + i] = path[orig + i];

			//store visited
			for (int i = 0; i < req; i++)
				path[i] = visitedPath[i];

			return req + size;
		}

		public bool MoveOverOffmeshConnection(NavPolyId offMeshConRef, NavPolyId[] refs, ref Vector3 startPos, ref Vector3 endPos, NavMeshQuery navquery)
		{
			//advance the path up to and over the off-mesh connection
			NavPolyId prevRef = NavPolyId.Null, polyRef = path[0];
			int npos = 0;
			while (npos < path.Count && polyRef != offMeshConRef)
			{
				prevRef = polyRef;
				polyRef = path[npos];
				npos++;
			}

			if (npos == path.Count)
			{
				//could not find offMeshConRef
				return false;
			}

			//prune path
			path.RemoveRange(0, npos);

			refs[0] = prevRef;
			refs[1] = polyRef;

			TiledNavMesh nav = navquery.NavMesh;

			if (nav.GetOffMeshConnectionPolyEndPoints(refs[0], refs[1], ref startPos, ref endPos) == true)
			{
				pos = endPos;
				return true;
			}

			return false;
		}

		/// <summary>
		/// Adjust the beginning of the path
		/// </summary>
		/// <param name="safeRef">The starting polygon reference</param>
		/// <param name="safePos">The starting position</param>
		/// <returns>True if path start changed, false if not</returns>
		public bool FixPathStart(NavPolyId safeRef, Vector3 safePos)
		{
			this.pos = safePos;
			if (path.Count < 3 && path.Count > 0)
			{
				NavPolyId lastPathId = path[path.Count - 1];

				path.Clear();
				path.Add(safeRef);
				path.Add(NavPolyId.Null);
				path.Add(lastPathId);
			}
			else
			{
				path[0] = safeRef;
				path[1] = NavPolyId.Null;
			}

			return true;
		}

		/// <summary>
		/// Determines whether all the polygons in the path are valid
		/// </summary>
		/// <param name="maxLookAhead">The amount of polygons to examine</param>
		/// <param name="navquery">The NavMeshQuery</param>
		/// <returns>True if all valid, false if otherwise</returns>
		public bool IsValid(int maxLookAhead, NavMeshQuery navquery)
		{
			int n = Math.Min(path.Count, maxLookAhead);
			for (int i = 0; i < n; i++)
			{
				if (!navquery.IsValidPolyRef(path[i]))
					return false;
			}

			return true;
		}

		public NavPolyId GetFirstPoly()
		{
			return (path.Count != 0) ? path[0] : NavPolyId.Null;
		}

		public NavPolyId GetLastPoly()
		{
			return (path.Count != 0) ? path[path.Count - 1] : NavPolyId.Null;
		}

		#endregion
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700">
  <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/icon?family=Material+Icons">

  <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/css/bootstrap-material-design.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-material-design/0.5.9/css/ripples.min.css">

  <link rel="stylesheet" type="text/css" href="../../assets/css/style.css">

  </script>

 Reservation Manager App


text:
<?php
namespace AppBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 *
 */
class ImportDataCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('nameo:import')
            ->setDescription('imports card data')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
      $data = file_get_contents("data/Card.json");
      $cards = json_decode($data,true);

      $entityManager = $this->getContainer()->get('doctrine')->getManager();

      foreach ($cards as $value){
        $category = $entityManager->getRepository('AppBundle:Category')->find($value['category_id']);
        if(!$category) {
          $output->writeln("Un problème !");
          dump($value);
          continue;
        }

        $card = $entityManager->getRepository('AppBundle:Card')->findOneBy([
          'title' => $value['title']
        ]);

        if(!$card) {
          $card=new \AppBundle\Entity\Card();
          $card->setTitle($value['title']);
          $card->setAttempts(0);
          $card->setSuccesses(0);
          $entityManager->persist($card);
        }

        $card->setDescription($value['description']);
        $card->setCategory($category);

        $output->writeln("Traitement réussi pour ".$card->getTitle());
      }
      $entityManager->flush();
    }
}


text:
package chav1961.purelib.streams;

import java.io.IOException;
import java.io.Writer;

/**
 *
This wrapper class can be used in conjunction with any Writer to get full access to Writer's methods without extending existent class to wrap.

 *
 * @author Alexander Chernomyrdin aka chav1961
 * @since 0.0.2
 */

public class WriterWrapper extends Writer {
	private final Writer	delegate;

	/**
	 *
Constructor of the class

	 * @param delegate nested writer to wrap
	 */
	public WriterWrapper(final Writer delegate) {
		if (delegate == null) {
			throw new NullPointerException("Writer delegate can't be null");
		}
		else {
			this.delegate = delegate;
		}
	}

	@Override
    public void write(final int c) throws IOException {
		delegate.write(c);
    }

	@Override
    public void write(final char cbuf[]) throws IOException {
		delegate.write(cbuf);
    }

	@Override
    public void write(final char cbuf[], final int off, final int len) throws IOException {
		delegate.write(cbuf, off, len);
    }

	@Override
    public void write(final String str) throws IOException {
		delegate.write(str);
    }

	@Override
    public void write(final String str, final int off, final int len) throws IOException {
		delegate.write(str, off, len);
    }

	@Override
    public Writer append(final CharSequence csq) throws IOException {
		delegate.append(csq);
        return this;
    }

	@Override
    public Writer append(final CharSequence csq, final int start, final int end) throws IOException {
		delegate.append(csq, start, end);
        return this;
    }

	@Override
    public Writer append(final char c) throws IOException {
		delegate.append(c);
        return this;
    }

	@Override
    public void flush() throws IOException {
		delegate.flush();
    }

	@Override
    public void close() throws IOException {
		delegate.close();
    }
}


text:
Some generic prototyping boards, mimicking the common breadboard design, with additional space for USB and barrel jack sockets.

The small boards fit the [SoB 5x5](http://dangerousprototypes.com/docs/Sick_of_Beige_standard_PCB_sizes_v1.0) footprint, while the large ones are twice as long.


text:
RailsApp::Application.routes.draw do |map|

  map.connect "admin/delayed/tasks/:action/:id(.:format)", :controller => "admin/delayed/tasks"

  Typus::Routes.draw(map)
  root :to => "welcome#index"

end


text:
A training tracker web app (WIP)

[![Code Climate](https://codeclimate.com/github/rodrigotassinari/training_tracker/badges/gpa.svg)](https://codeclimate.com/github/rodrigotassinari/training_tracker)
[![Test Coverage](https://codeclimate.com/github/rodrigotassinari/training_tracker/badges/coverage.svg)](https://codeclimate.com/github/rodrigotassinari/training_tracker/coverage)
[![Build Status](https://travis-ci.org/rodrigotassinari/training_tracker.png?branch=master)](https://travis-ci.org/rodrigotassinari/training_tracker)

**EXTREMELY ALPHA SOFTWARE!**, work in progress.

## Running on development

You will need:

- Ruby 2.3+
- PostgreSQL 9.4+

Clone the repo and create a `.env` file with values for your environment (use `.env.example` as a starting point, changing the values where needed).

Next run the standard Rails app setup:

```
$ bundle install
$ bundle exec rake db:setup
```

To start the app, run:

```
$ bin/foreman start
```

## Testing

Simply run:

```
$ bin/rake spec
```

## Contributing

Fork this repo, make your changes on your fork in a topic branch and submit a pull request against this repo's master branch.

Please write all code, comments, tests and commit messages in english. Use 2 spaces to indent code and follow idiomatic Ruby as close as possible. No CoffeeScript, please.

## License

This project is open source and licensed under the terms of the MIT License. See `LICENSE` for more information.


text:
package org.apache.drill.exec.resolver;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.drill.common.types.TypeProtos.MinorType;

public class ResolverTypePrecedence {

  public static final Map<MinorType, Integer> precedenceMap;
  public static final Map<MinorType, Set<MinorType>> secondaryImplicitCastRules;
  public static int MAX_IMPLICIT_CAST_COST;

  static {
    /* The precedenceMap is used to decide whether it's allowed to implicitly "promote"
     * one type to another type.
     *
     * The order that each type is inserted into HASHMAP decides its precedence.
     * First in ==> lowest precedence.
     * A type of lower precedence can be implicitly "promoted" to type of higher precedence.
     * For instance, NULL could be promoted to any other type;
     * tinyint could be promoted into int; but int could NOT be promoted into tinyint (due to possible precision loss).
     */
    int i = 0;
    precedenceMap = new HashMap<MinorType, Integer>();
    precedenceMap.put(MinorType.NULL, i += 2);       // NULL is legal to implicitly be promoted to any other type
    precedenceMap.put(MinorType.FIXEDBINARY, i += 2); // Fixed-length is promoted to var length
    precedenceMap.put(MinorType.VARBINARY, i += 2);
    precedenceMap.put(MinorType.FIXEDCHAR, i += 2);
    precedenceMap.put(MinorType.VARCHAR, i += 2);
    precedenceMap.put(MinorType.FIXED16CHAR, i += 2);
    precedenceMap.put(MinorType.VAR16CHAR, i += 2);
    precedenceMap.put(MinorType.BIT, i += 2);
    precedenceMap.put(MinorType.TINYINT, i += 2);   //type with few bytes is promoted to type with more bytes ==> no data loss.
    precedenceMap.put(MinorType.UINT1, i += 2);     //signed is legal to implicitly be promoted to unsigned.
    precedenceMap.put(MinorType.SMALLINT, i += 2);
    precedenceMap.put(MinorType.UINT2, i += 2);
    precedenceMap.put(MinorType.INT, i += 2);
    precedenceMap.put(MinorType.UINT4, i += 2);
    precedenceMap.put(MinorType.BIGINT, i += 2);
    precedenceMap.put(MinorType.UINT8, i += 2);
    precedenceMap.put(MinorType.MONEY, i += 2);
    precedenceMap.put(MinorType.FLOAT4, i += 2);
    precedenceMap.put(MinorType.DECIMAL9, i += 2);
    precedenceMap.put(MinorType.DECIMAL18, i += 2);
    precedenceMap.put(MinorType.DECIMAL28DENSE, i += 2);
    precedenceMap.put(MinorType.DECIMAL28SPARSE, i += 2);
    precedenceMap.put(MinorType.DECIMAL38DENSE, i += 2);
    precedenceMap.put(MinorType.DECIMAL38SPARSE, i += 2);
    precedenceMap.put(MinorType.FLOAT8, i += 2);
    precedenceMap.put(MinorType.DATE, i += 2);
    precedenceMap.put(MinorType.TIMESTAMP, i += 2);
    precedenceMap.put(MinorType.TIMETZ, i += 2);
    precedenceMap.put(MinorType.TIMESTAMPTZ, i += 2);
    precedenceMap.put(MinorType.TIME, i += 2);
    precedenceMap.put(MinorType.INTERVALDAY, i+= 2);
    precedenceMap.put(MinorType.INTERVALYEAR, i+= 2);
    precedenceMap.put(MinorType.INTERVAL, i+= 2);

    MAX_IMPLICIT_CAST_COST = i;

    /* Currently implicit cast follows the precedence rules.
     * It may be useful to perform an implicit cast in
     * the opposite direction as specified by the precedence rules.
     *
     * For example: As per the precedence rules we can implicitly cast
     * from VARCHAR ---> BIGINT , but based upon some functions (eg: substr, concat)
     * it may be useful to implicitly cast from BIGINT ---> VARCHAR.
     *
     * To allow for such cases we have a secondary set of rules which will allow the reverse
     * implicit casts. Currently we only allow the reverse implicit cast to VARCHAR so we don't
     * need any cost associated with it, if we add more of these that may collide we can add costs.
     */
    secondaryImplicitCastRules = new HashMap<>();
    HashSet<MinorType> rule = new HashSet<>();

    // Following cast functions should exist
    rule.add(MinorType.TINYINT);
    rule.add(MinorType.SMALLINT);
    rule.add(MinorType.INT);
    rule.add(MinorType.BIGINT);
    rule.add(MinorType.UINT1);
    rule.add(MinorType.UINT2);
    rule.add(MinorType.UINT4);
    rule.add(MinorType.UINT8);
    rule.add(MinorType.DECIMAL9);
    rule.add(MinorType.DECIMAL18);
    rule.add(MinorType.DECIMAL28SPARSE);
    rule.add(MinorType.DECIMAL28DENSE);
    rule.add(MinorType.DECIMAL38SPARSE);
    rule.add(MinorType.DECIMAL38DENSE);
    rule.add(MinorType.MONEY);
    rule.add(MinorType.FLOAT4);
    rule.add(MinorType.FLOAT8);
    rule.add(MinorType.BIT);
    rule.add(MinorType.FIXEDCHAR);
    rule.add(MinorType.FIXED16CHAR);
    rule.add(MinorType.VARCHAR);
    rule.add(MinorType.DATE);
    rule.add(MinorType.TIME);
    rule.add(MinorType.TIMESTAMP);
    rule.add(MinorType.TIMESTAMPTZ);
    rule.add(MinorType.INTERVAL);
    rule.add(MinorType.INTERVALYEAR);
    rule.add(MinorType.INTERVALDAY);
    secondaryImplicitCastRules.put(MinorType.VARCHAR, rule);

    rule = new HashSet<>();

    // Be able to implicitly cast to VARBINARY
    rule.add(MinorType.INT);
    rule.add(MinorType.BIGINT);
    rule.add(MinorType.FLOAT4);
    rule.add(MinorType.FLOAT8);
    rule.add(MinorType.VARCHAR);
    secondaryImplicitCastRules.put(MinorType.VARBINARY, rule);

  }

}


text:
package scripts.utils;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static scripts.utils.GcsBucketUtils.GCS_BLOB_CONTENT;

import bio.terra.testrunner.runner.config.TestUserSpecification;
import bio.terra.workspace.model.ControlledResourceIamRole;
import com.google.api.client.http.HttpStatusCodes;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class for testing access to a GCS bucket
 *
 *
The constructor requires a test user that is able to create a "reference" blob in the bucket.
 * The methods test the access levels using the ControlledResourceIamRole names and reports success
 * or failure. One instance of the class can be used for multiple role tests.
 *
 *
We test 6 operations:
 *
 *

 *
read an existing blob
 *
create a new blob
 *
update a blob
 *
delete a blob
 *
get bucket metadata
 *
delete the bucket (no role should be able to do this one)
 *

 *
 * Only listing the abilities:
 *
 *

 *
READER can read a blob
 *
WRITER can create, read, update, delete
 *
EDITOR can create, read, update, delete, and get metadata
 *
null indicates no role and has no abilities
 *

 *
 *
When an access change is made, we need to wait for the change to propagate, but since we also
 * expect many failures, we do not want to wait every time. If requested, using checkAccessWait, we
 * will wait on the first operation. Otherwise, we do not wait on any operations.
 */
public class GcsBucketAccessTester implements AutoCloseable {
  private static final Logger logger = LoggerFactory.getLogger(GcsBucketAccessTester.class);
  private final TestUserSpecification creatorTestUser;
  private final String bucketName;
  private final String projectId;
  private BlobId testBlobId;
  private final List<BlobId> createdBlobs;
  private boolean needToWait;
  private Storage testClient;

  public GcsBucketAccessTester(
      TestUserSpecification creatorTestUser, String bucketName, String projectId) throws Exception {
    this.creatorTestUser = creatorTestUser;
    this.bucketName = bucketName;
    this.projectId = projectId;
    this.testBlobId = null;
    this.needToWait = false;
    this.createdBlobs = new ArrayList<>();
  }

  @Override
  public void close() throws IOException {
    // Clean up any created blob so that delete happens quickly, lest the test timeout waiting.
    Storage creatorClient = ClientTestUtils.getGcpStorageClient(creatorTestUser, projectId);
    for (BlobId blobId : createdBlobs) {
      boolean found = creatorClient.delete(blobId);
      logger.info("Blob {} was {}", blobId.getName(), (found ? "found and deleted" : "not found"));
    }
  }

  public void checkAccessWait(
      TestUserSpecification testUser, @Nullable ControlledResourceIamRole role) throws Exception {
    needToWait = true;
    checkAccess(testUser, role);
  }

  /**
   * @param testUser user to check
   * @param role the IamRole to test for; null to test the "user has no role" case
   * @throws Exception from asserts if the user has unexpected access
   */
  public void checkAccess(TestUserSpecification testUser, @Nullable ControlledResourceIamRole role)
      throws Exception {
    logger.info(
        "Checking access of {} for role {} with wait {}",
        testUser.userEmail,
        (role == null ? "none" : role.toString()),
        needToWait);

    testClient = ClientTestUtils.getGcpStorageClient(testUser, projectId);
    if (role == null) {
      assertFalse(doWithOptionalWait(() -> blobCreate(testClient)), "no role cannot create");
      assertFalse(doWithOptionalWait(this::blobRead), "no role cannot read");
      assertFalse(doWithOptionalWait(this::blobUpdate), "no role cannot update");
      assertFalse(doWithOptionalWait(this::blobDelete), "no role cannot delete");
      assertFalse(doWithOptionalWait(this::bucketGet), "no role cannot bucket get");
      assertFalse(doWithOptionalWait(this::bucketDelete), "no role cannot bucket delete");
      return;
    }

    switch (role) {
      case READER:
        assertTrue(doWithOptionalWait(this::blobRead), "reader can read");
        assertFalse(doWithOptionalWait(() -> blobCreate(testClient)), "reader cannot create");
        assertFalse(doWithOptionalWait(this::blobUpdate), "reader cannot update");
        assertFalse(doWithOptionalWait(this::blobDelete), "reader cannot delete");
        assertFalse(doWithOptionalWait(this::bucketGet), "reader cannot bucket get");
        assertFalse(doWithOptionalWait(this::bucketDelete), "reader cannot bucket delete");
        return;

      case WRITER:
        assertTrue(doWithOptionalWait(() -> blobCreate(testClient)), "writer can create");
        assertTrue(doWithOptionalWait(this::blobRead), "writer can read");
        assertTrue(doWithOptionalWait(this::blobUpdate), "writer can update");
        assertTrue(doWithOptionalWait(this::blobDelete), "writer can delete");
        assertFalse(doWithOptionalWait(this::bucketGet), "writer cannot bucket get");
        assertFalse(doWithOptionalWait(this::bucketDelete), "writer cannot bucket delete");
        return;

      case EDITOR:
        assertTrue(doWithOptionalWait(() -> blobCreate(testClient)), "editor can create");
        assertTrue(doWithOptionalWait(this::blobRead), "editor can read");
        assertTrue(doWithOptionalWait(this::blobUpdate), "editor can update");
        assertTrue(doWithOptionalWait(this::blobDelete), "editor can delete");
        assertTrue(doWithOptionalWait(this::bucketGet), "editor can bucket get");
        assertFalse(doWithOptionalWait(this::bucketDelete), "editor cannot bucket delete");
        return;

      default:
        throw new IllegalArgumentException("Invalid IAM role: " + role);
    }
  }

  // Common logic for optionally waiting on the first check.

  @FunctionalInterface
  public interface TestFunction {
    Object apply() throws Exception;
  }

  private boolean doWithOptionalWait(TestFunction function) throws Exception {
    try {
      if (needToWait) {
        ClientTestUtils.getWithRetryOnException(function::apply);
        needToWait = false;
      } else {
        function.apply();
      }
      return true;
    } catch (StorageException e) {
      assertEquals(HttpStatusCodes.STATUS_CODE_FORBIDDEN, e.getCode());
      return false;
    }
  }

  // Simple operations that wrap the storage calls so they are homogeneous and
  // can be used as lambdas. These return Object so I can reuse getWithRetryOnException.

  // blobCreate doesn't follow the pattern of the other actions, because it is used
  // by both the creatorTestUser and the checkAccess testUser.
  private BlobId blobCreate(Storage storageClient) throws StorageException {
    BlobId blobId = BlobId.of(bucketName, makeBlobName());
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
    storageClient.create(blobInfo, GCS_BLOB_CONTENT.getBytes(StandardCharsets.UTF_8));
    createdBlobs.add(blobId);
    logger.info("Blob {} was created", blobId.getName());
    return blobId;
  }

  private Object blobRead() throws Exception {
    return testClient.get(makeTestBlobId());
  }

  private Object blobUpdate() throws Exception {
    Blob retrievedFile = testClient.get(makeTestBlobId());
    return retrievedFile.toBuilder().setContentType("text/html").build().update();
  }

  private Object blobDelete() throws Exception {
    boolean result = testClient.delete(makeTestBlobId());
    if (result) {
      testBlobId = null;
    }
    return result;
  }

  private Object bucketGet() throws Exception {
    return testClient.get(bucketName, Storage.BucketGetOption.fields(Storage.BucketField.values()));
  }

  private Object bucketDelete() throws Exception {
    return testClient.get(bucketName).delete();
  }

  // Make a blob for testing. We need a blob that can be read or deleted even if the
  // test user cannot create one. So we use our creatorTestUser to create the blob. We
  // reuse the blob, if it is still around. Note the variable clearing the blobDelete method.
  private BlobId makeTestBlobId() throws IOException {
    if (testBlobId == null) {
      Storage creatorClient = ClientTestUtils.getGcpStorageClient(creatorTestUser, projectId);
      testBlobId = blobCreate(creatorClient);
    }
    return testBlobId;
  }

  private String makeBlobName() {
    return RandomStringUtils.random(10, true, false);
  }
}


text:
/* Just a header that shows how to package up an inczip */
#ifndef _COUNTER_H
#define _COUNTER_H

#include <string>

using namespace std;

class Counter {
public:
    string count();
};

#endif /* _COUNTER_H */


text:
/*
 * Contains groups of units, useful constants, and methods to convert between units.
 *
 * Author: Julia McClellan
 * Version: 2/5/2016
 */

package HelperClasses;

import java.util.TreeMap;

import javax.swing.JTextField;

public class Units
{
	public static final int ENTERFIELD_AMOUNT_COLUMNS = 6;
	public static final int ENTERFIELD_AMOUNT_WIDTH = ((System.getProperty("os.name").contains("Mac")) ? -6 : 0) +
			(int)(new JTextField(ENTERFIELD_AMOUNT_COLUMNS).getPreferredSize().getWidth());
	public static final int ENTERFIELD_AMOUNT_HEIGHT = 26 + ((System.getProperty("os.name").contains("Mac")) ? 6 : 0);
	public static final double R = .0821, STANDARD_PRESSURE = 1, STANDARD_TEMPERATURE = 273.15, C = 3E8, h = 6.626E-34;
	public static final int UNKNOWN_VALUE = -500, ERROR_VALUE = -501;
	public static final String[] PREFIXES = {"p", "n", "\u00B5", "m", "c", "d", "", "da", "h", "k", "M", "G", "T"};
	public static final int[] POWERS = {-12, -9, -6, -3, -2, -1, 0, 1, 2, 3, 6, 9, 12};
	private static final TreeMap<String, String[]> UNITS = generateMap();

	private static TreeMap<String, String[]> generateMap()
	{
		TreeMap<String, String[]> units = new TreeMap<String, String[]>();
		units.put("Pressure", new String[]{"atm", "torr", "kPa"});
		units.put("Temperature", new String[]{"K", "\u2103", "\u2109"});
		units.put("Amount", new String[]{"mol"});
		units.put("Volume", createGroup("L"));
		units.put("Length", createGroup("m"));
		units.put("Mass", createGroup("g"));
		units.put("Frequency", new String[]{"Hz"});
		units.put("Energy", createGroup("J"));
		units.put("Velocity", new String[] {"m/s"});
		units.put("Planck", new String[]{"J\u00B7s"});
		units.put("Time", new String[]{"s", "hr", "day"});
		units.put("Mass*Temp", new String[]{"g\u00B7K", "g\u00B7\u2103"});
		units.put("Percent", new String[]{"%"});
		return units;
	}

	private static String[] createGroup(String base)
	{
		String[] group = new String[PREFIXES.length];
		for(int index = 0; index < PREFIXES.length; index++)
		{
			group[index] = PREFIXES[index] + base;
		}
		return group;
	}

	public static String[] getUnits(String type)
	{
		if(type.equals("Moles")) type = "Amount";
		return UNITS.get(type);
	}

	public static String[][] getUnits(String[] types)
	{
		String[][] units = new String[types.length][];
		for(int index = 0; index < types.length; index++)
		{
			units[index] = getUnits(types[index]);
		}
		return units;
	}

	public static double fahrenheitToKelvin(double fahrenheit)
	{
		return (fahrenheit + 459.67) * 5 / 9;
	}

	public static double kelvinToFahrenheit(double kelvin)
	{
		return (kelvin  * 9 / 5) - 459.67;
	}

	public static double celsiusToKelvin(double celsius)
	{
		return celsius + 273.15;
	}

	public static double kelvinToCelsius(double kelvin)
	{
		return kelvin - 273.15;
	}

	public static double torrToatm(double torr)
	{
		return torr * 0.00131579;
	}

	public static double atmTotorr(double atm)
	{
		return atm / 0.00131579;
	}

	public static double kPaToatm(double kPa)
	{
		return kPa * 0.00986923;
	}

	public static double atmTokPa(double atm)
	{
		return atm / 0.00986923;
	}

	public static double toBaseUnit(double amount, int unit)
	{
		if(amount == Units.UNKNOWN_VALUE) return amount;
		else if(amount == Units.ERROR_VALUE) return amount;
		else return amount * Math.pow(10, POWERS[unit]);
	}

	public static double fromBaseUnit(double amount, int unit)
	{
		if(amount == Units.UNKNOWN_VALUE) return amount;
		else if(amount == Units.ERROR_VALUE) return amount;
		else return amount / Math.pow(10, POWERS[unit]);
	}

	public static double betweenUnits(double amount, int from, int to)
	{
		return amount * Math.pow(10, POWERS[from - to]);
	}

	public static double toKelvin(double amount, int unit) {
		if(amount == UNKNOWN_VALUE) return amount;
		else if(amount == ERROR_VALUE) return amount;
		else if(unit == 0) return amount; //if kelvin
		else if(unit == 1) return Units.celsiusToKelvin(amount); //if celcius
		else return Units.fahrenheitToKelvin(amount); //if fahrenheit
	}

	public static double toOriginalTemp(double amount, int unit) {
		if(unit == 0) return amount; //if kelvin
		else if(unit == 1) return Units.kelvinToCelsius(amount);//if celcius
		else return Units.kelvinToFahrenheit(amount); //if fahrenheit
	}

	public static double toSeconds(double amount, int unit) {
		if(unit == 0) return amount; //if seconds
		else if(unit == 1) return amount * 3600; //if hours
		else return amount * 86400; //if days
	}

	public static double toOriginalTime(double amount, int unit) {
		if(unit == 0) return amount; //if seconds
		else if(unit == 1) return amount / 3600; //if hours
		else return amount / 86400; //if days
	}

	public static double toAtm(double amount, int unit)
	{
		if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE || unit == 0) return amount;
		if(unit == 1) return torrToatm(amount);
		return  kPaToatm(amount);
	}

	public static double fromAtm(double amount, int unit)
	{
		if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE || unit == 0) return amount;
		if(unit == 1) return atmTotorr(amount);
		return  atmTokPa(amount);
	}

	public static double toStandard(double amount, int unit, String type)
	{
		if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE) return amount;
		if(type.equals("Temperature")) return toKelvin(amount, unit);
		else if(type.equals("Pressure")) return toAtm(amount, unit);
		else if(type.equals("Time")) return toSeconds(amount, unit);
		else if(UNITS.get(type).length == PREFIXES.length) return toBaseUnit(amount, unit);
		else return amount;
	}

	public static double fromStandard(double amount, int unit, String type)
	{
		if(amount == UNKNOWN_VALUE || amount == ERROR_VALUE) return amount;
		if(type.equals("Temperature")) return toOriginalTemp(amount, unit);
		else if(type.equals("Pressure")) return fromAtm(amount, unit);
		else if(type.equals("Time")) return toOriginalTime(amount, unit);
		else if(UNITS.get(type).length == PREFIXES.length) return fromBaseUnit(amount, unit);
		else return amount;
	}
}


text:
from __future__ import division
from ImportTrackMateData import *
import TrackClassGlobals as TCG
import TrackFilterFunctions as TFF
from Serializers import *
from General import *
import sys, traceback, datetime, os.path, math
import numpy as np
import pylab as P
from copy import deepcopy
import matplotlib.cm as cm
from scipy import stats
import _pickle as pickle
from colorsys import *

##
## @brief      { Holds raw position and frame data for 1 cell-track }
##
class Track():

	##
	## @brief      { Constructor }
	##
	## @param      self  The object
	## @param      x     { 1xN array of x pos, where index corresonds to frame# }
	## @param      y     { 1xN array of y pos, where index corresonds to frame# }
	## @param      z     { 1xN array of z pos, where index corresonds to frame# }
	## @param      t     { 1xN array of t pos, where index corresonds to frame# }
	##
	def __init__(self, x, y, z, t):
		self.x = x
		self.y = y
		self.z = z
		self.t = t

##
## @brief      { Holds all Tracks contained in a single TrackMate xml output file }
##
class TrackFile():

	##
	## @brief      { Constructor }
	##
	## @param      self      The object
	## @param      tracks    1xN array of Track objects
	## @param      fileName  name of the xml file
	## @param      fields    the Track measurements to be included in
	##                       computation/analysis
	## @param      filters   a filter settings object (Default has no active
	##                       filters)
	## @param      path      the full path to the xml file's parent directory
	## @param      master    Bool to flag a merged Trackfile, representing a
	##                       full experiment containing all tracks. When this is
	##                       set to true, the experiment x and y dimensions are
	##                       found, and initial analysis is performed to prep
	##                       for filtering.
	##
	def __init__(self, tracks,
				 fileName,
				 expParams = TCG.DefaultExpParams,
				 path = 0,
				 master = False):

		self.fileName = fileName
		self.path = path
		self.importTime = None

		self.fields = TCG.DefaultTrackMeasurements
		self.filters = {}
		self.expParams = expParams
		self.tracks = tracks
		self.d = {} #Dictionary of Track measurement lists,
		            #where indices across lists correlate to
		            #the same Track
		self.meta = {} #Dict in which track measurement metadata is stored
		self.axisLimits = expParams['DefaultAxisLimits'] #Dict in which track measurement min and max values are stored

		self.master = master #True means the trackfile contains full experiment data
		                     #and is ready for analysis

		#to be done on TrackFile that has merged tracks
		#first analysis performed, field axislimits are updated
		if self.master:
			self.analysis()
		return

	# Filters tracks and reanalyzes
	#
	# @param      self     The object
	# @param      filters  The filters
	#
	# @exception  <exception_object> { Error occured while filtering }
	#
	def selectData(self, filters):
		#for filterInstance in filters:
		updateFilterSettings(self, filters)

		try:
			TFF.selectFrames(self, filters)
			TFF.selectArea(self, filters)
			TFF.selectDictBins(self, filters)
		except:
			#pass
			vprint('Warning: exception hit in track filtering. Possibly no tracks to filter.')
			traceback.print_exc(file = sys.stdout)

		return

	# Recomputes track measurement dict d. Updates
	# axislimits of all trackmeasurements
	#
	# @param      self    The object
	# @param      fields  The fields
	#
	def analysis(self):
		#if no tracks analysis cannot be performed. clear data and return
		if len(self.tracks) == 0:
			clear(self)
			return

		for key, measurementClass in self.fields.items():
			if measurementClass.function:
				dataBuffer = []
				for track in self.tracks:
					dataBuffer.append(measurementClass.function(track, **self.expParams))
				if len(dataBuffer) == 0:
					clear(self)
					return
				else:
					self.d[key] = dataBuffer
					self.meta[key] = self.getAverage(key)
					self.axisLimits[key] = [min(dataBuffer), max(dataBuffer)]

		self.axisLimits["xPos"] = [min(self.d["xStartPos"]), max(self.d["xEndPos"])]
		self.axisLimits["yPos"] = [min(self.d["yStartPos"]), max(self.d["yEndPos"])]
		self.axisLimits["frames"] = [min(self.d["firstFrame"]), max(self.d["lastFrame"])]

		return

	##
	## Scans over tracks by propertyName, and computes function on them
	## at each slice
	##
	## @param      self          The object
	## @param      propertyName  The property name
	## @param      minVal        The minimum value
	## @param      maxVal        The maximum value
	## @param      resolution    The resolution
	## @param      function      The function
	## @param      args     	 The scan settings
	##
	def scan(self,
			 propertyName,
			 minVal,
			 maxVal,
			 resolution,
			 function,
			 *args):

		vprint("Scanning %s by %s..." % (self.fileName, propertyName))
		#check that scanning range is valid and update if otherwise
		minVal, maxVal = scanAxesClampHelper(self, propertyName, minVal, maxVal)

		#Instantiate workbook for writing data from this function
		workBookName = "%s %s scan of %s vs %s by %s.xlsx" % (TCG.SAVE_DIRECTORY, self.fileName, args[0], args[1], propertyName)
		workbook = xlsxwriter.Workbook(workBookName, {'nan_inf_to_errors': True, 'in_memory': True})

		bins = np.linspace(minVal, maxVal, resolution+1)
		settings = args[2]
		title = "%s, %s vs %s scanned by %s" % (self.fileName , args[0], args[1], propertyName)
		legendStrings = []
		colorIndices = np.linspace(0, 1, resolution)
		fig = constructFig(self, title)

		writeData(self, workbook, "binData")

		keepOpen = True #flag for whether to close the excel workbook on the next write
		for index, colorIdx in zip (range(0, len(bins)-1), colorIndices):

			#get filter instance range
			lowerVal = bins[index]
			upperVal = bins[index+1]

			#copy data
			filtersCopy = {}
			filtersCopy[propertyName] = [[lowerVal, upperVal]]
			trackFileCopy = deepcopy(self)
			trackFileCopy.selectData(filtersCopy)

			#turn off settings new fig
			settings["show"] = False
			settings["newFig"] = False
			settings["save"] = False

			#get plot instance legend name
			legendString = "%.1f to %.1f" % (lowerVal, upperVal)
			legendStrings.append(legendString)

			if (index == len(bins)-1):
				keepOpen = False

			#plot
			P = function(trackFileCopy, *args, color = cm.cool(colorIdx), workbook = [workbook, legendString, keepOpen])
			P.legend(legendStrings, title=(self.fields[propertyName]).axisLabel, loc = settings['legendLoc'], prop = {'size': 9})

		savePlot(fig, title)
		P.close()

	# returns weightedAverage and standard deviation
	# or number average and standard error of a measurement in Trackfile
	#
	# no standard method for calculating weighted average standard error
	#
	# TODO: Maybe nAvg should also have stdDev
	# TODO: handle errors, don't return 0. will have to do for now
	# TODO: rename to getAverage()
	#
	# @param      self          TrackFile
	# @param      propertyName  measurementName
	# @param      settings      The settings
	#
	# @return     either wAvg and stdErr or nAvg and stdDev
	#
	def getAverage(self, propertyName, weights = False):
		if len(self.tracks) == 0:
			vprint("Notice: getAverage called on 0 tracks")
			return float('nan'), float('nan'), float('nan')
		try:
			if not weights:
				avg = np.average(self.d[propertyName])
				stdDev = np.std(self.d[propertyName])
				stdErr = stats.sem(self.d[propertyName])
				return avg, stdDev, stdErr

			weightedAvg = np.average(self.d[propertyName], weights = self.d[weights])
			stdDev = sqrt(np.average((self.d[propertyName] - weightedAvg)**2, weights = self.d[weights]))
			return weightedAvg, stdDev, 0

		except:
			print("Warning: Exception hit in getAverage")
			return float('nan'), float('nan'), float('nan')

	##
	## BEGIN SCAN COMPATIBLE FUNCTIONS
	##

	# Bins dataPropertyName values by binnedPropertyName
	# calculates avg, stdDev, stdErr for n bins and returns size N lists
	#
	# Does same thing as getWieightedAverageCorr, but non-monotonically increasing bins can
	# be used with this one.
	#
	# TODO: switch getWieghtedAverageCorr to getBinData
	# 		should be able to choose scanning mode. e.g. by monotonic or by percentiles
	# 		Right now only supports nonmonotonic/scalar bins defined in settings
	#
	# @param      self                The object
	# @param      binnedPropertyName  The binned property name
	# @param      dataPropertyName    The data property name
	# @param      settings            The settings
	#
	# @return     averages, stdDevs, stdErrs, trackCounts, countPercents (bin# to experiment#), bincenters
	#
	def getBinData(self, binnedPropertyName, dataPropertyName, settings = TCG.PlotDefaults):
		if len(self.d[binnedPropertyName]) == 0:
			return 0, 0, 0, 0, 0, 0

		avgs = []
		stdDevs = []
		stdErrs = []
		trackCounts = []
		countPercents = []
		binCenters = []

		#format bin setting to iterator (hacky)
		binArray = (self.fields[binnedPropertyName]).bins
		if type(binArray) == int:
			minValueProperty = (self.axisLimits[binnedPropertyName])[0] #min value
			maxValueProperty = (self.axisLimits[binnedPropertyName])[1] #max value
			binArray = np.linspace(minValueProperty, maxValueProperty, binArray+1)

		#iterate across bins, select data, get dataPropertyName avgs, stdDevs, stderrs and
		#add to array
		for index in range(len(binArray) - 1):
			minVal = binArray[index]
			maxVal = binArray[index+1]
			filters = {}
			filters[binnedPropertyName] = [[minVal, maxVal]]

			copy = deepcopy(self)
			copy.selectData(filters)
			wAvg, stdDev, stdErr = copy.getAverage(dataPropertyName, weights = settings['weights'])

			if not math.isnan(wAvg):
				avgs.append(wAvg)
				stdDevs.append(stdDev)
				stdErrs.append(stdErr)
				trackCounts.append(len(copy.d[binnedPropertyName]))
				#countpercents are #cellsInBin/#totalCells
				if len(self.d[binnedPropertyName]) != 0:
					countPercents.append(100 * len(copy.d[binnedPropertyName])/len(self.d[binnedPropertyName]))
				else:
					countPercents.append(0)
				binCenters.append((minVal + maxVal)/2)

		return avgs, stdDevs, stdErrs, trackCounts, countPercents, binCenters

	# Plots getBinData. Error bars are stdError right now.
	#
	# TODO: choose stdDev or stdErr, based on getAverage settings
	# TODO: plot a high-order polynomial smooth-fit curve
	#
	# @param      self                The object
	# @param      binnedPropertyName  The binned property name
	# @param      dataPropertyName    The data property name
	# @param      settings            The settings
	#
	def plotBinData(self, binnedPropertyName, dataPropertyName, settings = TCG.PlotDefaults, workbook = None, **kwargs):
		vprint("Plotting binData: %s scanned by %s" % (dataPropertyName, binnedPropertyName))

		#plot info
		plotTitle = "%s, avgs of %s binned by %s %s" % (self.fileName, dataPropertyName, binnedPropertyName, settings['title'])
		if settings['newFig']: fig = constructFig(self, plotTitle)

		P.xlabel((self.fields[binnedPropertyName]).axisLabel)
		P.ylabel((self.fields[dataPropertyName]).axisLabel)

		avgs, stdDevs, stdErrs, trackCounts, countPercents, binCenters = self.getBinData(binnedPropertyName, dataPropertyName, settings = settings)

		if not avgs:  #(type(avgs) is not int) and len(avgs) == 0:
			vprint("Warning: No tracks to plot. Exiting plotBinData call instance.")
			return P

		P.errorbar(binCenters, avgs, yerr = stdErrs, **kwargs)

		if workbook:
			worksheetName = workbook[1]
			writeBinData(workbook[0], worksheetName, avgs, stdDevs, stdErrs, trackCounts, countPercents, binCenters)
			if not workbook[2]:
				workbook[0].close()

		if settings['show']: P.show()
		if settings['save']: savePlot(fig, plotTitle)
		return P

	# Gets histogram values
	#
	# TODO: confirm density plot options
	#
	# @param      self          The object
	# @param      propertyName  The property name
	# @param      settings      The settings
	#
	# @return     y values and corresponding bincenters
	#
	def getHistogram(self, propertyName1, propertyName2 = None, settings = TCG.PlotDefaults, workbook = None, **kwargs):

		values = self.d[propertyName1]
		data = np.array(values)
		y, binEdges = np.histogram(data, bins = settings['bins'], density = settings['norm'])
		bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
		return y, bincenters

	# Plots a histogram, using getHistogram
	#
	# @param      self       FH   The object
	# @param      propertyName  The property name
	# @param      settings      The settings
	#
	# @return     The Pylab plot
	#
	def plotHistogram(self, propertyName1, propertyName2 = None, settings = TCG.PlotDefaults, workbook = None, **kwargs):
		vprint("Plotting histogram: %s" % (propertyName1))

		#plot info
		plotTitle = "%s %s histogram%s" % (self.fileName, propertyName1, settings['title'])
		if settings['newFig']: fig = constructFig(self, plotTitle)

		normStr = {True : "normalized count", False : "count"}
		P.ylabel(normStr[settings['norm']])
		P.xlabel((self.fields[propertyName1]).axisLabel)

		#histogram generation
		y, bincenters = self.getHistogram(propertyName1, settings = settings)
		P.plot(bincenters, y, **kwargs)

		if workbook:
			writeTrackData(self, workbook[0], workbook[1])
			writeMetaData(self, workbook[0], workbook[1])
			if not workbook[2]:
				workbook[0].close()

		if settings['show']: P.show()
		if settings['save']: savePlot(fig, plotTitle)
		return P

	# Simple scatter plot
	#
	# @param      self           The object
	# @param      propertyName1  x axisLimits
	# @param      propertyName2  y axisLimits
	# @param      settings       The settings
	# @param      kwargs         The kwargs
	#
	# @return     the plot object
	#
	def plotScatter(self, propertyName1, propertyName2, settings = TCG.PlotDefaults, workbook = None, **kwargs):
		vprint("Plotting scatterplot: %s vs %s" % (propertyName1, propertyName2))

		#plot info
		plotTitle = "%s scatterplot of %s and %s, %s" % (self.fileName, propertyName1, propertyName2, settings['title'])
		if settings['newFig']: fig = constructFig(self, plotTitle)
		P.xlabel((self.fields[propertyName1]).axisLabel)
		P.ylabel((self.fields[propertyName2]).axisLabel)

		#plot generation
		xValues = self.d[propertyName1]
		yValues = self.d[propertyName2]
		P.scatter(xValues, yValues, **kwargs)

		if workbook:
			writeTrackData(self, workbook[0], workbook[1])
			writeMetaData(self, workbook[0], workbook[1])
			if not workbook[2]:
				workbook[0].close()

		if settings['show']: P.show()
		if settings['save']: savePlot(fig, plotTitle)
		return P

	##
	## END SCAN COMPATIBLE FUNCTIONS
	##

	# bin tracks based on the percentile of their propertyName value. e.g. for
	# getting avgMov of top 10% avgMov
	#
	# @param      self                 The object
	# @param      propertyName         The property name
	# @param      percentPropertyName  The percent property name
	# @param      settings             The settings
	#
	# @return     lists of histogram values, bincenters, and label lists
	#
	def getPercentHistogram(self, propertyName, percentPropertyName, settings = TCG.PlotDefaults):
		allHistogramValues = {}
		allHistogramBincenters = {}
		allHistogramLabels = {}

		#for each percent range, get histogram
		percents = settings['percents']
		for i in range(len(percents) - 1):
			tmp = deepcopy(self)
			perLow = percents[i]
			perHigh = percents[i+1]
			percentValues = TFF.selectPercentile(tmp, percentPropertyName, percentRange = [perLow, perHigh])
			y, bincenters = tmp.getHistogram(propertyName, settings = settings)
			allHistogramValues[i] = y
			allHistogramBincenters[i] = bincenters
			allHistogramLabels[i] = "%s: %d-%d%%, (%.3f to %.3f)" % (percentPropertyName[0:5], perLow, perHigh, percentValues[0], percentValues[1])

		return allHistogramValues, allHistogramBincenters, allHistogramLabels

	# plots getPercentHistogram
	def plotPercentHistogram(self, propertyName, percentPropertyName, settings = TCG.PlotDefaults, workbook = None, **kwargs):
		vprint("Plotting percent histogram: %s scanned by %s" % (propertyName, percentPropertyName))

		#plot info
		plotTitle = "%s %s histograms by %% %s; %s" % (self.fileName, propertyName, percentPropertyName, settings['title'])
		if settings['newFig']: fig = constructFig(self, plotTitle)
		normStr = {True : "normalized count", False : "count"}
		P.ylabel(normStr[settings['norm']])
		P.xlabel((self.fields[propertyName]).axisLabel)

		y, bincenters, labels = self.getPercentHistogram(propertyName, percentPropertyName, settings = settings)

		#histogram generation
		for i in range(0, len(y)):
			P.plot(bincenters[i], y[i],'-', label = labels[i])
		if settings['legend']:
			P.legend(loc = settings['legendLoc'], prop = {'size': 9})

		if workbook:
			worksheetName = workbook[1]
			writePercentHistogramData(workbook[0], worksheetName, y, bincenters, labels)
			if not workbook[2]:
				workbook[0].close()

		if settings['show']: P.show()
		if settings['save']: savePlot(fig, plotTitle)
		return P

	# generates heatmap movie of all tracks in experiment, where each dot is
	# placed at xStartPos, yStartPos. colors represent propertyName values of each track
	#
	# @param      self          The object
	# @param      propertyName  The property name
	# @param      snapshots     The snapshots
	# @param      settings      The settings
	#
	# @return     { description_of_the_return_value }
	#
	def cellVisualization(self, propertyName, snapshots = None, settings = TCG.PlotDefaults):
		print("Generating movie for %s with framerate %d" % (self.fileName, snapshots))
		#check or set snapshot value
		firstFrame = (self.axisLimits['firstFrame'])[0]
		lastFrame = (self.axisLimits['lastFrame'])[1]
		maxPossibleSnaps = lastFrame - firstFrame
		if not snapshots:
			snapshots = maxPossibleSnaps / 3
		if snapshots > maxPossibleSnaps or snapshots < 1:
			print("Invalid snapshot number for moving cell visualization.")

		#print status

		Blues = P.get_cmap('jet')
		xPositionsAllFrames = []
		yPositionsAllFrames = []
		propertyAllFrames = []

		#for each frame
		frames = np.linspace(int(firstFrame), int(lastFrame), int(snapshots))
		for frame in frames:
			frame = int(frame)
			xPositionsPerFrame = []
			yPositionsPerFrame = []
			propertyPerFrame = []
			#for all tracks
			trackIndex = 0
			propList = self.d[propertyName]
			for track in self.tracks:
				for frameNumber, x, y in zip(track.t, track.x, track.y):
					frameNumber = int(frameNumber)
					#if track exists on the current iterating frame
					if frame == frameNumber:
						#save its x,y position to array of positions for all other cells existing in this frame
						xPositionsPerFrame.append(x)
						yPositionsPerFrame.append(y)
						propertyPerFrame.append(propList[trackIndex])
				trackIndex = trackIndex + 1

			xPositionsAllFrames.append(xPositionsPerFrame)
			yPositionsAllFrames.append(yPositionsPerFrame)
			propertyAllFrames.append(propertyPerFrame)

		maxXPos = max(map(max, xPositionsAllFrames))
		maxYPos = max(map(max, yPositionsAllFrames))

		for xFrame, yFrame, cFrame, frameNum in zip(xPositionsAllFrames, yPositionsAllFrames, propertyAllFrames, frames):
			plotTitle = "%s cellVisual, %s, Frame %d, %s" % (self.fileName, propertyName, int(frameNum), settings['title'])
			fig = constructFig(self, plotTitle)
			settingsCopy = settings.copy()

			vmin, vmax, separation, colormap = getColorMapPlotSettings(self, propertyName, settings)

			sc = P.scatter(xFrame, yFrame, c = cFrame, vmin = vmin, vmax = vmax, s = separation, cmap = colormap)
			P.colorbar(sc, label = (self.fields[propertyName]).axisLabel)
			P.xlim(xmin = 0, xmax = maxXPos)
			P.xlabel('microns')
			P.ylim(ymin = 0, ymax = maxYPos)
			P.ylabel('microns')
			savePlot(fig, plotTitle)
		return

	def heatmapVisualization(self, xPropertyName, yPropertyName, colorPropertyName, settings = TCG.PlotDefaults):
		vprint("Plotting heatmapVisualization of %s, %s vs %s colored by %s" % (self.fileName, xPropertyName, yPropertyName, colorPropertyName))

		plotTitle = "%s x=%s y=%s c=%s heatmap %s" % (self.fileName, xPropertyName, yPropertyName, colorPropertyName, settings['title'])
		fig = constructFig(self, plotTitle)

		xPositionsAllFrames = []
		yPositionsAllFrames = []
		propertyAllFrames = []

		vmin, vmax, separation, colormap = getColorMapPlotSettings(self, colorPropertyName, settings)

		sc = P.scatter(self.d[xPropertyName], self.d[yPropertyName], c = self.d[colorPropertyName], vmin = vmin, vmax = vmax, s = separation, cmap = colormap)
		P.colorbar(sc, label = (self.fields[colorPropertyName]).axisLabel)

		maxXPos = max(self.d[xPropertyName])
		maxYPos = max(self.d[yPropertyName])
		minXPos = min(self.d[xPropertyName])
		minYPos = min(self.d[yPropertyName] )

		P.xlim(xmin = minXPos, xmax = maxXPos)
		P.xlabel((self.fields[xPropertyName]).axisLabel)
		P.ylim(ymin = minYPos, ymax = maxYPos)
		P.ylabel((self.fields[yPropertyName]).axisLabel)

		savePlot(fig, plotTitle)

########################
########################
class AllExperimentData():

	def __init__(self, foldername):
		self.folderPath = TCG.TRACK_FILES_IMPORT_PATH + foldername
		self.importTime = datetime.datetime.now()
		self.experiments = {}
		self.filters = {}
		#get all files from folderpath and sort in numerical order
		files = (os.listdir(self.folderPath + '/'))
		sort_nicely(files)
		#iterate over all experiment folders, and add merged TrackFile experiments
		#to AllExperimentData object
		for experimentName in files:
			fullExperimentPath = self.folderPath + '/' + experimentName
			experimentTrackFolder = importTracksFromFolder(fullExperimentPath)
			experimentFile = experimentTrackFolder.toTrackFile()
			experimentFile.importTime = self.importTime
			experimentFile.path = fullExperimentPath
			self.experiments[experimentName] = experimentFile

	def selectData(self, filters):
		#for filterInstance in filters:
		updateFilterSettings(self, filters)

		for experiment in self.experiments:
			self.experiments[experiment].selectData(filters)

	#print out all track property values
	def writeData(self, settings = TCG.PlotDefaults):
		workbook = createWorkbook("summary data")
		for experiment, v in sorted(self.experiments.items()):
			writeData(v, workbook, "")
		workbook.close()

	def compare(self, plotFunction, *args):
		vprint("Comparing %s for all experiments" % (plotFunction.__name__))

		settings = args[2]
		title = "Comparison of %s" % plotFunction.__name__
		fig = constructFig(self, title)
		settings["show"] = False
		settings["newFig"] = False
		settings["save"] = False

		legendStrings = []
		for experiment, v in sorted(self.experiments.items()):
			P = plotFunction(v, *args)
			legendStrings.append(experiment)

		P.legend(legendStrings, title="experiment", loc = settings['legendLoc'], prop = {'size': 9})
		savePlot(fig, title)
		P.close()

	def iterate(self, plotFunction, *args):
		vprint("Iterating through %s for all experiments" % (plotFunction.__name__))

		for experiment, v in sorted(self.experiments.items()):
			if len(args)==4:
				args[3][1] = experiment
			plotFunction(v, *args)


text:
from __future__ import unicode_literals, print_function
from django.db import migrations

# setColors :: [{name :: String, color :: String}]
setColors = [{'name': 'ALL Indic',        'color': 'E11D21'},
             {'name': 'ALL Iranic',       'color': 'EEA2BE'},
             {'name': 'ALL Anatolian',    'color': '654321'},
             {'name': 'Tocharian',        'color': 'C9BA9D'},
             {'name': 'ALL Balto-Slavic', 'color': 'FFFF00'},
             {'name': 'Baltic',           'color': 'FF6701'},
             {'name': 'Armenian',         'color': '7E0B80'},
             {'name': 'Albanian',         'color': '999999'},
             {'name': 'ALL Greek',        'color': '97E7FF'},
             {'name': 'ALL Germanic',     'color': '002146'},
             {'name': 'ALL Romance',      'color': '66FF00'},
             {'name': 'ALL Celtic',       'color': '006301'}]

def forwards_func(apps, schema_editor):
    LanguageBranches = apps.get_model("lexicon", "LanguageBranches")
    print('Coloring LanguageBranches..')
    for set in setColors:
        try:
            branch = LanguageBranches.objects.get(
                level1_branch_name=set['name'])
            branch.hexColor = set['color']
            branch.save()
        except:
            print('Could not color Branch: ', set['name'])

def reverse_func(apps, schema_editor):
    LanguageBranches = apps.get_model("lexicon", "LanguageBranches")
    print('Discoloring LanguageBranches..')
    for set in setColors:
        try:
            branch = LanguageBranches.objects.get(
                level1_branch_name=set['name'])
            branch.hexColor = ''
            branch.save()
        except:
            print('Could not discolor Branch: ', set['name'])

class Migration(migrations.Migration):

    dependencies = [('lexicon', '0016_languagebranches_armenian')]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]


text:
package com.ericyl.example.ui.fragment.network;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ericyl.example.R;
import com.ericyl.example.model.ui.TabInfo;
import com.ericyl.example.ui.adapter.VPHomeAdapter;
import com.ericyl.example.ui.fragment.BaseFragment;
import com.ericyl.example.ui.fragment.BlankFragment;
import com.ericyl.example.util.AppProperties;
import com.ericyl.utils.util.StringUtils;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class NetworkFragment extends BaseFragment {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout_tab)
    TabLayout layoutTab;
    @BindView(R.id.vp_content)
    ViewPager vpContent;

    private AppCompatActivity activity;

    private static final ArrayList<TabInfo> tabInfos;

    @IdRes
    private int tabIdRes = R.id.tab_volley;
    private static final String PARAM_TAB_ID_RES = "tabIdRes";

    static {
        tabInfos = new ArrayList<>();
        tabInfos.add(new TabInfo(StringUtils.getString(AppProperties.getContext(), R.string.volley), new BlankFragment(), R.id.tab_volley));
//        tabInfos.add(new TabInfo(EricylUtils.getString(AppProperties.getContext(), R.string.ksoap), new BlankFragment(), R.id.tab_ksoap));
        tabInfos.add(new TabInfo(StringUtils.getString(AppProperties.getContext(), R.string.okHttp), new BlankFragment(), R.id.tab_okhttp));
    }

    public static NetworkFragment newInstance(@IdRes int tabIdRes) {
        NetworkFragment networkFragment = new NetworkFragment();
        Bundle arguments = new Bundle();
        arguments.putInt(PARAM_TAB_ID_RES, tabIdRes);
        networkFragment.setArguments(arguments);
        return networkFragment;
    }

    @Override
    public boolean setTabIdRes(@IdRes int tabIdRes) {
        boolean flag = super.setTabIdRes(tabIdRes);
        if (flag)
            this.tabIdRes = tabIdRes;
        return flag;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_network, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (AppCompatActivity) getActivity();
    }

    @Override
    protected void init(View view, @Nullable Bundle savedInstanceState) {
        super.init(view, savedInstanceState);
        initActionBar();

        VPHomeAdapter adapter = new VPHomeAdapter(getChildFragmentManager(), tabInfos);
        vpContent.setAdapter(adapter);
        layoutTab.setupWithViewPager(vpContent);

        int position = getPositionInViewPage(tabIdRes);
        vpContent.setCurrentItem(position);
    }

    private void initActionBar() {
        activity.setSupportActionBar(toolbar);
        ActionBar actionBar = activity.getSupportActionBar();
        if (actionBar == null)
            return;
        actionBar.setTitle(R.string.network);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
    }

    private int getPositionInViewPage(@IdRes int tabIdRes) {
        for (int i = 0; i < tabInfos.size(); i++) {
            TabInfo tabInfo = tabInfos.get(i);
            if (tabInfo.getIdRes() == tabIdRes)
                return i;
        }
        return 0;
    }

}