text:
#include <cstdio>
#include <cassert>
#include <cstdlib>
#include <unistd.h>
#include "legion.h"
using namespace LegionRuntime::HighLevel;
using namespace LegionRuntime::Accessor;
using namespace LegionRuntime::Arrays;

#define ORDER 2

enum {
  TOP_LEVEL_TASK_ID,
  SPMD_TASK_ID,
  INIT_FIELD_TASK_ID,
  STENCIL_TASK_ID,
  CHECK_FIELD_TASK_ID,
};

enum {
  FID_VAL,
  FID_DERIV,
  FID_GHOST,
};

enum {
  GHOST_LEFT,
  GHOST_RIGHT,
};

struct SPMDArgs {
public:
  PhaseBarrier notify_ready[2];
  PhaseBarrier notify_empty[2];
  PhaseBarrier wait_ready[2];
  PhaseBarrier wait_empty[2];
  int num_elements;
  int num_subregions;
  int num_steps;
};

void top_level_task(const Task *task,
                    const std::vector<PhysicalRegion> &regions,
                    Context ctx, HighLevelRuntime *runtime)
{
  int num_elements = 1024;
  int num_subregions = 4;
  int num_steps = 10;
  // Check for any command line arguments
  {
      const InputArgs &command_args = HighLevelRuntime::get_input_args();
    for (int i = 1; i < command_args.argc; i++)
    {
      if (!strcmp(command_args.argv[i],"-n"))
        num_elements = atoi(command_args.argv[++i]);
      if (!strcmp(command_args.argv[i],"-b"))
        num_subregions = atoi(command_args.argv[++i]);
      if (!strcmp(command_args.argv[i],"-s"))
        num_steps = atoi(command_args.argv[++i]);
    }
  }
  // This algorithm needs at least two sub-regions to work
  assert(num_subregions > 1);
  printf("Running stencil computation for %d elements for %d steps...\n",
          num_elements, num_steps);
  printf("Partitioning data into %d sub-regions...\n", num_subregions);

  // we're going to use a must epoch launcher, so we need at least as many
  //  processors in our system as we have subregions - check that now
  std::set<Processor> all_procs;
  Realm::Machine::get_machine().get_all_processors(all_procs);
  int num_loc_procs = 0;
  for(std::set<Processor>::const_iterator it = all_procs.begin();
      it != all_procs.end();
      it++)
    if((*it).kind() == Processor::LOC_PROC)
      num_loc_procs++;

  if(num_loc_procs < num_subregions) {
    printf("FATAL ERROR: This test uses a must epoch launcher, which requires\n");
    printf("  a separate Realm processor for each subregion.  %d of the necessary\n",
	   num_loc_procs);
    printf("  %d are available.  Please rerun with '-ll:cpu %d'.\n",
	   num_subregions, num_subregions);
    exit(1);
  }

  // For this example we'll create a single index space tree, but we
  // will make different logical regions from this index space.  The
  // index space will have two levels of partitioning.  One level for
  // describing the partitioning into pieces, and then a second level
  // for capturing partitioning to describe ghost regions.
  Rect<1> elem_rect(Point<1>(0),Point<1>(num_elements-1));
  IndexSpace is = runtime->create_index_space(ctx,
                          Domain::from_rect<1>(elem_rect));
  runtime->attach_name(is, "is");

  FieldSpace ghost_fs = runtime->create_field_space(ctx);
  runtime->attach_name(ghost_fs, "ghost_fs");
  {
    FieldAllocator allocator =
      runtime->create_field_allocator(ctx, ghost_fs);
    allocator.allocate_field(sizeof(double),FID_GHOST);
    runtime->attach_name(ghost_fs, FID_GHOST, "GHOST");
  }

  Rect<1> color_bounds(Point<1>(0),Point<1>(num_subregions-1));
  Domain color_domain = Domain::from_rect<1>(color_bounds);

  // Create the partition for pieces
  IndexPartition disjoint_ip;
  {
    const int lower_bound = num_elements/num_subregions;
    const int upper_bound = lower_bound+1;
    const int number_small = num_subregions - (num_elements % num_subregions);
    DomainColoring disjoint_coloring;
    int index = 0;
    for (int color = 0; color < num_subregions; color++)
    {
      int num_elmts = color < number_small ? lower_bound : upper_bound;
      assert((index+num_elmts) <= num_elements);
      Rect<1> subrect(Point<1>(index),Point<1>(index+num_elmts-1));
      disjoint_coloring[color] = Domain::from_rect<1>(subrect);
      index += num_elmts;
    }
    disjoint_ip = runtime->create_index_partition(ctx, is, color_domain,
                                    disjoint_coloring, true/*disjoint*/);
  }
  runtime->attach_name(disjoint_ip, "disjoint_ip");
  // Now iterate over each of the sub-regions and make the ghost partitions
  Rect<1> ghost_bounds(Point<1>((int)GHOST_LEFT),Point<1>((int)GHOST_RIGHT));
  Domain ghost_domain = Domain::from_rect<1>(ghost_bounds);
  std::vector<LogicalRegion> ghost_left;
  std::vector<LogicalRegion> ghost_right;
  char buf[32]; const char* parts[2] = {"L", "R"};
  for (int color = 0; color < num_subregions; color++)
  {
    // Get each of the subspaces
    IndexSpace subspace = runtime->get_index_subspace(ctx, disjoint_ip, color);
    sprintf(buf, "disjoint_subspace_%d", color);
    runtime->attach_name(subspace, buf);
    Domain dom = runtime->get_index_space_domain(ctx, subspace);
    Rect<1> rect = dom.get_rect<1>();
    // Make two sub-regions, one on the left, and one on the right
    DomainColoring ghost_coloring;
    Rect<1> left(rect.lo, rect.lo[0]+(ORDER-1));
    ghost_coloring[GHOST_LEFT] = Domain::from_rect<1>(left);
    Rect<1> right(rect.hi[0]-(ORDER-1),rect.hi);
    ghost_coloring[GHOST_RIGHT] = Domain::from_rect<1>(right);
    IndexPartition ghost_ip =
      runtime->create_index_partition(ctx, subspace, ghost_domain,
                                      ghost_coloring, true/*disjoint*/);
    sprintf(buf, "ghost_ip_%d", color);
    runtime->attach_name(ghost_ip, buf);
    // Make explicit logical regions for each of the ghost spaces
    for (int idx = GHOST_LEFT; idx <= GHOST_RIGHT; idx++)
    {
      IndexSpace ghost_space = runtime->get_index_subspace(ctx, ghost_ip, idx);
      LogicalRegion ghost_lr =
        runtime->create_logical_region(ctx, ghost_space, ghost_fs);
      sprintf(buf, "ghost_lr_%d_%s", color, parts[idx]);
      runtime->attach_name(ghost_lr, buf);
      if (idx == GHOST_LEFT)
        ghost_left.push_back(ghost_lr);
      else
        ghost_right.push_back(ghost_lr);
    }
  }

  // Create all of the phase barriers for this computation
  std::vector<PhaseBarrier> left_ready_barriers;
  std::vector<PhaseBarrier> left_empty_barriers;
  std::vector<PhaseBarrier> right_ready_barriers;
  std::vector<PhaseBarrier> right_empty_barriers;
  for (int color = 0; color < num_subregions; color++)
  {
    left_ready_barriers.push_back(runtime->create_phase_barrier(ctx, 1));
    left_empty_barriers.push_back(runtime->create_phase_barrier(ctx, 1));
    right_ready_barriers.push_back(runtime->create_phase_barrier(ctx, 1));
    right_empty_barriers.push_back(runtime->create_phase_barrier(ctx, 1));
  }

  // In order to guarantee that all of our spmd_tasks execute in parallel
  // we have to use a must epoch launcher.  This instructs the runtime
  // to check that all of the operations in the must epoch are capable of
  // executing in parallel making it possible for them to synchronize using
  // named barriers with potential deadlock.  If for some reason they
  // cannot run in parallel, the runtime will report an error and indicate
  // the cause of it.
  {
    MustEpochLauncher must_epoch_launcher;
    // Need a separate array for storing these until we call the runtime
    std::vector<SPMDArgs> args(num_subregions);
    // For each of our parallel tasks launch off a task with the ghost regions
    // for its neighbors as well as our ghost regions and the  necessary phase
    // barriers.  Assume periodic boundary conditions.
    for (int color = 0; color < num_subregions; color++)
    {
      args[color].notify_ready[GHOST_LEFT] = left_ready_barriers[color];
      args[color].notify_ready[GHOST_RIGHT] = right_ready_barriers[color];
      args[color].wait_empty[GHOST_LEFT] = left_empty_barriers[color];
      args[color].wait_empty[GHOST_RIGHT] = right_empty_barriers[color];
      if (color == 0)
      {
        args[color].wait_ready[GHOST_LEFT] = right_ready_barriers[num_subregions-1];
        args[color].notify_empty[GHOST_LEFT] = right_empty_barriers[num_subregions-1];
      }
      else
      {
        args[color].wait_ready[GHOST_LEFT] = right_ready_barriers[color-1];
        args[color].notify_empty[GHOST_LEFT] = right_empty_barriers[color-1];
      }
      if (color == (num_subregions-1))
      {
        args[color].wait_ready[GHOST_RIGHT] = left_ready_barriers[0];
        args[color].notify_empty[GHOST_RIGHT] = left_empty_barriers[0];
      }
      else
      {
        args[color].wait_ready[GHOST_RIGHT] = left_ready_barriers[color+1];
        args[color].notify_empty[GHOST_RIGHT] = left_empty_barriers[color+1];
      }
      args[color].num_elements = num_elements;
      args[color].num_subregions = num_subregions;
      args[color].num_steps = num_steps;

      TaskLauncher spmd_launcher(SPMD_TASK_ID,
                        TaskArgument(&args[color], sizeof(SPMDArgs)));
      // Our Left
      spmd_launcher.add_region_requirement(
          RegionRequirement(ghost_left[color], READ_WRITE,
                            SIMULTANEOUS, ghost_left[color]));
      spmd_launcher.region_requirements[0].flags = NO_ACCESS_FLAG;
      // Our Right
      spmd_launcher.add_region_requirement(
          RegionRequirement(ghost_right[color], READ_WRITE,
                            SIMULTANEOUS, ghost_right[color]));
      spmd_launcher.region_requirements[1].flags = NO_ACCESS_FLAG;
      // Left Ghost
      if (color == 0)
        spmd_launcher.add_region_requirement(
            RegionRequirement(ghost_right[num_subregions-1], READ_ONLY,
                              SIMULTANEOUS, ghost_right[num_subregions-1]));
      else
        spmd_launcher.add_region_requirement(
            RegionRequirement(ghost_right[color-1], READ_ONLY,
                              SIMULTANEOUS, ghost_right[color-1]));
      // Right Ghost
      if (color == (num_subregions-1))
        spmd_launcher.add_region_requirement(
            RegionRequirement(ghost_left[0], READ_ONLY,
                              SIMULTANEOUS, ghost_left[0]));
      else
        spmd_launcher.add_region_requirement(
            RegionRequirement(ghost_left[color+1], READ_ONLY,
                              SIMULTANEOUS, ghost_left[color+1]));
      for (unsigned idx = 0; idx < 4; idx++)
        spmd_launcher.add_field(idx, FID_GHOST);

      spmd_launcher.add_index_requirement(IndexSpaceRequirement(is,
								NO_MEMORY,
								is));

      DomainPoint point(color);
      must_epoch_launcher.add_single_task(point, spmd_launcher);
    }
    FutureMap fm = runtime->execute_must_epoch(ctx, must_epoch_launcher);
    // wait for completion at least
    fm.wait_all_results();

    printf("Test completed.\n");
  }

  // Clean up our mess when we are done
  for (unsigned idx = 0; idx < ghost_left.size(); idx++)
    runtime->destroy_logical_region(ctx, ghost_left[idx]);
  for (unsigned idx = 0; idx < ghost_right.size(); idx++)
    runtime->destroy_logical_region(ctx, ghost_right[idx]);
  for (unsigned idx = 0; idx < left_ready_barriers.size(); idx++)
    runtime->destroy_phase_barrier(ctx, left_ready_barriers[idx]);
  for (unsigned idx = 0; idx < left_empty_barriers.size(); idx++)
    runtime->destroy_phase_barrier(ctx, left_empty_barriers[idx]);
  for (unsigned idx = 0; idx < right_ready_barriers.size(); idx++)
    runtime->destroy_phase_barrier(ctx, right_ready_barriers[idx]);
  for (unsigned idx = 0; idx < right_empty_barriers.size(); idx++)
    runtime->destroy_phase_barrier(ctx, right_empty_barriers[idx]);
  ghost_left.clear();
  ghost_right.clear();
  left_ready_barriers.clear();
  left_empty_barriers.clear();
  right_ready_barriers.clear();
  right_empty_barriers.clear();
  runtime->destroy_index_space(ctx, is);
  runtime->destroy_field_space(ctx, ghost_fs);
}

void spmd_task(const Task *task,
               const std::vector<PhysicalRegion> &regions,
               Context ctx, HighLevelRuntime *runtime)
{
  // Unmap all the regions we were given since we won't actually use them
  runtime->unmap_all_regions(ctx);

  SPMDArgs *args = (SPMDArgs*)task->args;
  LogicalRegion neighbor_lr[2];
  neighbor_lr[GHOST_LEFT] = task->regions[0].region;
  neighbor_lr[GHOST_RIGHT] = task->regions[1].region;
  LogicalRegion ghosts_lr[2];
  ghosts_lr[GHOST_LEFT] = task->regions[2].region;
  ghosts_lr[GHOST_RIGHT] = task->regions[3].region;
  // Create the logical region that we'll use for our data
  FieldSpace local_fs;
  LogicalRegion local_lr;
  {
    char buf[16];
    IndexSpace ghost_is = task->regions[0].region.get_index_space();
    IndexPartition ghost_ip = runtime->get_parent_index_partition(ctx, ghost_is);
    IndexSpace local_is = runtime->get_parent_index_space(ctx, ghost_ip);
    local_fs = runtime->create_field_space(ctx);
    sprintf(buf, "local_fs_%lld", task->index_point.get_index());
    runtime->attach_name(local_fs, buf);
    FieldAllocator allocator =
      runtime->create_field_allocator(ctx, local_fs);
    allocator.allocate_field(sizeof(double),FID_VAL);
    runtime->attach_name(local_fs, FID_VAL, "VAL");
    allocator.allocate_field(sizeof(double),FID_DERIV);
    runtime->attach_name(local_fs, FID_DERIV, "DERIV");
    local_lr = runtime->create_logical_region(ctx, local_is, local_fs);
    sprintf(buf, "local_lr_%lld", task->index_point.get_index());
    runtime->attach_name(local_lr, buf);
  }
  // Run a bunch of steps
  for (int s = 0; s < args->num_steps; s++)
  {
    // Launch a task to initialize our field with some data
    TaskLauncher init_launcher(INIT_FIELD_TASK_ID,
                                TaskArgument(NULL, 0));
    init_launcher.add_region_requirement(
        RegionRequirement(local_lr, WRITE_DISCARD,
                          EXCLUSIVE, local_lr));
    init_launcher.add_field(0, FID_VAL);
    runtime->execute_task(ctx, init_launcher);

    // Issue explicit region-to-region copies
    for (unsigned idx = GHOST_LEFT; idx <= GHOST_RIGHT; idx++)
    {
      CopyLauncher copy_launcher;
      copy_launcher.add_copy_requirements(
          RegionRequirement(local_lr, READ_ONLY,
                            EXCLUSIVE, local_lr),
          RegionRequirement(neighbor_lr[idx], WRITE_DISCARD,
                            EXCLUSIVE, neighbor_lr[idx]));
      copy_launcher.add_src_field(0, FID_VAL);
      copy_launcher.add_dst_field(0, FID_GHOST);
      // It's not safe to issue the copy until we know
      // that the destination instance is empty. Only
      // need to do this after the first iteration.
      if (s > 0) {
	// advance the barrier first - we're waiting for the next phase
	//  to start
        args->wait_empty[idx] =
          runtime->advance_phase_barrier(ctx, args->wait_empty[idx]);
        copy_launcher.add_wait_barrier(args->wait_empty[idx]);
      }
      // When we are done with the copy, signal that the
      // destination instance is now ready
      copy_launcher.add_arrival_barrier(args->notify_ready[idx]);
      runtime->issue_copy_operation(ctx, copy_launcher);
      // Once we've issued our copy operation, advance both of
      // the barriers to the next generation.
      args->notify_ready[idx] =
        runtime->advance_phase_barrier(ctx, args->notify_ready[idx]);
    }

    // Acquire coherence on our left and right ghost regions
    for (unsigned idx = GHOST_LEFT; idx <= GHOST_RIGHT; idx++)
    {
      AcquireLauncher acquire_launcher(ghosts_lr[idx],
                                       ghosts_lr[idx],
                                       regions[2+idx]);
      acquire_launcher.add_field(FID_GHOST);
      // The acquire operation needs to wait for the data to
      // be ready to consume, so wait on the next phase of the
      // ready barrier.
      args->wait_ready[idx] =
        runtime->advance_phase_barrier(ctx, args->wait_ready[idx]);
      acquire_launcher.add_wait_barrier(args->wait_ready[idx]);
      runtime->issue_acquire(ctx, acquire_launcher);
    }

    // Run the stencil computation
    TaskLauncher stencil_launcher(STENCIL_TASK_ID,
                                  TaskArgument(NULL, 0));
    stencil_launcher.add_region_requirement(
        RegionRequirement(local_lr, WRITE_DISCARD, EXCLUSIVE, local_lr));
    stencil_launcher.add_field(0, FID_DERIV);
    stencil_launcher.add_region_requirement(
        RegionRequirement(local_lr, READ_ONLY, EXCLUSIVE, local_lr));
    stencil_launcher.add_field(1, FID_VAL);
    for (unsigned idx = GHOST_LEFT; idx <= GHOST_RIGHT; idx++)
    {
      stencil_launcher.add_region_requirement(
          RegionRequirement(ghosts_lr[idx], READ_ONLY, EXCLUSIVE, ghosts_lr[idx]));
      stencil_launcher.add_field(idx+2, FID_GHOST);
    }
    runtime->execute_task(ctx, stencil_launcher);

    // Release coherence on our left and right ghost regions
    for (unsigned idx = GHOST_LEFT; idx <= GHOST_RIGHT; idx++)
    {
      ReleaseLauncher release_launcher(ghosts_lr[idx],
                                       ghosts_lr[idx],
                                       regions[2+idx]);
      release_launcher.add_field(FID_GHOST);
      // On all but the last iteration we need to signal that
      // we have now consumed the ghost instances and it is
      // safe to issue the next copy.
      if (s < (args->num_steps-1))
        release_launcher.add_arrival_barrier(args->notify_empty[idx]);
      runtime->issue_release(ctx, release_launcher);
      if (s < (args->num_steps-1))
        args->notify_empty[idx] =
          runtime->advance_phase_barrier(ctx, args->notify_empty[idx]);
    }
  }

  // now check our results
  {
    TaskLauncher check_launcher(CHECK_FIELD_TASK_ID,
				TaskArgument(args, sizeof(SPMDArgs)));
    check_launcher.add_region_requirement(
			  RegionRequirement(local_lr, READ_ONLY,
                          EXCLUSIVE, local_lr));
    check_launcher.add_field(0, FID_DERIV);
    Future f = runtime->execute_task(ctx, check_launcher);
    int errors = f.get_result<int>();
    if(errors > 0) {
      printf("Errors detected in check task!\n");
      sleep(1); // let other tasks also report errors if they wish
      exit(1);
    }
  }

  runtime->destroy_logical_region(ctx, local_lr);
  runtime->destroy_field_space(ctx, local_fs);
}

void init_field_task(const Task *task,
                     const std::vector<PhysicalRegion> &regions,
                     Context ctx, HighLevelRuntime *runtime)
{
  assert(regions.size() == 1);
  assert(task->regions.size() == 1);
  assert(task->regions[0].privilege_fields.size() == 1);

  FieldID fid = *(task->regions[0].privilege_fields.begin());

  RegionAccessor<AccessorType::Generic, double> acc =
    regions[0].get_field_accessor(fid).typeify<double>();

  Domain dom = runtime->get_index_space_domain(ctx,
      task->regions[0].region.get_index_space());
  Rect<1> rect = dom.get_rect<1>();
  for (GenericPointInRectIterator<1> pir(rect); pir; pir++)
  {
    // use a ramp with little ripples
    const int ripple_period = 4;
    const double ripple[ripple_period] = { 0, 0.25, 0, -0.25 };

    double value = (double)(pir.p[0]) + ripple[pir.p[0] % ripple_period];
    acc.write(DomainPoint::from_point<1>(pir.p), value);
  }
}

void stencil_field_task(const Task *task,
                        const std::vector<PhysicalRegion> &regions,
                        Context ctx, HighLevelRuntime *runtime)
{
  assert(regions.size() == 4);
  assert(task->regions.size() == 4);
  for (int idx = 0; idx < 4; idx++)
    assert(task->regions[idx].privilege_fields.size() == 1);

  FieldID write_fid = *(task->regions[0].privilege_fields.begin());
  FieldID read_fid = *(task->regions[1].privilege_fields.begin());
  FieldID ghost_fid = *(task->regions[2].privilege_fields.begin());

  RegionAccessor<AccessorType::Generic, double> write_acc =
    regions[0].get_field_accessor(write_fid).typeify<double>();
  RegionAccessor<AccessorType::Generic, double> read_acc =
    regions[1].get_field_accessor(read_fid).typeify<double>();
  RegionAccessor<AccessorType::Generic, double> left_ghost_acc =
    regions[2].get_field_accessor(ghost_fid).typeify<double>();
  RegionAccessor<AccessorType::Generic, double> right_ghost_acc =
    regions[3].get_field_accessor(ghost_fid).typeify<double>();

  Domain main_dom = runtime->get_index_space_domain(ctx,
      task->regions[0].region.get_index_space());
  Domain left_dom = runtime->get_index_space_domain(ctx,
      task->regions[2].region.get_index_space());
  Domain right_dom = runtime->get_index_space_domain(ctx,
      task->regions[3].region.get_index_space());

  Rect<1> left_rect = left_dom.get_rect<1>();
  Rect<1> right_rect = right_dom.get_rect<1>();
  Rect<1> main_rect = main_dom.get_rect<1>();

  double window[2*ORDER+1];

  // we're going to perform the stencil computation with 4 iterators: read iterators
  //  for the left, main, and right rectangles, and a write iterator for the main
  //  rectangle (the read and write iterators for the main rectangle will effectively
  //  be offset by ORDER
  GenericPointInRectIterator<1> pir_left(left_rect);
  GenericPointInRectIterator<1> pir_main_read(main_rect);
  GenericPointInRectIterator<1> pir_main_write(main_rect);
  GenericPointInRectIterator<1> pir_right(right_rect);

  // Prime the window with the left data and the first ORDER elements of main
  for (int i = 0; i < ORDER; i++)
  {
    window[i] = left_ghost_acc.read(DomainPoint::from_point<1>((pir_left++).p));
    window[i + ORDER] = read_acc.read(DomainPoint::from_point<1>((pir_main_read++).p));
  }

  // now iterate over the main rectangle's write value, pulling from the right ghost
  //  data once the main read iterator is exhausted
  while (pir_main_write)
  {
    if (pir_main_read)
      window[2 * ORDER] = read_acc.read(DomainPoint::from_point<1>((pir_main_read++).p));
    else
      window[2 * ORDER] = right_ghost_acc.read(DomainPoint::from_point<1>((pir_right++).p));

    // only have calculation for ORDER == 2
    double deriv;
    switch(ORDER)
    {
      case 2: {
	deriv = (window[0] - 8.0 * window[1] +
		 8.0 * window[3] - window[4]);
#ifdef DEBUG_STENCIL_CALC
	printf("A: [%d] %g %g %g %g %g -> %g\n",
	       pir_main_write.p[0],
	       window[0],
	       window[1],
	       window[2],
	       window[3],
	       window[4],
	       deriv);
#endif
	break;
      }

      default: assert(0);
    }

    write_acc.write(DomainPoint::from_point<1>((pir_main_write++).p),
		    deriv);

    // slide the window for the next point
    for (int j = 0; j < (2*ORDER); j++)
      window[j] = window[j+1];
  }

  // check that we exhausted all the iterators
  assert(!pir_left);
  assert(!pir_main_read);
  assert(!pir_main_write);
  assert(!pir_right);
}

int check_field_task(const Task *task,
		     const std::vector<PhysicalRegion> &regions,
		     Context ctx, HighLevelRuntime *runtime)
{
  SPMDArgs *args = (SPMDArgs*)task->args;

  assert(regions.size() == 1);
  assert(task->regions.size() == 1);
  assert(task->regions[0].privilege_fields.size() == 1);

  FieldID fid = *(task->regions[0].privilege_fields.begin());

  RegionAccessor<AccessorType::Generic, double> acc =
    regions[0].get_field_accessor(fid).typeify<double>();

  Domain dom = runtime->get_index_space_domain(ctx,
      task->regions[0].region.get_index_space());
  Rect<1> rect = dom.get_rect<1>();
  int errors = 0;
  for (GenericPointInRectIterator<1> pir(rect); pir; pir++)
  {
    // the derivative of a ramp with ripples is a constant function with ripples
    const int ripple_period = 4;
    const double deriv_ripple[ripple_period] = { 4.0, 0, -4.0, 0 };
    double exp_value = 12.0 + deriv_ripple[pir.p[0] % ripple_period];

    // correct for the wraparound cases
    if(pir.p[0] < ORDER) {
      // again only actually supporting ORDER == 2
      assert(ORDER == 2);
      if(pir.p[0] == 0) exp_value += -7.0 * args->num_elements;
      if(pir.p[1] == 1) exp_value += 1.0 * args->num_elements;
    }
    if(pir.p[0] >= (args->num_elements - ORDER)) {
      // again only actually supporting ORDER == 2
      assert(ORDER == 2);
      if(pir.p[0] == (args->num_elements - 1)) exp_value += -7.0 * args->num_elements;
      if(pir.p[1] == (args->num_elements - 2)) exp_value += 1.0 * args->num_elements;
    }

    double act_value = acc.read(DomainPoint::from_point<1>(pir.p));

    // polarity is important here - comparisons with NaN always return false
    bool ok = ((exp_value < 0) ? ((-act_value >= 0.99 * -exp_value) &&
				  (-act_value <= 1.01 * -exp_value)) :
	       (exp_value > 0) ? ((act_value >= 0.99 * exp_value) &&
				  (act_value <= 1.01 * exp_value)) :
 	                         (act_value == 0));

    if(!ok) {
      printf("ERROR: check for location %lld failed: expected=%g, actual=%g\n",
	     pir.p[0], exp_value, act_value);
      errors++;
    }
  }

  return errors;
}

int main(int argc, char **argv)
{
  HighLevelRuntime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
  HighLevelRuntime::register_legion_task<top_level_task>(TOP_LEVEL_TASK_ID,
      Processor::LOC_PROC, true/*single*/, false/*index*/,
      AUTO_GENERATE_ID, TaskConfigOptions(), "top_level");
  HighLevelRuntime::register_legion_task<spmd_task>(SPMD_TASK_ID,
      Processor::LOC_PROC, true/*single*/, true/*single*/,
      AUTO_GENERATE_ID, TaskConfigOptions(), "spmd");
  HighLevelRuntime::register_legion_task<init_field_task>(INIT_FIELD_TASK_ID,
      Processor::LOC_PROC, true/*single*/, true/*single*/,
      AUTO_GENERATE_ID, TaskConfigOptions(true), "init");
  HighLevelRuntime::register_legion_task<stencil_field_task>(STENCIL_TASK_ID,
      Processor::LOC_PROC, true/*single*/, true/*single*/,
      AUTO_GENERATE_ID, TaskConfigOptions(true), "stencil");
  HighLevelRuntime::register_legion_task<int, check_field_task>(CHECK_FIELD_TASK_ID,
      Processor::LOC_PROC, true/*single*/, true/*single*/,
      AUTO_GENERATE_ID, TaskConfigOptions(true), "check");

  return HighLevelRuntime::start(argc, argv);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.sprylab.android.texturevideoview</groupId>
        <artifactId>parent</artifactId>
        <version>1.0.2-SNAPSHOT</version>
    </parent>

    <artifactId>sample</artifactId>
    <packaging>apk</packaging>

    <name>TextureVideoView for Android - Sample</name>

    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>com.sprylab.android.texturevideoview</groupId>
            <artifactId>texturevideoview</artifactId>
            <version>${project.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

redpajama_set_name: RedPajamaGithub


text:
import { Injectable } from '@angular/core';
import { Page } from 'app/model/Page';
import { ListItem } from 'app/model/ListItem';
import { ResearchHubApiService, SearchResultsParams } from 'app/services/research-hub-api.service';
import { map ,  delay } from 'rxjs/operators';
import { forkJoin ,  BehaviorSubject, Observable } from 'rxjs';

@Injectable()
export class SearchResultsComponentService {

  private resultsSubject: BehaviorSubject<Page<ListItem>>;
  public results$ : Observable<Page<ListItem>>;
  private resultsLoadingSubject : BehaviorSubject<boolean>;
  public resultsLoading$ : Observable<boolean>;

  private categorySubject: BehaviorSubject<Array<Object>>;
  public resultsCategories$ : Observable<Array<Object>>;
  private categoriesLoadingSubject : BehaviorSubject<boolean>;
  public categoriesLoading$ : Observable<boolean>;

  constructor(public apiService: ResearchHubApiService) {
    this.initialiseSubjects();
  }

  public searchWithParams(params: SearchResultsParams){
    this.resultsLoadingSubject.next(true);
    const resultsSub = this.updateSearchResults(params)
      .pipe(delay(250)) // Add delay to make result changes obvious.
      .subscribe(page =>
                 {
                   this.resultsSubject.next(page);
                   this.resultsLoadingSubject.next(false);
                   resultsSub.unsubscribe();
                 }
                );

    this.categoriesLoadingSubject.next(true);
    const categorySub = this.updateSearchResultsCategories(params)
      .subscribe(categories => {
        this.categoriesLoadingSubject.next(false);
        this.categorySubject.next(categories);
        categorySub.unsubscribe();
      });
  }

  initialiseSubjects(){
    // We initialise the Subjects with an empty initial value.
    this.resultsSubject = new BehaviorSubject<Page<ListItem>>(<Page<ListItem>>{});
    this.results$ = this.resultsSubject.asObservable();

    this.resultsLoadingSubject = new BehaviorSubject<boolean>(false);
    this.resultsLoading$ = this.resultsLoadingSubject.asObservable();

    this.categorySubject = new BehaviorSubject<Array<Object>>([]);
    this.resultsCategories$ = this.categorySubject.asObservable();

    this.categoriesLoadingSubject = new BehaviorSubject<boolean>(false);
    this.categoriesLoading$ = this.categoriesLoadingSubject.asObservable();
  }

  private updateSearchResults(params: SearchResultsParams){
    return this.apiService.getSearchResults(params);
  }

  private updateSearchResultsCategories(params: SearchResultsParams){
    const categoryList = {};
    const categoryListArray = [];
    return  this.apiService.getSearchResultsCategories(params).pipe(
      map(res => {
        for (let i = 0; i < res['content'].length; i++) {
          for (let j = 0; j < res['content'][i]['categories'].length; j++) {
            categoryList[res['content'][i]['categories'][j]] = categoryList[res['content'][i]['categories'][j]] === undefined ? 1 : categoryList[res['content'][i]['categories'][j]] + 1;
          }
        }
        // Convert JSON to array for Angular *ngFor
        for (const categoryTuple in categoryList) {
          categoryListArray.push([categoryTuple, categoryList[categoryTuple]]);
        }
        return categoryListArray;
      })
    );
  }

}


text:
using Abp.AspNetCore;
using Abp.Castle.Logging.Log4Net;
using Abp.Extensions;
using Castle.Facilities.Logging;
using KingYSoft.Foretch.Authentication.JwtBearer;
using KingYSoft.Foretch.Configuration;
using KingYSoft.Foretch.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Linq;

#if FEATURE_SIGNALR
using Owin;
using Microsoft.Owin.Cors;
using Microsoft.AspNet.SignalR;
using MyProject.Owin;
using Abp.Owin;
#endif

namespace KingYSoft.Foretch.Web.Host.Startup
{
    public class Startup
    {
        private const string DefaultCorsPolicyName = "localhost";

        private readonly IConfigurationRoot _appConfiguration;

        public Startup(IHostingEnvironment env)
        {
            _appConfiguration = env.GetAppConfiguration();
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // MVC
            services.AddMvc(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory(DefaultCorsPolicyName));
            });

            IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, _appConfiguration);

            // Configure CORS for angular2 UI
            services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                    builder
                        .WithOrigins(_appConfiguration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries)
                                                                         .Select(o => o.RemovePostFix("/"))
                                                                         .ToArray())
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Title = "MyProject API", Version = "v1" });
                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                // Assign scope requirements to operations based on AuthorizeAttribute
                options.OperationFilter<SecurityRequirementsOperationFilter>();
            });

            // Configure Abp and Dependency Injection
            return services.AddAbp<ForetchWebHostModule>(options =>
            {
                // Configure Log4Net logging
                options.IocManager.IocContainer.AddFacility<LoggingFacility>(
                    f => f.UseAbpLog4Net().WithConfig("log4net.config")
                );
            });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.UseAbp(); // Initializes ABP framework.

            app.UseCors(DefaultCorsPolicyName); // Enable CORS!

            app.UseStaticFiles();

            app.UseAuthentication();
            app.UseJwtTokenMiddleware();

#if FEATURE_SIGNALR
            // Integrate to OWIN
            app.UseAppBuilder(ConfigureOwinServices);
#endif

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "defaultWithArea",
                    template: "{area}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();
            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                options.InjectOnCompleteJavaScript("/swagger/ui/abp.js");
                options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js");
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "MyProject API V1");
            }); // URL: /swagger
        }

#if FEATURE_SIGNALR
        private static void ConfigureOwinServices(IAppBuilder app)
        {
            app.Properties["host.AppName"] = "MyProject";

            app.UseAbp();

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                };
                map.RunSignalR(hubConfiguration);
            });
        }
#endif
    }
}


text:
package org.mindtrails.domain;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.mindtrails.domain.piPlayer.InterpretationReport;
import org.mindtrails.domain.piPlayer.TrialJson;
import junit.framework.Assert;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

/**
 * Created with IntelliJ IDEA.
 * User: dan
 * Date: 3/20/14
 * Time: 2:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class TrialJsonTest {

    // Here is a typical Json string, as provided by the PiPlayer
    public static final String JSON_STRING = "{\"log_serial\":22,\"trial_id\":24,\"name\":\"IAT\",\"responseHandle\":\"left\",\"latency\":897302,\"stimuli\":[\"Good Words\"],\"media\":[\"Happy\"],\"data\":{\"score\":0,\"block\":2,\"left1\":\"Good Words\",\"right1\":\"Bad Words\",\"conditioning\":\"Good Words/Bad Words\"}}";

    public static final String JSON_INT = "{\"log_serial\":3,\"trial_id\":\"trial_39\"," +
            "\"name\":\"posneg\"," +
            "\"responseHandle\":\"answered\"," +
            "\"latency\":3225,\"stimuli\":[\"error\"," +
            "\"yesno\",\"paragraph\",\"question\"]," +
            "\"media\":[\"X\",\"Type \\\"y\\\" for Yes, and \\\"n\\\" for No.\",\"
<%= stimulusData.statement %><%= trialData.positive ? stimulusData.positiveWord : stimulusData.negativeWord %>
\",\"
Would you expect to feel uncomfortable if others look at your work?
\"]," +
            "\"data\":{\n" +
            "    \"positive\":false, \n" +
            "    \"correctOnLetter\":true, \n" +
            "    \"word\":\"ter[r]ible.\", \n" +
            "    \"paragraph\": \"You are out to dinner on a date. As you lo... is ter[r]ible.\", \n" +
            "    \"letter_latency\":6702, \n" +
            "    \"first_letter_latency\":6201, \n" +
            "    \"correctOnQuestion\":false, \n" +
            "    \"first_question_latency\":3498, \n" +
            "    \"question\":\"Is it fun to experience a little uncertainty on a date?\" , \n" +
            "    \"question_latency\":9985}}}";

public static TrialJson fromJson(String text) throws IllegalArgumentException {
        ObjectMapper mapper = new ObjectMapper();
        TrialJson    trialJson   = new TrialJson();
        try {
            trialJson = mapper.readValue(text, TrialJson.class);
        } catch (JsonMappingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (JsonParseException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return trialJson;
    }

    @Test
    public void TrialFromJsonContainsCorrectData() {

        TrialJson trial = fromJson(JSON_STRING);

        Assert.assertEquals(22, trial.getLog_serial());
        Assert.assertEquals(897302, trial.getLatency());
        Assert.assertEquals("Good Words", trial.getStimuli().get(0));
        Assert.assertEquals("0", trial.getData().get("score"));
    }

    @Test
    public void testInterpretationReport() {

        TrialJson trial = fromJson(JSON_INT);
        System.out.print("The trial is:" + trial.toString());
        InterpretationReport report;
        report = trial.toInterpretationReport();

        assertEquals("false", report.getPositive());
        assertEquals("true", report.getLetterCorrect());
        assertEquals("ter[r]ible.", report.getWord());
        assertEquals("You are out to dinner on a date. As you lo... is ter[r]ible.", report.getParagraph());
        assertEquals("6702", report.getLetterLatency());
        assertEquals("6201", report.getFirstLetterLatency());
        assertEquals("false", report.getQuestionCorrect());
        assertEquals("3498", report.getFirstQuestionLatency());
        assertEquals("Is it fun to experience a little uncertainty on a date?", report.getQuestion());
        assertEquals("9985", report.getQuestionLatency());

    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VagrantSettings">
    <option name="instanceFolder" value="" />
    <option name="vagrantExecutable" value="vagrant" />
  </component>
</project>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.firmansyah.gilang.jadwal.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;

/**
 *
 * @author gilang
 */
@Entity
public class Kelas {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    private String id;
    private String nama;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getNama() {
        return nama;
    }

    public void setNama(String nama) {
        this.nama = nama;
    }
}


text:
package mapper

import "time"

type mapperConfigDefaults struct {
	ObserverType        ObserverType     `yaml:"observer_type"`
	MatchType           MatchType        `yaml:"match_type"`
	GlobDisableOrdering bool             `yaml:"glob_disable_ordering"`
	Ttl                 time.Duration    `yaml:"ttl"`
	SummaryOptions      SummaryOptions   `yaml:"summary_options"`
	HistogramOptions    HistogramOptions `yaml:"histogram_options"`
}

// mapperConfigDefaultsAlias is used to unmarshal the yaml config into mapperConfigDefaults and allows deprecated fields
type mapperConfigDefaultsAlias struct {
	ObserverType        ObserverType      `yaml:"observer_type"`
	TimerType           ObserverType      `yaml:"timer_type,omitempty"` // DEPRECATED - field only present to preserve backwards compatibility in configs
	Buckets             []float64         `yaml:"buckets"`              // DEPRECATED - field only present to preserve backwards compatibility in configs
	Quantiles           []metricObjective `yaml:"quantiles"`            // DEPRECATED - field only present to preserve backwards compatibility in configs
	MatchType           MatchType         `yaml:"match_type"`
	GlobDisableOrdering bool              `yaml:"glob_disable_ordering"`
	Ttl                 time.Duration     `yaml:"ttl"`
	SummaryOptions      SummaryOptions    `yaml:"summary_options"`
	HistogramOptions    HistogramOptions  `yaml:"histogram_options"`
}

// UnmarshalYAML is a custom unmarshal function to allow use of deprecated config keys
// observer_type will override timer_type
func (d *mapperConfigDefaults) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var tmp mapperConfigDefaultsAlias
	if err := unmarshal(&tmp); err != nil {
		return err
	}

	// Copy defaults
	d.ObserverType = tmp.ObserverType
	d.MatchType = tmp.MatchType
	d.GlobDisableOrdering = tmp.GlobDisableOrdering
	d.Ttl = tmp.Ttl
	d.SummaryOptions = tmp.SummaryOptions
	d.HistogramOptions = tmp.HistogramOptions

	// Use deprecated TimerType if necessary
	if tmp.ObserverType == "" {
		d.ObserverType = tmp.TimerType
	}

	// Use deprecated quantiles if necessary
	if len(tmp.SummaryOptions.Quantiles) == 0 && len(tmp.Quantiles) > 0 {
		d.SummaryOptions = SummaryOptions{Quantiles: tmp.Quantiles}
	}

	// Use deprecated buckets if necessary
	if len(tmp.HistogramOptions.Buckets) == 0 && len(tmp.Buckets) > 0 {
		d.HistogramOptions = HistogramOptions{Buckets: tmp.Buckets}
	}

	return nil
}


text:
package com.helger.xservlet;

import org.junit.Test;

import com.helger.commons.mock.SPITestHelper;

/**
 * Test SPI configuration consistency.
 *
 * @author Philip Helger
 */
public final class SPITest
{
  @Test
  public void testBasic () throws Exception
  {
    SPITestHelper.testIfAllSPIImplementationsAreValid ();
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revista Soc. Brazil agron. 12(3-4): 56 (1956)

#### Original name
Piggotia aegiphilae Bat.

### Remarks
null


text:
use super::*;
use crate::cell::Cell;

/// # Safety
/// List must be valid.
unsafe fn assert_empty<T>(list: &mut UnsafeList<T>) {
    assert!(unsafe { list.pop() }.is_none(), "assertion failed: list is not empty");
}

#[test]
fn init_empty() {
    unsafe {
        assert_empty(&mut UnsafeList::<i32>::new());
    }
}

#[test]
fn push_pop() {
    unsafe {
        let mut node = UnsafeListEntry::new(1234);
        let mut list = UnsafeList::new();
        assert_eq!(list.push(&mut node), &1234);
        assert_eq!(list.pop().unwrap(), &1234);
        assert_empty(&mut list);
    }
}

#[test]
fn push_remove() {
    unsafe {
        let mut node = UnsafeListEntry::new(1234);
        let mut list = UnsafeList::new();
        assert_eq!(list.push(&mut node), &1234);
        list.remove(&mut node);
        assert_empty(&mut list);
    }
}

#[test]
fn push_remove_pop() {
    unsafe {
        let mut node1 = UnsafeListEntry::new(11);
        let mut node2 = UnsafeListEntry::new(12);
        let mut node3 = UnsafeListEntry::new(13);
        let mut node4 = UnsafeListEntry::new(14);
        let mut node5 = UnsafeListEntry::new(15);
        let mut list = UnsafeList::new();
        assert_eq!(list.push(&mut node1), &11);
        assert_eq!(list.push(&mut node2), &12);
        assert_eq!(list.push(&mut node3), &13);
        assert_eq!(list.push(&mut node4), &14);
        assert_eq!(list.push(&mut node5), &15);

        list.remove(&mut node1);
        assert_eq!(list.pop().unwrap(), &12);
        list.remove(&mut node3);
        assert_eq!(list.pop().unwrap(), &14);
        list.remove(&mut node5);
        assert_empty(&mut list);

        assert_eq!(list.push(&mut node1), &11);
        assert_eq!(list.pop().unwrap(), &11);
        assert_empty(&mut list);

        assert_eq!(list.push(&mut node3), &13);
        assert_eq!(list.push(&mut node4), &14);
        list.remove(&mut node3);
        list.remove(&mut node4);
        assert_empty(&mut list);
    }
}

#[test]
fn complex_pushes_pops() {
    unsafe {
        let mut node1 = UnsafeListEntry::new(1234);
        let mut node2 = UnsafeListEntry::new(4567);
        let mut node3 = UnsafeListEntry::new(9999);
        let mut node4 = UnsafeListEntry::new(8642);
        let mut list = UnsafeList::new();
        list.push(&mut node1);
        list.push(&mut node2);
        assert_eq!(list.pop().unwrap(), &1234);
        list.push(&mut node3);
        assert_eq!(list.pop().unwrap(), &4567);
        assert_eq!(list.pop().unwrap(), &9999);
        assert_empty(&mut list);
        list.push(&mut node4);
        assert_eq!(list.pop().unwrap(), &8642);
        assert_empty(&mut list);
    }
}

#[test]
fn cell() {
    unsafe {
        let mut node = UnsafeListEntry::new(Cell::new(0));
        let mut list = UnsafeList::new();
        let noderef = list.push(&mut node);
        assert_eq!(noderef.get(), 0);
        list.pop().unwrap().set(1);
        assert_empty(&mut list);
        assert_eq!(noderef.get(), 1);
    }
}


text:
import { RichUtils } from 'draft-js';
import handleTabToInsertIndent from './handleTabToInsertIndent';

import type { Config } from '../types/Config';

const createOnTab = (config: Config): Function => (e, pluginFunctions): void => {
  if (handleTabToInsertIndent(e, pluginFunctions)) {
    return;
  }

  const editorState = pluginFunctions.getEditorState();
  const newEditorState = RichUtils.onTab(e, editorState, config.maxDepth);
  if (newEditorState !== editorState) {
    pluginFunctions.setEditorState(newEditorState);
  }
};

export default createOnTab;


text:
class SendSmsJob < ApplicationJob
  queue_as :default

  rescue_from(StandardError) do |exception|
    logger.error exception.message
  end

  def perform(number, message)
    UserTexter.send_message(number, message).deliver
  rescue Twilio::REST::RequestError => e
    logger.error "Could not send message for phone #{number}"
    logger.error e.message
  end
end


text:
/*
	This file is part of cpp-ethereum.
	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file QEtherHelper.js
 * @author Yann yann@ethdev.com
 * @author Arkadiy Paronyan arkadiy@ethdev.com
 * @date 2015
 * Ethereum IDE client.
 */

function createEther(_value, _unit, _parent)
{
	var etherComponent = Qt.createComponent("qrc:/qml/EtherValue.qml");
	var ether = etherComponent.createObject();
	ether.setValue(_value);
	ether.setUnit(_unit);
	return ether;
}

function createBigInt(_value)
{
	var bigintComponent = Qt.createComponent("qrc:/qml/BigIntValue.qml");
	var bigint = bigintComponent.createObject();
	bigint.setValue(_value);
	return bigint;
}


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: avi_alertconfig
author: Gaurav Rastogi (grastogi@avinetworks.com)

short_description: Module for setup of AlertConfig Avi RESTful Object
description:
    - This module is used to configure AlertConfig object
    - more examples at U(https://github.com/avinetworks/devops)
requirements: [ avisdk ]
version_added: "2.4"
options:
    state:
        description:
            - The state that should be applied on the entity.
        default: present
        choices: ["absent","present"]
    action_group_ref:
        description:
            - The alert config will trigger the selected alert action, which can send notifications and execute a controlscript.
            - It is a reference to an object of type actiongroupconfig.
    alert_rule:
        description:
            - List of filters matching on events or client logs used for triggering alerts.
        required: true
    autoscale_alert:
        description:
            - This alert config applies to auto scale alerts.
    category:
        description:
            - Determines whether an alert is raised immediately when event occurs (realtime) or after specified number of events occurs within rolling time
            - window.
            - Enum options - REALTIME, ROLLINGWINDOW, WATERMARK.
            - Default value when not specified in API or module is interpreted by Avi Controller as REALTIME.
        required: true
    description:
        description:
            - A custom description field.
    enabled:
        description:
            - Enable or disable this alert config from generating new alerts.
            - Default value when not specified in API or module is interpreted by Avi Controller as True.
    expiry_time:
        description:
            - An alert is expired and deleted after the expiry time has elapsed.
            - The original event triggering the alert remains in the event's log.
            - Allowed values are 1-31536000.
            - Default value when not specified in API or module is interpreted by Avi Controller as 86400.
    name:
        description:
            - Name of the alert configuration.
        required: true
    obj_uuid:
        description:
            - Uuid of the resource for which alert was raised.
    object_type:
        description:
            - The object type to which the alert config is associated with.
            - Valid object types are - virtual service, pool, service engine.
            - Enum options - VIRTUALSERVICE, POOL, HEALTHMONITOR, NETWORKPROFILE, APPLICATIONPROFILE, HTTPPOLICYSET, DNSPOLICY, IPADDRGROUP, STRINGGROUP,
            - SSLPROFILE, SSLKEYANDCERTIFICATE, NETWORKSECURITYPOLICY, APPLICATIONPERSISTENCEPROFILE, ANALYTICSPROFILE, VSDATASCRIPTSET, TENANT, PKIPROFILE,
            - AUTHPROFILE, CLOUD, SERVERAUTOSCALEPOLICY, AUTOSCALELAUNCHCONFIG, MICROSERVICEGROUP, IPAMPROFILE, HARDWARESECURITYMODULEGROUP, POOLGROUP,
            - PRIORITYLABELS, POOLGROUPDEPLOYMENTPOLICY, GSLBSERVICE, GSLBSERVICERUNTIME, SCHEDULER, GSLBGEODBPROFILE, GSLBAPPLICATIONPERSISTENCEPROFILE,
            - TRAFFICCLONEPROFILE, VSVIP, SERVICEENGINE, DEBUGSERVICEENGINE, DEBUGCONTROLLER, DEBUGVIRTUALSERVICE, SERVICEENGINEGROUP, SEPROPERTIES, NETWORK,
            - CONTROLLERNODE, CONTROLLERPROPERTIES, SYSTEMCONFIGURATION, VRFCONTEXT, USER, ALERTCONFIG, ALERTSYSLOGCONFIG, ALERTEMAILCONFIG, ALERTTYPECONFIG,
            - APPLICATION, ROLE, CLOUDPROPERTIES, SNMPTRAPPROFILE, ACTIONGROUPPROFILE, MICROSERVICE, ALERTPARAMS, ACTIONGROUPCONFIG, CLOUDCONNECTORUSER, GSLB,
            - GSLBDNSUPDATE, GSLBSITEOPS, GLBMGRWARMSTART, IPAMDNSRECORD, GSLBDNSGSSTATUS, GSLBDNSGEOFILEOPS, GSLBDNSGEOUPDATE, GSLBDNSGEOCLUSTEROPS,
            - GSLBDNSCLEANUP, TCPSTATRUNTIME, UDPSTATRUNTIME, IPSTATRUNTIME, ARPSTATRUNTIME, MBSTATRUNTIME, IPSTKQSTATSRUNTIME, MALLOCSTATRUNTIME,
            - SHMALLOCSTATRUNTIME, CPUUSAGERUNTIME, L7GLOBALSTATSRUNTIME, L7VIRTUALSERVICESTATSRUNTIME, SEAGENTVNICDBRUNTIME, SEAGENTGRAPHDBRUNTIME,
            - SEAGENTSTATERUNTIME, INTERFACERUNTIME, ARPTABLERUNTIME, DISPATCHERSTATRUNTIME, DISPATCHERSTATCLEARRUNTIME, DISPATCHERTABLEDUMPRUNTIME,
            - DISPATCHERREMOTETIMERLISTDUMPRUNTIME, METRICSAGENTMESSAGE, HEALTHMONITORSTATRUNTIME, METRICSENTITYRUNTIME, PERSISTENCEINTERNAL,
            - HTTPPOLICYSETINTERNAL, DNSPOLICYINTERNAL, CONNECTIONDUMPRUNTIME, SHAREDDBSTATS, SHAREDDBSTATSCLEAR, ICMPSTATRUNTIME, ROUTETABLERUNTIME,
            - VIRTUALMACHINE, POOLSERVER, SEVSLIST, MEMINFORUNTIME, RTERINGSTATRUNTIME, ALGOSTATRUNTIME, HEALTHMONITORRUNTIME, CPUSTATRUNTIME, SEVM, HOST,
            - PORTGROUP, CLUSTER, DATACENTER, VCENTER, HTTPPOLICYSETSTATS, DNSPOLICYSTATS, METRICSSESTATS, RATELIMITERSTATRUNTIME, NETWORKSECURITYPOLICYSTATS,
            - TCPCONNRUNTIME, POOLSTATS, CONNPOOLINTERNAL, CONNPOOLSTATS, VSHASHSHOWRUNTIME, SELOGSTATSRUNTIME, NETWORKSECURITYPOLICYDETAIL, LICENSERUNTIME,
            - SERVERRUNTIME, METRICSRUNTIMESUMMARY, METRICSRUNTIMEDETAIL, DISPATCHERSEHMPROBETEMPDISABLERUNTIME, POOLDEBUG, VSLOGMGRMAP, SERUMINSERTIONSTATS,
            - HTTPCACHE, HTTPCACHESTATS, SEDOSSTATRUNTIME, VSDOSSTATRUNTIME, SERVERUPDATEREQ, VSSCALEOUTLIST, SEMEMDISTRUNTIME, TCPCONNRUNTIMEDETAIL,
            - SEUPGRADESTATUS, SEUPGRADEPREVIEW, SEFAULTINJECTEXHAUSTM, SEFAULTINJECTEXHAUSTMCL, SEFAULTINJECTEXHAUSTMCLSMALL, SEFAULTINJECTEXHAUSTCONN,
            - SEHEADLESSONLINEREQ, SEUPGRADE, SEUPGRADESTATUSDETAIL, SERESERVEDVS, SERESERVEDVSCLEAR, VSCANDIDATESEHOSTLIST, SEGROUPUPGRADE, REBALANCE,
            - SEGROUPREBALANCE, SEAUTHSTATSRUNTIME, AUTOSCALESTATE, VIRTUALSERVICEAUTHSTATS, NETWORKSECURITYPOLICYDOS, KEYVALINTERNAL, KEYVALSUMMARYINTERNAL,
            - SERVERSTATEUPDATEINFO, CLTRACKINTERNAL, CLTRACKSUMMARYINTERNAL, MICROSERVICERUNTIME, SEMICROSERVICE, VIRTUALSERVICEANALYSIS, CLIENTINTERNAL,
            - CLIENTSUMMARYINTERNAL, MICROSERVICEGROUPRUNTIME, BGPRUNTIME, REQUESTQUEUERUNTIME, MIGRATEALL, MIGRATEALLSTATUSSUMMARY, MIGRATEALLSTATUSDETAIL,
            - INTERFACESUMMARYRUNTIME, INTERFACELACPRUNTIME, DNSTABLE, GSLBSERVICEDETAIL, GSLBSERVICEINTERNAL, GSLBSERVICEHMONSTAT, SETROLESREQUEST,
            - TRAFFICCLONERUNTIME, GEOLOCATIONINFO, SEVSHBSTATRUNTIME, GEODBINTERNAL, GSLBSITEINTERNAL, SERESOURCEPROTO, SECONSUMERPROTO, SECREATEPENDINGPROTO,
            - PLACEMENTSTATS, SEVIPPROTO, RMVRFPROTO, VCENTERMAP, VIMGRVCENTERRUNTIME, INTERESTEDVMS, INTERESTEDHOSTS, VCENTERSUPPORTEDCOUNTERS, ENTITYCOUNTERS,
            - TRANSACTIONSTATS, SEVMCREATEPROGRESS, PLACEMENTSTATUS, VISUBFOLDERS, VIDATASTORE, VIHOSTRESOURCES, CLOUDCONNECTOR, VINETWORKSUBNETVMS,
            - VIDATASTORECONTENTS, VIMGRVCENTERCLOUDRUNTIME, VIVCENTERPORTGROUPS, VIVCENTERDATACENTERS, VIMGRHOSTRUNTIME, PLACEMENTGLOBALS, APICCONFIGURATION,
            - CIFTABLE, APICTRANSACTION, VIRTUALSERVICESTATEDBCACHESUMMARY, POOLSTATEDBCACHESUMMARY, SERVERSTATEDBCACHESUMMARY, APICAGENTINTERNAL,
            - APICTRANSACTIONFLAP, APICGRAPHINSTANCES, APICEPGS, APICEPGEPS, APICDEVICEPKGVER, APICTENANTS, APICVMMDOMAINS, NSXCONFIGURATION, NSXSGTABLE,
            - NSXAGENTINTERNAL, NSXSGINFO, NSXSGIPS, NSXAGENTINTERNALCLI, MAXOBJECTS.
    recommendation:
        description:
            - Recommendation of alertconfig.
    rolling_window:
        description:
            - Only if the number of events is reached or exceeded within the time window will an alert be generated.
            - Allowed values are 1-31536000.
            - Default value when not specified in API or module is interpreted by Avi Controller as 300.
    source:
        description:
            - Signifies system events or the type of client logsused in this alert configuration.
            - Enum options - CONN_LOGS, APP_LOGS, EVENT_LOGS, METRICS.
        required: true
    summary:
        description:
            - Summary of reason why alert is generated.
    tenant_ref:
        description:
            - It is a reference to an object of type tenant.
    threshold:
        description:
            - An alert is created only when the number of events meets or exceeds this number within the chosen time frame.
            - Allowed values are 1-65536.
            - Default value when not specified in API or module is interpreted by Avi Controller as 1.
    throttle:
        description:
            - Alerts are suppressed (throttled) for this duration of time since the last alert was raised for this alert config.
            - Allowed values are 0-31536000.
            - Default value when not specified in API or module is interpreted by Avi Controller as 600.
    url:
        description:
            - Avi controller URL of the object.
    uuid:
        description:
            - Unique object identifier of the object.
extends_documentation_fragment:
    - avi
'''

EXAMPLES = """
- name: Example to create AlertConfig object
  avi_alertconfig:
    controller: 10.10.25.42
    username: admin
    password: something
    state: present
    name: sample_alertconfig
"""

RETURN = '''
obj:
    description: AlertConfig (api/alertconfig) object
    returned: success, changed
    type: dict
'''

from ansible.module_utils.basic import AnsibleModule
try:
    from ansible.module_utils.avi import (
        avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:
    HAS_AVI = False

def main():
    argument_specs = dict(
        state=dict(default='present',
                   choices=['absent', 'present']),
        action_group_ref=dict(type='str',),
        alert_rule=dict(type='dict', required=True),
        autoscale_alert=dict(type='bool',),
        category=dict(type='str', required=True),
        description=dict(type='str',),
        enabled=dict(type='bool',),
        expiry_time=dict(type='int',),
        name=dict(type='str', required=True),
        obj_uuid=dict(type='str',),
        object_type=dict(type='str',),
        recommendation=dict(type='str',),
        rolling_window=dict(type='int',),
        source=dict(type='str', required=True),
        summary=dict(type='str',),
        tenant_ref=dict(type='str',),
        threshold=dict(type='int',),
        throttle=dict(type='int',),
        url=dict(type='str',),
        uuid=dict(type='str',),
    )
    argument_specs.update(avi_common_argument_spec())
    module = AnsibleModule(
        argument_spec=argument_specs, supports_check_mode=True)
    if not HAS_AVI:
        return module.fail_json(msg=(
            'Avi python API SDK (avisdk>=17.1) is not installed. '
            'For more details visit https://github.com/avinetworks/sdk.'))
    return avi_ansible_api(module, 'alertconfig',
                           set([]))

if __name__ == '__main__':
    main()


text:
<?php

use \PEIP\Command\Command as PEIP_Command;

require_once dirname(__FILE__).'/../../misc/bootstrap.php';

PHPUnit_Util_Fileloader::checkAndLoad(dirname(__FILE__).'/../_files/CallableMock.php');

class CommandTest extends PHPUnit_Framework_TestCase
{
    public function setup()
    {
    }

    public function testExecuteStatic()
    {
        $callable = ['CallableMock', 'repeatStatic'];
        $command = new PEIP_Command($callable, ['Test']);
        $this->assertEquals(CallableMock::repeatStatic('Test'), $command->execute());
    }

    public function testExecuteInstance()
    {
        $inst = new CallableMock();
        $callable = [$inst, 'repeat'];
        $command = new PEIP_Command($callable, ['Test']);
        $this->assertEquals($inst->repeat('Test'), $command->execute());
    }

    public function testExecuteFunction()
    {
        $callable = 'callable_mock_function';
        $command = new PEIP_Command($callable, ['Test']);
        $this->assertEquals(callable_mock_function('Test'), $command->execute());
    }

    public function testInvoke()
    {
        $callable = 'callable_mock_function';
        $command = new PEIP_Command($callable, ['Test']);
        $this->assertEquals($command->execute(), $command->__invoke());
    }
}


text:
import $ from 'jquery';
import '../../../lib/select2';
import loadTemplate from '../../../utils/loadTemplate';
import { getTranslatedCountries } from '../../../data/countries';
import regions, {
  getTranslatedRegions,
  getIndexedRegions,
} from '../../../data/regions';
import ServiceMd from '../../../models/listing/Service';
import app from '../../../app';
import Service from './Service';
import BaseView from '../../baseVw';

export default class extends BaseView {
  constructor(options = {}) {
    if (!options.model) {
      throw new Error('Please provide a model.');
    }

    if (typeof options.getCurrency !== 'function') {
      throw new Error('Please provide a function for me to obtain the current currency.');
    }

    const opts = {
      listPosition: 1,
      ...options,
    };

    super(opts);
    this.options = opts;

    // get regions
    this.select2CountryData = getTranslatedRegions(app.settings.get('language'))
      .map(regionObj => ({
        id: regionObj.id,
        text: `REGION_${regionObj.name}`,
      }));

    // now, we'll add in the countries
    const select2countries = getTranslatedCountries(app.settings.get('language'))
      .map(countryObj => ({
        id: countryObj.dataName,
        text: countryObj.name,
      }));
    this.select2CountryData = this.select2CountryData.concat(select2countries);

    this.services = this.model.get('services');
    this.serviceViews = [];

    this.listenTo(this.services, 'add', (serviceMd) => {
      const serviceVw = this.createServiceView({
        model: serviceMd,
      });

      this.serviceViews.push(serviceVw);
      this.$servicesWrap.append(serviceVw.render().el);
    });

    this.listenTo(this.services, 'remove', (serviceMd, servicesCl, removeOpts) => {
      const [splicedVw] = this.serviceViews.splice(removeOpts.index, 1);
      splicedVw.remove();
    });
  }

  events() {
    const events = {
      'click .js-removeShippingOption': 'onClickRemoveShippingOption',
      'click .js-btnAddService': 'onClickAddService',
      'click .js-clearAllShipDest': 'onClickClearShipDest',
    };

    events[`change #shipOptionType_${this.model.cid}`] = 'onChangeShippingType';

    return events;
  }

  tagName() {
    return 'section';
  }

  onClickRemoveShippingOption() {
    this.trigger('click-remove', { view: this });
  }

  onClickAddService() {
    this.services
      .push(new ServiceMd());
  }

  onClickClearShipDest() {
    this.$shipDestinationsSelect
      .find('select')
      .val(null)
      .trigger('change', true);
  }

  onChangeShippingType(e) {
    let method;

    if ($(e.target).val() === 'LOCAL_PICKUP') {
      method = 'addClass';
    } else {
      method = 'removeClass';

      const services = this.model.get('services');

      if (!services.length) services.push(new ServiceMd());
    }

    this.$serviceSection[method]('hide');
  }

  set listPosition(position) {
    if (typeof position !== 'number') {
      throw new Error('Please provide a position as a number');
    }

    const prevPosition = this.options.listPosition;
    const listPosition = this.options.listPosition = position;

    if (listPosition !== prevPosition) {
      this.$headline.text(
        app.polyglot.t('editListing.shippingOptions.optionHeading', { listPosition })
      );
    }
  }

  get listPosition() {
    return this.options.listPosition;
  }

  getFormData(fields = this.$formFields) {
    const formData = super.getFormData(fields);
    const indexedRegions = getIndexedRegions();

    // Strip out any region elements from shipping destinations
    // drop down. The individual countries will remain.
    formData.regions = formData.regions
      .filter(region => !indexedRegions[region]);

    return formData;
  }

  // Sets the model based on the current data in the UI.
  setModelData() {
    // set the data for our nested Services views
    this.serviceViews.forEach((serviceVw) => serviceVw.setModelData());
    this.model.set(this.getFormData());
  }

  createServiceView(opts) {
    const options = {
      getCurrency: this.options.getCurrency,
      ...opts || {},
    };

    const view = this.createChild(Service, options);

    this.listenTo(view, 'click-remove', e => {
      this.services.remove(
        this.services.at(this.serviceViews.indexOf(e.view)));
    });

    return view;
  }

  get $headline() {
    return this._$headline ||
      (this._$headline = this.$('h1'));
  }

  get $shipDestinationDropdown() {
    return this._$shipDestinationDropdown ||
      (this._$shipDestinationDropdown =
        this.$(`#shipDestinationsDropdown_${this.model.cid}`));
  }

  get $serviceSection() {
    return this._$serviceSection ||
      (this._$serviceSection = this.$('.js-serviceSection'));
  }

  get $shipDestinationsSelect() {
    return this._$shipDestinationsSelect ||
      (this._$shipDestinationsSelect = this.$('.js-shipDestinationsSelect'));
  }

  get $formFields() {
    return this._$formFields ||
      (this._$formFields =
        this.$('select[name], input[name], textarea[name]').filter((index, el) => (
          !$(el).parents('.js-serviceSection').length)));
  }

  get fullRegions() {
    // Returns a list of any regions that are fully represented
    // in the country dropdown (i.e. all the individual countries
    // of the region are selected - the actual region selection may
    // or may not be)
    const curSelectionVal = this.$shipDestinationSelect.val();
    const selectedRegions = [];

    regions.forEach(region => {
      if (region.countries.every(elem => curSelectionVal.indexOf(elem) > -1)) {
        selectedRegions.push(region.id);
      }
    });

    return selectedRegions;
  }

  render() {
    loadTemplate('modals/editListing/shippingOption.html', t => {
      this.$el.html(t({
        // Since multiple instances of this view will be rendered, any id's should
        // include the cid, so they're unique.
        cid: this.model.cid,
        listPosition: this.options.listPosition,
        shippingTypes: this.model.shippingTypes,
        errors: this.model.validationError || {},
        countrySelectOptions: this.select2CountryData,
        ...this.model.toJSON(),
      }));

      this.$(`#shipOptionType_${this.model.cid}`).select2({
        // disables the search box
        minimumResultsForSearch: Infinity,
      });

      this.$shipDestinationSelect = this.$(`#shipDestinationsSelect_${this.model.cid}`);
      this.$shipDestinationsPlaceholder = this.$(`#shipDestinationsPlaceholder_${this.model.cid}`);
      this.$servicesWrap = this.$('.js-servicesWrap');

      this.$shipDestinationSelect.select2({
        multiple: true,
        // even though this is a tagging field, since we are limiting the possible selections
        // to a list of countries, don't use tag: true, because then it will allows you to
        // add tags not in the list
        // tags: true,
        dropdownParent: this.$(`#shipDestinationsDropdown_${this.model.cid}`),
        templateSelection: (data) => {
          const text = data.text.startsWith('REGION_') ?
            data.text.slice(7) : data.text;

          return text;
        },
        templateResult: (data) => {
          const text = data.text.startsWith('REGION_') ?
            data.text.slice(7) : data.text;

          return text;
        },
      }).on('change', (e, ignoreRegions = false) => {
        this.$shipDestinationsPlaceholder[
          this.$shipDestinationSelect.val().length ? 'removeClass' : 'addClass'
        ]('emptyOfTags');

        if (ignoreRegions) return;

        setTimeout(() => {
          const curSelected = $(e.target).val();
          const newSelected = this.fullRegions;
          const indexedRegions = getIndexedRegions();

          curSelected.forEach(selected => {
            // We started the newSelected list with any fully
            // represented regions, not we'll add in the selected
            // countries.
            if (!indexedRegions[selected]) {
              newSelected.push(selected);
            }
          });

          $(e.target).val(newSelected)
            .trigger('change', true)
            .select2('close');
        });
      }).on('select2:selecting', (e) => {
        // manage regions
        const region = getIndexedRegions()[e.params.args.data.id];

        if (region) {
          // decide whether we should add or remove the region
          if (this.fullRegions.indexOf(e.params.args.data.id) !== -1) {
            // the region is fully represented, so we'll remove it
            $(e.target).val(
              $(e.target).val()
                .filter(selectedCountry =>
                  (region.countries.indexOf(selectedCountry) === -1))
            ).trigger('change');
          } else {
            // the region is not fully represented, so we'll add it
            $(e.target).val(
              $(e.target).val()
                .concat(region.countries)
            ).trigger('change');
          }
        }
      })
      .on('select2:unselecting', (e) => {
        // manage regions
        const region = getIndexedRegions()[e.params.args.data.id];

        if (region) {
          $(e.target).val(
            $(e.target).val()
              .filter(country =>
                region.countries.indexOf(country) === -1)
          ).trigger('change');
        }
      });

      this.$shipDestinationsPlaceholder[
        this.$shipDestinationSelect.val().length ? 'removeClass' : 'addClass'
      ]('emptyOfTags');

      this.serviceViews.forEach((serviceVw) => serviceVw.remove());
      this.serviceViews = [];
      const servicesFrag = document.createDocumentFragment();

      this.model.get('services').forEach((serviceMd) => {
        const serviceVw = this.createServiceView({ model: serviceMd });

        this.serviceViews.push(serviceVw);
        serviceVw.render().$el.appendTo(servicesFrag);
      });

      this.$servicesWrap.append(servicesFrag);

      this._$headline = null;
      this._$shipDestinationDropdown = null;
      this._$formFields = null;
      this._$serviceSection = null;
      this._$shipDestinationsSelect = null;
    });

    return this;
  }
}


text:
package pt.com.gmv.lab.implant.helpers;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.res.AssetManager;

/**
 * An helper class for handling files from the application.
 *
 * @author fao
 * @since 1
 */
/*
 * Why god, oh why, doesn't Java has extensions methods?!
 */
public final class FileHelpers {
	/**
	 * Moves a file in the application container to the device filesystem.
	 *
	 * @param folder The folder to copy the file to.
	 * @param asset The filename for the file to move.
	 * @param am The asset manager to select the file to move.
	 *
	 * @throws FileNotFoundException In case the file is not found.
	 * @throws IOException In case the copy operation isn't successful.
	 */
	public final static String moveFileToApplicationFilesystem(final File folder,
																final String asset,
																final AssetManager am)
	throws FileNotFoundException, IOException {
		if (!folder.exists()) {
			folder.mkdir();
		}

		if (folder.exists()) {
			File file = new File(folder, asset);

			if (!file.exists()) {
				copy(am.open(asset), new FileOutputStream(file));
			}

			return file.getCanonicalPath();
		}

		return null;
	}

	/**
	 * Makes a buffered copy of data.
	 *
	 * @param in The input stream.
	 * @param out The output stream.
	 *
	 * @throws IOException In case there's a problem when writing to the output stream.
	 */
	private final static void copy(final InputStream in, final OutputStream out) throws IOException {
	    byte[] buffer = new byte[0xFFFF];
	    for (int len; (len = in.read(buffer)) != -1;)
	      out.write( buffer, 0, len );
	}
}


text:
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;

namespace ParentLoadRO.Business.ERLevel
{

    ///
    /// A06_Country (read only object).

    /// This is a generated base class of <see cref="A06_Country"/> business object.
    ///
    /// <remarks>
    /// This class contains one child collection:

    /// - <see cref="A07_RegionObjects"/> of type <see cref="A07_RegionColl"/> (1:M relation to <see cref="A08_Region"/>)

    /// This class is an item of <see cref="A05_CountryColl"/> collection.
    /// </remarks>
    [Serializable]
    public partial class A06_Country : ReadOnlyBase<A06_Country>
    {

        #region State Fields

        private byte[] _rowVersion = new byte[] {};

        [NotUndoable]
        [NonSerialized]
        internal int parent_SubContinent_ID = 0;

        #endregion

        #region Business Properties

        ///
        /// Maintains metadata about <see cref="Country_ID"/> property.
        ///
        public static readonly PropertyInfo<int> Country_IDProperty = RegisterProperty<int>(p => p.Country_ID, "Country ID", -1);
        ///
        /// Gets the Country ID.
        ///
        /// <value>The Country ID.</value>
        public int Country_ID
        {
            get { return GetProperty(Country_IDProperty); }
        }

        ///
        /// Maintains metadata about <see cref="Country_Name"/> property.
        ///
        public static readonly PropertyInfo<string> Country_NameProperty = RegisterProperty<string>(p => p.Country_Name, "Country Name");
        ///
        /// Gets the Country Name.
        ///
        /// <value>The Country Name.</value>
        public string Country_Name
        {
            get { return GetProperty(Country_NameProperty); }
        }

        ///
        /// Maintains metadata about <see cref="ParentSubContinentID"/> property.
        ///
        public static readonly PropertyInfo<int> ParentSubContinentIDProperty = RegisterProperty<int>(p => p.ParentSubContinentID, "Parent Sub Continent ID");
        ///
        /// Gets the Parent Sub Continent ID.
        ///
        /// <value>The Parent Sub Continent ID.</value>
        public int ParentSubContinentID
        {
            get { return GetProperty(ParentSubContinentIDProperty); }
        }

        ///
        /// Maintains metadata about child <see cref="A07_Country_SingleObject"/> property.
        ///
        public static readonly PropertyInfo<A07_Country_Child> A07_Country_SingleObjectProperty = RegisterProperty<A07_Country_Child>(p => p.A07_Country_SingleObject, "A07 Country Single Object");
        ///
        /// Gets the A07 Country Single Object ("parent load" child property).
        ///
        /// <value>The A07 Country Single Object.</value>
        public A07_Country_Child A07_Country_SingleObject
        {
            get { return GetProperty(A07_Country_SingleObjectProperty); }
            private set { LoadProperty(A07_Country_SingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="A07_Country_ASingleObject"/> property.
        ///
        public static readonly PropertyInfo<A07_Country_ReChild> A07_Country_ASingleObjectProperty = RegisterProperty<A07_Country_ReChild>(p => p.A07_Country_ASingleObject, "A07 Country ASingle Object");
        ///
        /// Gets the A07 Country ASingle Object ("parent load" child property).
        ///
        /// <value>The A07 Country ASingle Object.</value>
        public A07_Country_ReChild A07_Country_ASingleObject
        {
            get { return GetProperty(A07_Country_ASingleObjectProperty); }
            private set { LoadProperty(A07_Country_ASingleObjectProperty, value); }
        }

        ///
        /// Maintains metadata about child <see cref="A07_RegionObjects"/> property.
        ///
        public static readonly PropertyInfo<A07_RegionColl> A07_RegionObjectsProperty = RegisterProperty<A07_RegionColl>(p => p.A07_RegionObjects, "A07 Region Objects");
        ///
        /// Gets the A07 Region Objects ("parent load" child property).
        ///
        /// <value>The A07 Region Objects.</value>
        public A07_RegionColl A07_RegionObjects
        {
            get { return GetProperty(A07_RegionObjectsProperty); }
            private set { LoadProperty(A07_RegionObjectsProperty, value); }
        }

        #endregion

        #region Factory Methods

        ///
        /// Factory method. Loads a <see cref="A06_Country"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        /// <returns>A reference to the fetched <see cref="A06_Country"/> object.</returns>
        internal static A06_Country GetA06_Country(SafeDataReader dr)
        {
            A06_Country obj = new A06_Country();
            obj.Fetch(dr);
            obj.LoadProperty(A07_RegionObjectsProperty, new A07_RegionColl());
            return obj;
        }

        #endregion

        #region Constructor

        ///
        /// Initializes a new instance of the <see cref="A06_Country"/> class.
        ///
        /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
        [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
        public A06_Country()
        {
            // Use factory methods and do not use direct creation.
        }

        #endregion

        #region Data Access

        ///
        /// Loads a <see cref="A06_Country"/> object from the given SafeDataReader.
        ///
        /// <param name="dr">The SafeDataReader to use.</param>
        private void Fetch(SafeDataReader dr)
        {
            // Value properties
            LoadProperty(Country_IDProperty, dr.GetInt32("Country_ID"));
            LoadProperty(Country_NameProperty, dr.GetString("Country_Name"));
            LoadProperty(ParentSubContinentIDProperty, dr.GetInt32("Parent_SubContinent_ID"));
            _rowVersion = dr.GetValue("RowVersion") as byte[];
            // parent properties
            parent_SubContinent_ID = dr.GetInt32("Parent_SubContinent_ID");
            var args = new DataPortalHookArgs(dr);
            OnFetchRead(args);
        }

        ///
        /// Loads child <see cref="A07_Country_Child"/> object.
        ///
        /// <param name="child">The child object to load.</param>
        internal void LoadChild(A07_Country_Child child)
        {
            LoadProperty(A07_Country_SingleObjectProperty, child);
        }

        ///
        /// Loads child <see cref="A07_Country_ReChild"/> object.
        ///
        /// <param name="child">The child object to load.</param>
        internal void LoadChild(A07_Country_ReChild child)
        {
            LoadProperty(A07_Country_ASingleObjectProperty, child);
        }

        #endregion

        #region DataPortal Hooks

        ///
        /// Occurs after the low level fetch operation, before the data reader is destroyed.
        ///
        partial void OnFetchRead(DataPortalHookArgs args);

        #endregion

    }
}


text:
#import "NSObject.h"

#import "NSCoding-Protocol.h"
#import "NSDecimalNumberBehaviors-Protocol.h"

@interface NSDecimalNumberHandler : NSObject <NSDecimalNumberBehaviors, NSCoding>
{
    unsigned int _scale:16;
    unsigned int _roundingMode:3;
    unsigned int _raiseOnExactness:1;
    unsigned int _raiseOnOverflow:1;
    unsigned int _raiseOnUnderflow:1;
    unsigned int _raiseOnDivideByZero:1;
    unsigned int _unused:9;
    void *_reserved2;
    void *_reserved;
}

+ (id)decimalNumberHandlerWithRoundingMode:(unsigned long long)arg1 scale:(short)arg2 raiseOnExactness:(_Bool)arg3 raiseOnOverflow:(_Bool)arg4 raiseOnUnderflow:(_Bool)arg5 raiseOnDivideByZero:(_Bool)arg6;
+ (id)defaultDecimalNumberHandler;
- (id)exceptionDuringOperation:(SEL)arg1 error:(unsigned long long)arg2 leftOperand:(id)arg3 rightOperand:(id)arg4;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (short)scale;
- (unsigned long long)roundingMode;
- (id)initWithRoundingMode:(unsigned long long)arg1 scale:(short)arg2 raiseOnExactness:(_Bool)arg3 raiseOnOverflow:(_Bool)arg4 raiseOnUnderflow:(_Bool)arg5 raiseOnDivideByZero:(_Bool)arg6;

@end


text:
.dd { position: relative; display: block; margin: 0; padding: 0; max-width: 600px; list-style: none; font-size: 13px; line-height: 20px; }

.dd-list { display: block; position: relative; margin: 0; padding: 0; list-style: none; }
.dd-list .dd-list { padding-left: 30px; }
.dd-collapsed .dd-list { display: none; }

.dd-item,
.dd-empty,
.dd-placeholder { display: block; position: relative; margin: 0; padding: 0; min-height: 20px; font-size: 13px; line-height: 20px; }

.dd-handle { display: block; height: 30px; margin: 5px 0; padding: 5px 10px; cursor: move; color: #979898; text-decoration: none; font-weight: bold; border: 1px solid #e5e5e5;
    background: #fafafa;
    box-sizing: border-box; -moz-box-sizing: border-box;
}
.dd-handle:hover { color: #317eeb; background: #fff; }

.dd-item > button { display: block; position: relative; cursor: pointer; float: left; width: 25px; height: 20px; margin: 5px 0; padding: 0; text-indent: 100%; white-space: nowrap; overflow: hidden; border: 0; background: transparent; font-size: 12px; line-height: 1; text-align: center; font-weight: bold; }
.dd-item > button:before { content: '+'; display: block; position: absolute; width: 100%; text-align: center; text-indent: 0; }
.dd-item > button[data-action="collapse"]:before { content: '-'; }

.dd-placeholder,
.dd-empty { margin: 5px 0; padding: 0; min-height: 30px; background: #f5f5f5; border: 1px dashed #b6bcbf; box-sizing: border-box; -moz-box-sizing: border-box; }
.dd-empty { border: 1px dashed #bbb; min-height: 100px; background-color: #e5e5e5;

    background-size: 60px 60px;
    background-position: 0 0, 30px 30px;
}

.dd-dragel { position: absolute; pointer-events: none; z-index: 9999; }
.dd-dragel > .dd-item .dd-handle { margin-top: 0; }
.dd-dragel .dd-handle {
    -webkit-box-shadow: 2px 4px 6px 0 rgba(0,0,0,.1);
            box-shadow: 2px 4px 6px 0 rgba(0,0,0,.1);
}

.dd3-content { display: block; height: 30px; margin: 5px 0; padding: 5px 10px 5px 40px; color: #979898; text-decoration: none; font-weight: bold; border: 1px solid #e5e5e5;
    background: #fafafa;
    box-sizing: border-box; -moz-box-sizing: border-box;
}
.dd3-content:hover { color: #317eeb; background: #fff; }

.dd-dragel > .dd3-item > .dd3-content { margin: 0; }

.dd3-item > button { margin-left: 30px; }

.dd3-handle { position: absolute; margin: 0; left: 0; top: 0; cursor: pointer; width: 30px; text-indent: 100%; white-space: nowrap; overflow: hidden;
    border: 1px solid #ccc;
    background: #d5d5d5;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
}
.dd3-handle:before { content: "\f0c9";font-family: FontAwesome; display: block; position: absolute; left: 0; top: 3px; width: 100%; text-align: center; text-indent: 0; color: #fff; font-size: 14px; font-weight: normal; }
.dd3-handle:hover { background: #404040; border:1px solid #404040; }


text:
var labelType, useGradients, nativeTextSupport, animate;

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'Native';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();

var Log = {
  elem: false,
  write: function(text){
    if (!this.elem)
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};


text:
<?php
namespace falkirks\simplewarp\lang;

use falkirks\simplewarp\api\SimpleWarpAPI;
use falkirks\simplewarp\store\DataStore;
use falkirks\simplewarp\store\Reloadable;
use falkirks\simplewarp\store\Saveable;
use pocketmine\utils\TextFormat;

/**
 * This class is currently not implemented in any of SimpleWarp's utilities
 * Class TranslationManager
 * @package falkirks\simplewarp\lang
 */
class TranslationManager {
    /** @var  SimpleWarpAPI */
    private $api;
    /** @var  DataStore */
    private $store;

    public function __construct(SimpleWarpAPI $api, DataStore $store){
        $this->api = $api;
        $this->store = $store;
        $this->registerDefaults();
        $this->save();

    }
    public function get($name){
        return $this->store->get($name);
    }
    public function execute($name, ...$args): string{
        if($args === null || count($args) === 0){
            return $this->get($name);
        }
        if(is_array($args[0])){
            $args = $args[0];
        }
        return  sprintf($this->get($name), ...$args);
    }
    protected function registerDefaults(){
        $this->registerDefault("addwarp-cmd", "addwarp");
        $this->registerDefault("addwarp-desc", "Add new warps.");
        $this->registerDefault("addwarp-usage", "/addwarp <name> [<ip> <port>|<x> <y> <z> <level>|<player>]");
        $this->registerDefault("addwarp-event-cancelled", "A plugin has cancelled the creation of this warp.");

        $this->registerDefault("closewarp-cmd", "closewarp");
        $this->registerDefault("closewarp-desc", "Close existing warps.");
        $this->registerDefault("closewarp-usage", "/closewarp <name>");
        $this->registerDefault("closewarp-event-cancelled", "A plugin has cancelled this action.");

        $this->registerDefault("delwarp-cmd", "delwarp");
        $this->registerDefault("delwarp-desc", "Delete existing warps.");
        $this->registerDefault("delwarp-usage", "/delwarp <name>");
        $this->registerDefault("delewarp-event-cancelled", "A plugin has cancelled the deletion of this warp.");

        $this->registerDefault("listwarps-cmd", "listwarps");
        $this->registerDefault("listwarps-desc", "List all your warps.");
        $this->registerDefault("listwarps-usage", "/listwarps");
        $this->registerDefault("listwarps-list-title", "Warp list:\n");
        $this->registerDefault("listwarps-no-warps",  TextFormat::RED . "No warps found." . TextFormat::RESET);
        $this->registerDefault("listwarps-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("openwarp-cmd", "openwarp");
        $this->registerDefault("openwarp-desc", "Open existing warps.");
        $this->registerDefault("openwarp-usage", "/openwarp <name>");
        $this->registerDefault("delwarp-event-cancelled", "A plugin has cancelled this action.");

        $this->registerDefault("warp-cmd", "warp");
        $this->registerDefault("warp-desc", "Warp around your world.");
        $this->registerDefault("warp-usage", "/warp <name> [player]");

        $this->registerDefault("warp-added-xyz", "You have created a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET . " %s");
        $this->registerDefault("warp-added-player", "You have created a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET . " %s");
        $this->registerDefault("warp-added-server", "You have created a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET . " %s");
        $this->registerDefault("warp-added-self", "You have created a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET . " %s");

        $this->registerDefault("level-not-loaded", TextFormat::RED . "You specified a level which isn't loaded.\nPlease see http://bit.ly/levelerror for explanation." . TextFormat::RESET);

        $this->registerDefault("needs-external-warps", "This warp needs " . TextFormat::AQUA . "FastTransfer" . TextFormat::RESET . " or a newer version of PocketMine.");

        $this->registerDefault("player-not-loaded", TextFormat::RED . "You specified a player which isn't loaded." . TextFormat::RESET);

        $this->registerDefault("addwarp-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("bad-warp-name", TextFormat::RED . "That warp name is invalid." . TextFormat::RESET);

        $this->registerDefault("closed-warp-1", "You have closed a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET);
        $this->registerDefault("closed-warp-2", "  Only players with the permission " . TextFormat::AQUA . "%s" . TextFormat::RESET . " will be able to use this warp.");
        $this->registerDefault("warp-doesnt-exist", TextFormat::RED . "That warp doesn't exist." . TextFormat::RESET);
        $this->registerDefault("closewarp-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("warp-deleted", "You have deleted a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET);
        $this->registerDefault("delwarp-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("opened-warp-1", "You have opened a warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET);
        $this->registerDefault("opened-warp-2", "  Any player will be able to use this warp.");
        $this->registerDefault("openwarp-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("warping-popup", "Warping...");
        $this->registerDefault("other-player-warped", "%s has been warped to " . TextFormat::AQUA . "%s" . TextFormat::RESET . ".");
        $this->registerDefault("no-permission-warp", TextFormat::RED . "You don't have permission to use this warp." . TextFormat::RESET);
        $this->registerDefault("no-permission-warp-other", TextFormat::RED . "You don't have permission to warp other players." . TextFormat::RESET);
        $this->registerDefault("warp-done", "You have been warped");
        $this->registerDefault("warp-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("level-not-loaded-warp", "The warp you are using is attached to a level which isn't loaded");

        $this->registerDefault("ess-warp-doesnt-exist", TextFormat::RED . "That warp doesn't exist." . TextFormat::RESET);
        $this->registerDefault("ess-warp-conflict",  "The warp called " . TextFormat::AQUA . "%s" . TextFormat::RESET . " exists in both " . TextFormat::AQUA . "EssentialsPE" . TextFormat::RESET . " and " . TextFormat::AQUA . "SimpleWarp" . TextFormat::RESET . ". The one from " . TextFormat::AQUA . "SimpleWarp" . TextFormat::RESET . " will be used by default. If you wish to use the " . TextFormat::AQUA . "EssentialsPE" . TextFormat::RESET . " warp, prefix the warp name with " . TextFormat::DARK_AQUA . "ess:" . TextFormat::RESET);

        $this->registerDefault("addwarp-ess-prefix-warning", "Support for " . TextFormat::AQUA . "EssentialsPE" . TextFormat::RESET . " is enabled on this server. When a user wants to explicitly use an " . TextFormat::AQUA . "EssentialsPE" . TextFormat::RESET . " warp, they can prefix their command with " . TextFormat::DARK_AQUA . "ess:" . TextFormat::RESET . ". By choosing to pick a warp name that starts with the same prefix, you are making things complicated. Maybe pick a different name?");

        $this->registerDefault("hold-still-popup", "HOLD STILL to WARP.");
        $this->registerDefault("hold-still-other", "The target must hold still to complete the warp.");
        $this->registerDefault("hold-still-cancelled", "The warp was unsuccessful because you moved.");
        $this->registerDefault("hold-still-cancelled-other", "The warp was unsuccessful because the target moved.");

        $this->registerDefault("warp-failed-popup", TextFormat::RED . "Warp failed!" . TextFormat::RESET);

        $this->registerDefault("warpreport-cmd", "warpreport");
        $this->registerDefault("warpreport-desc", "Report an issue with SimpleWarp.");
        $this->registerDefault("warpreport-usage", "/warpreport [title]");
        $this->registerDefault("warpreport-noperm", TextFormat::RED . "You don't have permission to use this command" . TextFormat::RESET);

        $this->registerDefault("plugin-disabled", TextFormat::RED . "SimpleWarp is disabled and can't execute commands." . TextFormat::RESET);
    }
    protected function registerDefault($name, $text){
        if(!$this->store->exists($name)){
            $this->store->add($name, $text);
        }
    }
    public function reload(){
        if($this->store instanceof Reloadable){
            $this->store->reload();
        }
    }
    protected function save(){
        if($this->store instanceof Saveable){
            $this->store->save();
        }
    }

}


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<!--L
  Copyright Washington University at St. Louis

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/geneconnect/LICENSE.txt for details.
L-->

<SQLSCRIPT>
	<!-- SYSTEM TABLES -->
	<DATASOURCE>
    <NAME>TERMDATA</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE SYSTEM_TERMDATA
			ADD CONSTRAINT PK_SYSTEM_TERMDATA
			PRIMARY KEY  (STD_TERMID)
	</CONSTRAINT_QUERY>
	<CONSTRAINT_QUERY>
			ALTER TABLE SYSTEM_TERMTREE
			ADD CONSTRAINT PK_SYSTEM_TERMTREE
			PRIMARY KEY  (STT_CHILD_TERMID, STT_PARENT_TERMID)
	</CONSTRAINT_QUERY>
	<CONSTRAINT_QUERY>
			ALTER TABLE SYSTEM_TERMTREE
			ADD CONSTRAINT FK_SYSTEM_TERMTREE
			FOREIGN KEY  (STT_CHILD_TERMID) REFERENCES SYSTEM_TERMDATA(STD_TERMID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>

	<!--TABLES POPULATED FROM ENTREZGENE DATA SOURCE-->
	<DATASOURCE>
	<NAME>ENTREZGENE</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_UNIGENE
			ADD CONSTRAINT FK_ENTREZ_UNIGENE
			FOREIGN KEY  (EUG_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_MAP
			ADD CONSTRAINT FK_ENTREZ_MAP
			FOREIGN KEY  (EMA_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_STS
			ADD CONSTRAINT FK_ENTREZ_STS
			FOREIGN KEY  (EST_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_GOID
			ADD CONSTRAINT FK_ENTREZ_GOID
			FOREIGN KEY  (EGO_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_OMIM
			ADD CONSTRAINT FK_ENTREZ_OMIM
			FOREIGN KEY  (EOM_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_PMIDS
			ADD CONSTRAINT FK_ENTREZ_PMIDS
			FOREIGN KEY  (EPI_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_GENENAMES
			ADD CONSTRAINT FK_ENTREZ_GENENAMES
			FOREIGN KEY  (EGE_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_FLY
			ADD CONSTRAINT FK_ENTREZ_FLY
			FOREIGN KEY  (EFY_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_PHENOTYPE
			ADD CONSTRAINT FK_ENTREZ_PHENOTYPE
			FOREIGN KEY  (EPH_GENEID) REFERENCES ENTREZGENE(EGE_GENEID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>

	<!-- TABLES POPULATED FROM UNIGENE DATA SOURCE-->
	<DATASOURCE>
   <NAME>UNIGENE</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE UG_EXPRESS
			ADD CONSTRAINT FK_UG_EXPRESS
			FOREIGN KEY  (UEX_UGID) REFERENCES UNIGENE(UGE_UGID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE UG_SEQUENCE
			ADD CONSTRAINT FK_UG_SEQUENCE
			FOREIGN KEY  (USE_UGID) REFERENCES UNIGENE(UGE_UGID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE UG_PROTSIM
			ADD CONSTRAINT FK_UG_PROTSIM
			FOREIGN KEY  (UPR_UGID) REFERENCES UNIGENE(UGE_UGID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>

	<!-- TABLES POPULATED FROM UNISTS DATA SOURCE-->
	<DATASOURCE>
   <NAME>UNISTS</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE UNISTS_ACCESSION
			ADD CONSTRAINT FK_UNISTS_ACCESSION
			FOREIGN KEY  (UST_STSID,UST_LOCAL_TAXID) REFERENCES UNISTS(UST_STSID,UST_LOCAL_TAXID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>

	<!-- TABLES POPULATED FOR SERVER STATUS-->
	<DATASOURCE>
   <NAME>SERVER_STATUS</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE SERVER_FILE_STATUS
			ADD CONSTRAINT FK_SERVER_FILE_STATUS
			FOREIGN KEY  (SFS_ID) REFERENCES SERVER_STATUS (SST_ID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>

	<!-- TABLES POPULATED FROM DBSNP DATA SOURCE-->
	<DATASOURCE>
    <NAME>DBSNP</NAME>
	<CONSTRAINT_QUERY>
			ALTER TABLE CONTIG_INFO
			ADD CONSTRAINT FK_CONTIG_INFO
			FOREIGN KEY  (CTI_SNPID) REFERENCES SNPTABLE(SNP_SNPID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE ENTREZ_SNP
			ADD CONSTRAINT FK_ENTREZ_SNP
			FOREIGN KEY  (ESN_SNPID) REFERENCES SNPTABLE(SNP_SNPID)
	</CONSTRAINT_QUERY>

	<CONSTRAINT_QUERY>
			ALTER TABLE CONTIG_MAPLOC
			ADD CONSTRAINT FK_CONTIG_MAPLOC_SNPID
			FOREIGN KEY  (CML_SNPID) REFERENCES SNPTABLE(SNP_SNPID)
	</CONSTRAINT_QUERY>
	<CONSTRAINT_QUERY>
				ALTER TABLE FXNSET_CONTIGMAP
				ADD CONSTRAINT FK_FXNSET_CONTIGMAP_SNPID
				FOREIGN KEY  (FCM_SNPID) REFERENCES SNPTABLE(SNP_SNPID)
	</CONSTRAINT_QUERY>
	</DATASOURCE>
</SQLSCRIPT>