text:
import { ICurvedLineOptions } from '../../primitives/curved-line';
import { IPoint } from '../../primitives/point';
import { bezier2 } from '../../util/interpolation';
import { ReferenceColor } from '../reference/reference-color';
import { CurvedLineShape } from '../shape/curved-line-shape';

export interface IRibbonOptions extends ICurvedLineOptions{
  cachedQuadSegments?: boolean;
  depth?: number;
  startColor?: ReferenceColor;
  endColor?: ReferenceColor;
  start: IPoint;
  start2: IPoint;
  end: IPoint;
  end2: IPoint;
  resolution?: number;
  center1: IPoint;
  center2: IPoint;
  controlPoints: IPoint[];
}

/**
 * This defines a drawable ribbon shape.  It contains the information necessary
 * to efficiently render the ribbon.
 *
 * @export
 * @class RibbonShape
 * @extends {CurvedLineShape<T>}
 * @template T An associated data type that can be linked to this shape to make data retrieval from interacting
 *             with the shape easier
 */
export class RibbonShape<T> extends CurvedLineShape<T> {
  /** When true, this line will cache the segments of the curve as rendered quads */
  cachesQuadSegments: boolean;
  /** If caching is set, then this stores the calculated quads that composes this line */
  cachedQuadSegments: IPoint[];
  /** Depeth of draw location */
  depth: number = 0;
  /** The ending color components of this line. This must be a color reference */
  endColor: ReferenceColor;
  /** The starting color components of this line. This must be a color reference */
  startColor: ReferenceColor;
  /** The starting point of ribbon's second bezier line */
  start2: IPoint;
  /** The ending point of ribbon's second bezier line */
  end2: IPoint;
  /** Then center of hemiSphere where two starting points are located */
  center1: IPoint;
  /** Then center of hemiSphere where two ending points are located */
  center2: IPoint;

  /**
   *
   * Creates and instance of RibbonShape
   *
   * @param {IRibbonOptions} options  The options for creating this ribbon
   *
   */
  constructor(options: IRibbonOptions) {
    super(options);

    this.cachesQuadSegments = options.cachedQuadSegments || true;
    this.depth = options.depth || 0;
    this.start2 = options.start2;
    this.end2 = options.end2;
    this.encapsulatePoints(this.getRibbonStrip());
    this.center1 = options.center1;
    this.center2 = options.center2;
  }

  /**
   * Returns a new instance of this object that mimicks the properties of this Object
   *
   * @returns {RibbonShape<T>} The cloned object
   */
  clone() {
    // Perform the clone
    const clone: RibbonShape<T> = new RibbonShape<T>({
      center1: this.center1,
      center2: this.center2,
      controlPoints: this.controlPoints,
      end: this.end,
      end2: this.end2,
      endColor: this.endColor,
      resolution: this.resolution,
      start: this.start,
      start2 : this.start2,
      startColor: this.startColor,
      type: this.type,
    });

    clone.d = this.d;

    return clone;
  }

  /**
   * @override
   * Return distance from a point to ribbon. If the point is in ribbon, return 0
   * Otherwise use method of superclass.
   */
  distanceTo(point: IPoint): number {
    if (this.pointInside(point)) return 0;
    return super.distanceTo(point);
  }

  /**
   * Test whether a point is in the ribbon using Point Inclusion in Polygon Test method
   * @param point
   */
  pointInside(point: IPoint): boolean {
    const points = this.getRibbonStrip();
    const nvert: number = points.length;
    let i: number;
    let j: number;
    let c: boolean = false;
    const testx = point.x;
    const testy = point.y;

    for (i = 0, j = nvert - 1; i < nvert; j = i++) {
      if (((points[i].y > testy) !== (points[j].y > testy)) &&
         (testx < (points[j].x - points[i].x) * (testy - points[i].y) /
         (points[j].y - points[i].y) + points[i].x)) {
        c = !c;
      }
    }

    return c;
  }

  /**
   * This prodeuces all the points along the two bezier lines.
   * The order of all the points pushed should be clockwise.
   *
   * @return {IPoint[]} The points to create the quads that make each segment of the ribbon.
   *
   */
  getRibbonStrip(): IPoint[]{
    const strip: IPoint[] = [];
    const dt = 1 / this.resolution;
    const c1 = this.controlPoints[0];
    const c2 = this.controlPoints[1];

    for (let i = 0 ; i <= this.resolution; i++ ) {
      strip.push(bezier2(dt * i, this.start, this.end, c1));
    }

    for (let i = this.resolution; i >= 0; i--){
      strip.push(bezier2(dt * i, this.start2, this.end2, c2));
    }
    return strip;
  }

}


text:
#include <folly/executors/GlobalExecutor.h>
#include <folly/executors/IOExecutor.h>
#include <folly/portability/GTest.h>

using namespace folly;

TEST(GlobalExecutorTest, GlobalCPUExecutor) {
  class DummyExecutor : public folly::Executor {
   public:
    void add(Func f) override {
      f();
      count++;
    }
    int count{0};
  };

  // The default CPU executor is a synchronous inline executor, lets verify
  // that work we add is executed
  auto count = 0;
  auto f = [&]() { count++; };

  // Don't explode, we should create the default global CPUExecutor lazily here.
  getCPUExecutor()->add(f);
  EXPECT_EQ(1, count);

  {
    auto dummy = std::make_shared<DummyExecutor>();
    setCPUExecutor(dummy);
    getCPUExecutor()->add(f);
    // Make sure we were properly installed.
    EXPECT_EQ(1, dummy->count);
    EXPECT_EQ(2, count);
  }

  // Don't explode, we should restore the default global CPUExecutor because our
  // weak reference to dummy has expired
  getCPUExecutor()->add(f);
  EXPECT_EQ(3, count);
}

TEST(GlobalExecutorTest, GlobalIOExecutor) {
  class DummyExecutor : public IOExecutor {
   public:
    void add(Func) override {
      count++;
    }
    folly::EventBase* getEventBase() override {
      return nullptr;
    }
    int count{0};
  };

  auto f = []() {};

  // Don't explode, we should create the default global IOExecutor lazily here.
  getIOExecutor()->add(f);

  {
    auto dummy = std::make_shared<DummyExecutor>();
    setIOExecutor(dummy);
    getIOExecutor()->add(f);
    // Make sure we were properly installed.
    EXPECT_EQ(1, dummy->count);
  }

  // Don't explode, we should restore the default global IOExecutor because our
  // weak reference to dummy has expired
  getIOExecutor()->add(f);
}

redpajama_set_name: RedPajamaGithub


text:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class propiedadesFrame extends HttpServlet
{
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        PrintWriter p = response.getWriter();
        HttpSession s = request.getSession();

        s.setAttribute("fr", request.getParameter("frames"));

        p.print("<form action=\"DrawFrame\" method=\"POST\">");
        p.print("Filas: <input type='text' name='filas'>
");
        p.print("Columnas: <input type='text' name='columnas'>
");
        p.print("Espaciado: <input type='text' name='esp'>
");
        p.print("
<input type=\"submit\" name=\"send\" class=\"enviar\" value=\"Validar\" class=\"boton\"></form>");
    }
}


text:
util/checkout_yaml_test.pl

# Run YAML tests
test/run_yaml_tests.pl


text:
import java.io.*;
import java.util.*;
import java.util.jar.*;

public class JarFileList {
	public static void main(String[] args) throws IOException {
		if (args.length == 0) {
			System.err.println("error: no jar file specified");
			System.exit(1);
		}
		String jarFileName = args[0];

		try (JarFile jarFile = new JarFile(new File(jarFileName))) {
            for (JarEntry entry : Collections.list(jarFile.entries()))
				System.out.println(entry.getName());
		}
	}
}


text:
/**
	These tests are currently designed to be run from the command line like
	`/keystone/tests node fields`

	Currently in this format for expermientation, will be implemented as proper
	unit tests soon!
*/

var keystone = require('../').init(),
	Types = keystone.Field.Types;

/** Test List and Fields */

var Test = keystone.List('Test');

Test.add({
	date: Types.Date,
	datetime: Types.Datetime
});

Test.register();

/** Test Item */

var item = new Test.model();

/** FieldType: Date */

item._.date.parse('20131204', 'YYYYMMDD');
console.log('Should be 4th Dec 2013: ' + item._.date.format());
console.log('Should be 20131204: ' + item._.date.format('YYYYMMDD'));
console.log('Should be a moment object:');
console.log(item._.date.moment());


text:
#include "tensorflow/lite/arena_planner.h"

#include <stddef.h>

#include <algorithm>
#include <cstdint>
#include <limits>
#include <memory>
#include <utility>
#include <vector>

#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/graph_info.h"
#include "tensorflow/lite/simple_memory_arena.h"

namespace tflite {
namespace {

constexpr int32_t kNodeNotAssigned = std::numeric_limits<int32_t>::max();

}  // namespace

ArenaPlanner::ArenaPlanner(TfLiteContext* context,
                           std::unique_ptr<GraphInfo> graph_info,
                           bool preserve_all_tensors, int tensor_alignment)
    : context_(context),
      graph_info_(std::move(graph_info)),
      arena_(kDefaultArenaAlignment),
      persistent_arena_(kDefaultArenaAlignment),
      preserve_all_tensors_(preserve_all_tensors),
      tensor_alignment_(tensor_alignment) {}

ArenaPlanner::~ArenaPlanner() {}

std::intptr_t ArenaPlanner::BasePointer(TfLiteAllocationType type) {
  if (type == kTfLiteArenaRwPersistent) {
    return persistent_arena_.BasePointer();
  }
  if (type == kTfLiteArenaRw) {
    return arena_.BasePointer();
  }
  return 0;
}

TfLiteStatus ArenaPlanner::ResetAllocations() {
  TF_LITE_ENSURE_STATUS(arena_.ClearPlan());
  TF_LITE_ENSURE_STATUS(persistent_arena_.ClearPlan());
  allocs_.clear();
  allocs_.resize(graph_info_->num_tensors());
  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::ResetAllocationsAfter(int node) {
  for (int i = 0; i < static_cast<int>(allocs_.size()); ++i) {
    if (allocs_[i].first_node > node && allocs_[i].size > 0) {
      TfLiteTensor& tensor = *graph_info_->tensor(i);
      if (tensor.allocation_type == kTfLiteArenaRw) {
        TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[i]));
        allocs_[i].reset();
        tensor.data.raw = nullptr;
      }
    }
  }

  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::PlanAllocations() {
  // Invalidate any existing data.
  TF_LITE_ENSURE_STATUS(ResetAllocations());
  // Maybe other verb instead of 'Assigned'
  alloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned);
  dealloc_node_.assign(graph_info_->num_tensors(), kNodeNotAssigned);

  // Keeps track of references to each tensor.
  std::vector<int> refcounts(graph_info_->num_tensors(), 0);

  auto allocate = [this](int node, int tensor) -> TfLiteStatus {
    if (alloc_node_[tensor] != kNodeNotAssigned) {
      // Tensor has already been allocated.
      return kTfLiteOk;
    }
    TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned);
    alloc_node_[tensor] = node;
    return kTfLiteOk;
  };

  auto deallocate = [this](int node, int tensor) -> TfLiteStatus {
    if (alloc_node_[tensor] == kNodeNotAssigned) {
      // We don't need to deallocate the tensor, that is never allocated.
      // This happened with the constant tensors.
      return kTfLiteOk;
    }
    TF_LITE_ENSURE(context_, dealloc_node_[tensor] == kNodeNotAssigned);
    dealloc_node_[tensor] = node;
    return kTfLiteOk;
  };

  // We must make sure the output tensors are never overwritten. We do that by
  // artificially adding one to their ref-counts so they are never selected
  // for deallocation.
  for (int tensor_index : graph_info_->outputs()) {
    refcounts[tensor_index]++;
  }

  // Variable tensors also should be ensured to be never overwritten and need to
  // be alive all the time.
  for (int tensor_index : graph_info_->variables()) {
    // Increase the reference count for variable tensors by one, so it will
    // never be deallocated.
    refcounts[tensor_index]++;
    // `variables` is a subgraph-level list and it should never be
    // kTfLiteOptionalTensor.
    TF_LITE_ENSURE(context_, tensor_index != kTfLiteOptionalTensor);
    // Variable tensor should be allocated at the very beginning.
    TF_LITE_ENSURE_STATUS(allocate(0, tensor_index));
  }

  // Queue all graph inputs for allocation and make sure they are never
  // overwritten.
  for (int tensor_index : graph_info_->inputs()) {
    if (tensor_index != kTfLiteOptionalTensor) {
      refcounts[tensor_index]++;
      TF_LITE_ENSURE_STATUS(allocate(0, tensor_index));
    }
  }

  // Count references to node input tensors.
  for (size_t i = 0; i < graph_info_->num_execution_nodes(); ++i) {
    const TfLiteNode& node = graph_info_->node(i);
    TfLiteIntArray* node_inputs = node.inputs;
    for (int j = 0; j < node_inputs->size; ++j) {
      int tensor_index = node_inputs->data[j];
      if (tensor_index != kTfLiteOptionalTensor) {
        refcounts[tensor_index]++;
      }
    }
  }

  // Go through the graph in execution order.
  for (size_t i = 0; i < graph_info_->num_execution_nodes(); ++i) {
    const TfLiteNode& node = graph_info_->node(i);

    // First queue output tensors for allocation.
    TfLiteIntArray* node_outputs = node.outputs;
    for (int j = 0; j < node_outputs->size; ++j) {
      int tensor_index = node_outputs->data[j];
      TF_LITE_ENSURE_STATUS(allocate(i, tensor_index));
    }

    // Then update the ref-counts of the node's inputs, and if necessary queue
    // them for deallocation.
    if (!preserve_all_tensors_) {
      TfLiteIntArray* node_inputs = node.inputs;
      for (int j = 0; j < node_inputs->size; ++j) {
        int tensor_index = node_inputs->data[j];
        if (tensor_index != kTfLiteOptionalTensor) {
          refcounts[tensor_index]--;
          if (refcounts[tensor_index] == 0) {
            TF_LITE_ENSURE_STATUS(deallocate(i, tensor_index));
          }
        }
      }
    }
  }

  // Note that graph outputs will never be scheduled for deallocation. We
  // could do that here for completeness, but it won't have any effect.
  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::ExecuteAllocations(int first_node, int last_node) {
  // Grow the size of `allocs_` if necessary. This allows allocating temporary
  // tensors in op's `prepare` function.
  TF_LITE_ENSURE(context_, graph_info_->num_tensors() >= allocs_.size());
  alloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned);
  dealloc_node_.resize(graph_info_->num_tensors(), kNodeNotAssigned);
  allocs_.resize(graph_info_->num_tensors());
  // Set allocation and deallocation for temporary tensors.
  for (size_t i = first_node; i <= static_cast<size_t>(last_node) &&
                              i < graph_info_->num_execution_nodes();
       ++i) {
    const TfLiteNode& node = graph_info_->node(i);
    TfLiteIntArray* node_temporaries = node.temporaries;
    for (int j = 0; j < node_temporaries->size; ++j) {
      int tensor_index = node_temporaries->data[j];
      alloc_node_[tensor_index] = i;
      if (!preserve_all_tensors_) {
        dealloc_node_[tensor_index] = i;
      }
    }
  }

  TF_LITE_ENSURE_STATUS(CalculateAllocations(first_node, last_node));
  TF_LITE_ENSURE_STATUS(Commit());

  for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) {
    // TODO(ahentz): we could do this only for the tensors that were modified
    // in CalculateAllocations(), instead of redoing it for tensors that
    // already had proper pointers. However we must be very careful, because
    // SimpleMemoryArena::Commit() could move the base pointer.
    TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i));
  }

  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::ReleaseNonPersistentMemory() {
  // Clear non-persistent arena's buffer.
  TF_LITE_ENSURE_STATUS(arena_.ReleaseBuffer());
  // Set data pointers for all non-persistent tensors to nullptr.
  for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) {
    TfLiteTensor& tensor = *graph_info_->tensor(i);
    if (tensor.allocation_type == kTfLiteArenaRw) {
      tensor.data.raw = nullptr;
    }
  }
  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::AcquireNonPersistentMemory() {
  // First commit arena_ to allocate underlying buffer.
  TF_LITE_ENSURE_STATUS(arena_.Commit(context_));
  // Resolve allocations for all tensors not on the persistent arena.
  for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) {
    TfLiteTensor& tensor = *graph_info_->tensor(i);
    if (tensor.allocation_type == kTfLiteArenaRw) {
      TF_LITE_ENSURE_STATUS(ResolveTensorAllocation(i));
    }
  }
  return kTfLiteOk;
}

bool ArenaPlanner::HasNonPersistentMemory() {
  return arena_.GetBufferSize() != 0;
}

TfLiteStatus ArenaPlanner::Commit() {
  TF_LITE_ENSURE_STATUS(arena_.Commit(context_));
  TF_LITE_ENSURE_STATUS(persistent_arena_.Commit(context_));
  return kTfLiteOk;
}

std::vector<int32_t> ArenaPlanner::CreateTensorAllocationVector(int first_node,
                                                                int last_node) {
  auto tensor_compare = [this](int idx1, int idx2) {
    // Tensors that have lifespan through the whole model inference time are
    // allocated at the beginning of memory slice. Their respective order
    // doesn't matter in fact, so here they are sorted by index.
    if (this->alloc_node_[idx1] == 0 &&
        this->dealloc_node_[idx1] == kNodeNotAssigned) {
      if (this->alloc_node_[idx2] == 0 &&
          this->dealloc_node_[idx2] == kNodeNotAssigned) {
        return idx1 < idx2;
      }
      return true;
    }
    if (this->alloc_node_[idx2] == 0 &&
        this->dealloc_node_[idx2] == kNodeNotAssigned) {
      return false;
    }

    // All other tensors are sorted in non-increasing order of their size.
    auto size1 = this->graph_info_->tensor(idx1)->bytes;
    auto size2 = this->graph_info_->tensor(idx2)->bytes;
    if (size1 != size2) {
      return size1 > size2;
    }
    // Tensors with equal size are sorted in order of their allocation time.
    return this->alloc_node_[idx1] < this->alloc_node_[idx2];
  };

  std::vector<int32_t> tensor_order;
  for (int i = 0; i < static_cast<int>(graph_info_->num_tensors()); ++i) {
    if (alloc_node_[i] >= first_node && alloc_node_[i] <= last_node) {
      tensor_order.push_back(i);
    }
  }
  // Indices of tensors in order their allocation offsets will be calculated.
  std::sort(tensor_order.begin(), tensor_order.end(), tensor_compare);

  return tensor_order;
}

TfLiteStatus ArenaPlanner::CalculateAllocations(int first_node, int last_node) {
  // Indices of tensors in order their allocation offsets will be calculated.
  const std::vector<int32_t> tensor_order =
      CreateTensorAllocationVector(first_node, last_node);

  // Deallocate if the tensor was already allocated.
  for (const auto& tensor_index : tensor_order) {
    TfLiteTensor& tensor = *graph_info_->tensor(tensor_index);
    if (tensor.allocation_type == kTfLiteArenaRw &&
        allocs_[tensor_index].size != 0) {
      TF_LITE_ENSURE_STATUS(arena_.Deallocate(context_, allocs_[tensor_index]));
    }
  }

  // Vector of ids of already allocated tensors, ordered by offset.
  for (const auto& tensor_index : tensor_order) {
    TfLiteTensor& tensor = *graph_info_->tensor(tensor_index);
    if (tensor.allocation_type == kTfLiteArenaRw) {
      TF_LITE_ENSURE_STATUS(
          arena_.Allocate(context_, tensor_alignment_, tensor.bytes,
                          tensor_index, alloc_node_[tensor_index],
                          dealloc_node_[tensor_index], &allocs_[tensor_index]));
    }
    // Check allocs_[].size to prevent from reallocation of persistent tensors.
    if (tensor.allocation_type == kTfLiteArenaRwPersistent &&
        allocs_[tensor_index].size == 0) {
      TF_LITE_ENSURE_STATUS(persistent_arena_.Allocate(
          context_, tensor_alignment_, tensor.bytes, tensor_index,
          /*first_node=*/alloc_node_[tensor_index],
          /*last_node=*/std::numeric_limits<int32_t>::max(),
          &allocs_[tensor_index]));
    }
  }
  return kTfLiteOk;
}

TfLiteStatus ArenaPlanner::ResolveTensorAllocation(int tensor_index) {
  TfLiteTensor& tensor = *graph_info_->tensor(tensor_index);
  if (tensor.allocation_type == kTfLiteArenaRw) {
    // Skip resolution if the size of the tensor is zero, leaving it as a
    // nullptr.
    if (allocs_[tensor_index].size != 0) {
      TF_LITE_ENSURE_STATUS(arena_.ResolveAlloc(context_, allocs_[tensor_index],
                                                &tensor.data.raw));
    }
  }
  if (tensor.allocation_type == kTfLiteArenaRwPersistent) {
    TF_LITE_ENSURE_STATUS(persistent_arena_.ResolveAlloc(
        context_, allocs_[tensor_index], &tensor.data.raw));
  }
  return kTfLiteOk;
}

}  // namespace tflite


text:
# Licensing
This project is licensed under the MIT license. See [LICENSE.md](https://github.com/yayes2/ReactBase/blob/master/LICENSE.md) for further info.


text:
var exec    = require('cordova/exec'),
    channel = require('cordova/channel');

/*************
 * INTERFACE *
 *************/

/**
 * Clears the badge of the app icon.
 *
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.clear = function (callback, scope) {
    this.exec('clearBadge', null, callback, scope);
};

/**
 * Sets the badge of the app icon.
 *
 * @param {Number} badge
 *      The new badge number
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.set = function (badge, callback, scope) {
    var args = [parseInt(badge) || 0];

    this.registerPermission(function (granted) {
        if (granted) {
            this.exec('setBadge', args, callback, scope);
        }
    }, this);
};

/**
 * Gets the badge of the app icon.
 *
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.get = function (callback, scope) {
    this.exec('getBadge', null, callback, scope);
};

/**
 * Increases the badge number.
 *
 * @param {Number} count
 *      Count to add to the current badge number
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.increase = function (count, callback, scope) {
    this.get(function (badge) {
        this.set(badge + (count || 1), callback, scope);
    }, this);
};

/**
 * Decreases the badge number.
 *
 * @param {Number} count
 *      Count to subtract from the current badge number
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.decrease = function (count, callback, scope) {
    this.get(function (badge) {
        this.set(Math.max(0, badge - (count || 1)), callback, scope);
    }, this);
};

/**
 * Informs if the app has the permission to show badges.
 *
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.hasPermission = function (callback, scope) {
    this.exec('hasPermission', null, callback, scope);
};

/**
 * Register permission to show badges if not already granted.
 *
 * @param {Function} callback
 *      The function to be exec as the callback
 * @param {Object?} scope
 *      The callback function's scope
 */
exports.registerPermission = function (callback, scope) {
    this.exec('registerPermission', null, callback, scope);
};

/**
 * Configures the plugin's platform options.
 *
 * @param {Hash?} object
 *      The new configuration settings
 *
 * @return {Hash}
 *      The current configuration settings
 */
exports.configure = function (config) {
    for (var key in config) {
        if (this._config.hasOwnProperty(key)) {
            this._config[key] = config[key];
        }
    }

    return this._config;
};

/***********
 * MEMBERS *
 ***********/

exports._config = {
    autoClear: false
};

/********
 * UTIL *
 ********/

/**
 * Create callback, which will be executed within a specific scope.
 *
 * @param {Function} callbackFn
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 *
 * @return {Function}
 *      The new callback function
 */
exports.createCallbackFn = function (callbackFn, scope) {
    if (typeof callbackFn != 'function')
        return;

    return function () {
        callbackFn.apply(scope || this, arguments);
    };
};

/**
 * Execute the native counterpart.
 *
 * @param {String} action
 *      The name of the action
 * @param args[]
 *      Array of arguments
 * @param {Function} callback
 *      The callback function
 * @param {Object} scope
 *      The scope for the function
 */
exports.exec = function (action, args, callback, scope) {
    var fn = this.createCallbackFn(callback, scope),
        params = [];

    if (Array.isArray(args)) {
        params = args;
    } else if (args) {
        params.push(args);
    }

    exec(fn, null, 'Badge', action, params);
};

/*********
 * HOOKS *
 *********/

channel.onCordovaReady.subscribe(function () {
    if (exports._config.autoClear) { exports.clear(); }
});

channel.onResume.subscribe(function () {
    if (exports._config.autoClear) { exports.clear(); }
});


text:
<?php

namespace Pushman\Http\Middleware;

use Closure;
use Pushman\Exceptions\InvalidRequestException;
use Pushman\Interfaces\Ownable;

class MustOwnResource
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $allowed = true;
        $user = $request->user();

        if ($user->isAdmin()) {
            return $next($request);
        }

        $resources = [];

        $site = $request->route()->getParameter('sites');
        if (!is_null($site)) {
            $resources[] = $site;
        }

        $channel = $request->route()->getParameter('channels');
        if (!is_null($channel)) {
            $resources[] = $channel;
        }

        foreach ($resources as $resource) {
            if (!$resource instanceof Ownable) {
                throw new InvalidRequestException('Cannot check ownership on this object.');
            }
            if (!$resource->ownedBy($user)) {
                $allowed = false;
            }
        }

        if ($allowed) {
            return $next($request);
        }

        flash()->warning('You do not own that resource.');

        return redirect('/dashboard');
    }
}


text:
from .session import Session
import logging
logger = logging.getLogger(__name__)

SEARCH_URL = "https://web.archive.org/cdx/search/cdx"

def search(url,
    from_date=None,
    to_date=None,
    uniques_only=False,
    collapse=None,
    session=None):

    session = session or Session()
    res = session.get(SEARCH_URL, params={
        "url": url,
        "from": from_date,
        "to": to_date,
        "showDupeCount": "true",
        "output": "json",
        "collapse": collapse
    })

    if res.status_code == 200:
        cdx = res.json()

    else:
        log_msg = 'CDX exception: "{0}"'
        logger.info(log_msg.format(
            res.content.decode("utf-8").strip()
        ))
        return []

    if len(cdx) < 2: return []
    fields = cdx[0]
    snapshots = [ dict(zip(fields, row)) for row in cdx[1:] ]
    if uniques_only:
        return [ s for s in snapshots if int(s["dupecount"]) == 0 ]
    else:
        return snapshots


text:
package com.opengamma.sesame;

import com.opengamma.core.security.SecuritySource;
import com.opengamma.financial.analytics.curve.exposure.ExposureFunctions;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.result.Result;

/**
 * Function implementation that provides a market exposure selector.
 * @deprecated this serves no useful purpose, the engine can create {@link MarketExposureSelector} directly.
 */
@Deprecated
public class ConfigDbMarketExposureSelectorFn implements MarketExposureSelectorFn {

  /**
   * The exposure config.
   */
  private final ExposureFunctions _exposures;
  /**
   * The underlying security source.
   */
  private final SecuritySource _securitySource;

  public ConfigDbMarketExposureSelectorFn(ExposureFunctions exposureConfig, SecuritySource securitySource) {
    _exposures = ArgumentChecker.notNull(exposureConfig, "exposureConfig");
    _securitySource = ArgumentChecker.notNull(securitySource, "securitySource");
  }

  //-------------------------------------------------------------------------
  @Override
  public Result<MarketExposureSelector> getMarketExposureSelector() {
    return Result.success(new MarketExposureSelector(_exposures, _securitySource));
  }

}


text:
module.exports = {
  Models: require('./models'),
  Modules: require('./modules')
};


text:
package com.mercateo.spring.security.jwt.security;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Collections;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import lombok.val;

@RunWith(MockitoJUnitRunner.class)
public class JWTAuthenticationTokenFilterTest {

    @Mock
    private HttpServletRequest request;

    @Mock
    private HttpServletResponse response;

    @Mock
    private FilterChain chain;

    @Mock
    private AuthenticationManager authenticationManager;

    private JWTAuthenticationTokenFilter uut;

    @Before
    public void init() {
        uut = new JWTAuthenticationTokenFilter();
    }

    @Test
    public void throwsWithoutToken() throws Exception {

        JWTAuthenticationTokenFilter spy = Mockito.spy(uut);
        when(request.getServletPath()).thenReturn("/api");

        spy.doFilter(request, response, chain);

        verify(spy, never()).attemptAuthentication(request, response);
        verify(spy, never()).successfulAuthentication(eq(request), eq(response), eq(chain), any());

    }

    @Test
    public void returnsWrappedToken() {
        val tokenString = "<token>";
        when(request.getHeader("authorization")).thenReturn("Bearer " + tokenString);
        uut.setAuthenticationManager(authenticationManager);
        val authentication = mock(Authentication.class);
        when(authenticationManager.authenticate(new JWTAuthenticationToken(tokenString)))
                .thenReturn(authentication);

        val result = uut.attemptAuthentication(request, response);

        assertThat(result).isEqualTo(authentication);
    }

    @Test
    public void dontAttemptAuthenticationWithoutTokenWithAnonymousPath() throws Exception {

        uut.addUnauthenticatedPaths(Collections.singleton("/api"));
        JWTAuthenticationTokenFilter spy = Mockito.spy(uut);
        when(request.getServletPath()).thenReturn("/api");

        spy.doFilter(request, response, chain);

        verify(spy, never()).attemptAuthentication(request, response);

    }

    @Test
    public void dontAttemptAuthenticationWithoutTokenWithAnonymousPathWildcard() throws Exception {

        uut.addUnauthenticatedPaths(Collections.singleton("/api/*"));
        JWTAuthenticationTokenFilter spy = Mockito.spy(uut);
        when(request.getServletPath()).thenReturn("/api/foo");

        spy.doFilter(request, response, chain);

        verify(spy, never()).attemptAuthentication(request, response);

    }

    @Test
    public void callsFilterChainWithoutTokenWithAnonymousPath() throws Exception {

        uut.addUnauthenticatedPaths(Collections.singleton("/api"));
        when(request.getServletPath()).thenReturn("/api");

        uut.doFilter(request, response, chain);

        verify(chain).doFilter(request, response);

    }

    @Test
    public void callsFilterChainWithoutTokenWithoutAnonymousPath() throws Exception {

        final AuthenticationFailureHandler mockAuthenticationFailureHandler = mock(AuthenticationFailureHandler.class);
        doNothing().when(mockAuthenticationFailureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
                any(HttpServletResponse.class), any(AuthenticationException.class));
        uut.setAuthenticationFailureHandler(mockAuthenticationFailureHandler);

        uut.doFilter(request, response, chain);

        verify(chain, never()).doFilter(request, response);
        verify(mockAuthenticationFailureHandler).onAuthenticationFailure(any(HttpServletRequest.class),
                        any(HttpServletResponse.class), any(AuthenticationException.class));
    }

    @Test
    public void throwsWithoutTokenInSubdirectoryOfAnonymousPath() throws Exception {

        uut.addUnauthenticatedPaths(Collections.singleton("/api"));
        JWTAuthenticationTokenFilter spy = Mockito.spy(uut);
        when(request.getServletPath()).thenReturn("/api/foo");

        spy.doFilter(request, response, chain);

        verify(spy, never()).attemptAuthentication(request, response);
        verify(spy, never()).successfulAuthentication(eq(request), eq(response), eq(chain), any());

    }

    @Test
    public void callsFilterChainIfSuccessfulAuthentication() throws Exception {
        val authentication = mock(Authentication.class);
        uut.successfulAuthentication(request, response, chain, authentication);

        verify(chain).doFilter(request, response);
    }

    @Test
    public void returnNullWithoutToken() {
        Authentication result = uut.attemptAuthentication(request, response);

        assertThat(result).isNull();
    }

}


text:
<?php

namespace Speedwork\Database\Migration\Console;

use Speedwork\Console\Traits\ConfirmableTrait;
use Speedwork\Database\Migration\Migrator;
use Symfony\Component\Console\Input\InputOption;

/**
 * @author Sankar <sankar.suda@gmail.com>
 */
class ResetCommand extends BaseCommand
{
    use ConfirmableTrait;

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'migration:reset';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Rollback all database migrations';

    /**
     * The migrator instance.
     *
     * @var \Speedwork\Database\Migration\Migrator
     */
    protected $migrator;

    /**
     * Create a new migration rollback command instance.
     *
     * @param \Speedwork\Database\Migration\Migrator $migrator
     */
    public function __construct(Migrator $migrator)
    {
        parent::__construct();

        $this->migrator = $migrator;
    }

    /**
     * Execute the console command.
     */
    public function fire()
    {
        if (!$this->confirmToProceed()) {
            return;
        }

        $this->migrator->setConnection($this->option('database'));

        // First, we'll make sure that the migration table actually exists before we
        // start trying to rollback and re-run all of the migrations. If it's not
        // present we will just bail out with a info message for the developer.
        if (!$this->migrator->tableExists()) {
            return $this->comment('Migration table not found.');
        }

        $this->migrator->reset($this->getMigrationPaths(), [
            'seed' => $this->option('seed'),
        ]);

        // Once the migrator has run we will grab the note output and send it out to
        // the console screen, since the migrator itself functions without having
        // any instances of the OutputInterface contract passed into the class.
        foreach ($this->migrator->getNotes() as $note) {
            $this->output->writeln($note);
        }
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to use.'],
            ['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production.'],
            ['seed', null, InputOption::VALUE_NONE, 'Indicates if the seed task should be reset.'],
        ];
    }
}


text:
package org.sakuli.services.forwarder;

import org.sakuli.datamodel.state.TestCaseState;
import org.sakuli.services.forwarder.gearman.GearmanProperties;

import static org.mockito.Mockito.when;

/**
 * @author tschneck
 *         Date: 14.07.14
 */
public class MonitoringPropertiesTestHelper {

    public static final String NAGIOS_CHECK_COMMAND_DEFAULT = "check_sakuli";
    public static final String TEMPLATE_SUITE_SUMMARY = "{{state_short}} Sakuli suite \"{{id}}\" {{suite_summary}}. (Last suite run: {{stop_date}})";

    public static AbstractMonitoringTemplateProperties initMonitoringMock(AbstractMonitoringTemplateProperties mock) {
        when(mock.getTemplateSuiteSummary()).thenReturn(
                TEMPLATE_SUITE_SUMMARY
        );
        when(mock.lookUpTemplate(TestCaseState.OK)).thenReturn(
                "{{state_short}} case \"{{id}}\" ran in {{duration}}s - {{state_description}}"
        );
        when(mock.lookUpTemplate(TestCaseState.WARNING)).thenReturn(
                "{{state_short}} case \"{{id}}\" over runtime ({{duration}}s/warn at {{warning_threshold}}s){{step_information}}"
        );
        when(mock.lookUpTemplate(TestCaseState.WARNING_IN_STEP)).thenReturn(
                "{{state_short}} case \"{{id}}\" ({{duration}}s) ok{{step_information}}"
        );
        when(mock.lookUpTemplate(TestCaseState.CRITICAL)).thenReturn(
                "{{state_short}} case \"{{id}}\" over runtime ({{duration}}s/crit at {{critical_threshold}}s){{step_information}}"
        );
        when(mock.lookUpTemplate(TestCaseState.ERRORS)).thenReturn(
                "{{state_short}} case \"{{id}}\" {{state_description}}: {{error_message}}"
        );
        when(mock.getTemplateSuiteSummaryMaxLength()).thenReturn(200);
        return mock;
    }

    public static GearmanProperties initMock(GearmanProperties mock) {
        initMonitoringMock(mock);
        when(mock.getNagiosCheckCommand()).thenReturn(NAGIOS_CHECK_COMMAND_DEFAULT);
        when(mock.getTemplateSuiteTable()).thenReturn(
                "{{state_short}} Sakuli suite \"{{id}}\" {{suite_summary}}. (Last suite run: {{stop_date}}){{error_screenshot}}"
        );
        when(mock.lookUpTemplate(TestCaseState.ERRORS)).thenReturn(
                "{{state_short}} case \"{{id}}\" {{state_description}}: {{error_message}}{{error_screenshot}}"
        );
        when(mock.getTemplateScreenshotDivWidth()).thenReturn("640px");
        when(mock.getServiceType()).thenReturn("passive");
        return mock;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using HIO.Backup.Enumerations;

namespace HIO.Backup.Model
{
    public class FileBackupMeta
    {
        public FileBackupType Type;
        public string Hash;
        public Guid FullBackupId = Guid.Empty;

        // - Overrides
        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType()) return false;

            FileBackupMeta x = (FileBackupMeta)obj;

            if (this.Type != x.Type) return false;
            if (this.Hash != x.Hash) return false;
            if (this.FullBackupId != x.FullBackupId) return false;
            return true;
        }

        public override int GetHashCode()
        {
            int type_hash = this.Type.GetHashCode();
            int hash_hash = this.Hash.GetHashCode();
            int bckp_hash = this.FullBackupId.GetHashCode();

            return type_hash ^ hash_hash ^ bckp_hash;
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="HashUtility.cs" company="Sean McElroy">
//   Copyright Sean McElroy; released as open-source software under the licensing terms of the MIT License.
// </copyright>
// <summary>
//   Convenience utilities for hashing data
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Mystiko.Cryptography
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Security.Cryptography;
    using System.Threading.Tasks;

    using JetBrains.Annotations;

    using Mystiko.Net;

    /// <summary>
    /// Convenience utilities for hashing data
    /// </summary>
    public static class HashUtility
    {
        /// <summary>
        /// An instance of a hashing algorithm
        /// </summary>
        [NotNull]
        private static readonly SHA512 Hasher = SHA512.Create();

        /// <summary>
        /// Provides the SHA512 hash of the <paramref name="source"/> file, and also provides the first and last 64 bytes of that file.
        /// </summary>
        /// <param name="source">The file to hash</param>
        [NotNull, ItemNotNull, Pure]
        public static async Task<Tuple<byte[], byte[], byte[]>> HashFileSHA512Async([NotNull] FileInfo source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            using (var fs = new FileStream(source.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                return await HashFileSHA512Async(fs);
            }
        }

        /// <summary>
        /// Provides the SHA512 hash of the <paramref name="source"/> file, and also provides the first and last 64 bytes of that file.
        /// </summary>
        /// <param name="source">The file to hash</param>
        [NotNull, ItemNotNull, Pure]
        public static async Task<Tuple<byte[], byte[], byte[]>> HashFileSHA512Async([NotNull] Stream source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            using (var sha = SHA512.Create())
            using (var bsSource = new BufferedStream(source, 1024 * 1024 * 16))
            {
                bsSource.Seek(0, SeekOrigin.Begin);
                var first64Bytes = new byte[64];
                await bsSource.ReadAsync(first64Bytes, 0, 64);

                bsSource.Seek(0, SeekOrigin.Begin);
                Debug.Assert(sha != null, "sha != null");
                var hash = sha.ComputeHash(bsSource);

                bsSource.Seek(-64, SeekOrigin.End);
                var last64Bytes = new byte[64];
                await bsSource.ReadAsync(last64Bytes, 0, 64);

                return new Tuple<byte[], byte[], byte[]>(hash, first64Bytes, last64Bytes);
            }
        }

        /// <summary>
        /// Computes a hash for this block for the given pre-calculated header and a given nonce value
        /// </summary>
        /// <param name="nonce">The value to which to apply to the last eight bytes of the <paramref name="preNonceArray"/> before calculating the hash</param>
        /// <param name="preNonceArray">The output from the byte array for the header of this block</param>
        /// <returns>The hash for given pre-calculated header and a given nonce value</returns>
        [NotNull, Pure]
        public static byte[] HashForNonce(long nonce, [NotNull] byte[] preNonceArray)
        {
            if (preNonceArray == null)
                throw new ArgumentNullException(nameof(preNonceArray));
            if (preNonceArray.Length == 0)
                throw new ArgumentException("Value cannot be an empty collection.", nameof(preNonceArray));

            Array.Copy(BitConverter.GetBytes(nonce), 0, preNonceArray, preNonceArray.Length - 8, 8);
            return Hasher.ComputeHash(preNonceArray);
        }

        /// <summary>
        /// Finds the nonce value that would make this block have the <paramref name="zeroCount"/> number of zeros at the
        /// start of its hash value
        /// </summary>
        /// <param name="input">
        /// The input byte array to hash
        /// </param>
        /// <param name="zeroCount">
        /// The number of zeros for which to find the first nonce
        /// </param>
        /// <returns>
        /// The nonce value that makes this block's header have the required number of leading zeros
        /// </returns>
        [Pure]
        public static uint HashForZeroCount([NotNull] byte[] input, int zeroCount)
        {
            if (input == null)
                throw new ArgumentNullException(nameof(input));
            if (input.Length == 0)
                throw new ArgumentException("Value cannot be an empty collection.", nameof(input));

            var best = 0;

            for (var l = 0U; l < uint.MaxValue; l++)
            {
                var candidateHash = HashForNonce(l, input);
                var success = false;
                var candidateHashString = BitConverter.ToString(candidateHash).Replace("-", string.Empty);

                var i = 0;
                foreach (var c in candidateHashString)
                {
                    if (c == '0')
                    {
                        i++;
                        if (i == zeroCount)
                        {
                            success = true;
                            best = Math.Max(best, i);
                            break;
                        }
                    }
                    else
                    {
                        best = Math.Max(best, i);
                        break;
                    }
                }

                if (l % 10000 == 0)
                {
                    Console.Write($"\rBest: {best} of {zeroCount} (#{l:N0})");
                }

                if (success)
                {
                    Console.Write($"\rBest: {best} of {zeroCount} (#{l:N0})");
                    return l;
                }
            }

            throw new InvalidOperationException($"Unable to find any hash that returns {zeroCount} zeros");
        }

        /// <summary>
        /// Validates the nonce of the identity matches the <paramref name="targetDifficulty"/> number of leading zeros required
        /// </summary>
        /// <param name="dateEpoch">The date the identity was created, expressed in the number of seconds since the epoch (January 1, 1970)</param>
        /// <param name="publicKeyX">The value of the public key X-value for this identity</param>
        /// <param name="publicKeyY">The value of the public key Y-value for this identity</param>
        /// <param name="nonce">The nonce value that when applied the nonce value that when applied </param>
        /// <param name="targetDifficulty">The number of leading zeros required for the nonce-derived combined hash</param>
        /// <returns>A value indicating whether or not the <see cref="nonce"/> value has the requisite number of leading zeros when hashed together with other fields of this identity</returns>
        [NotNull, Pure]
        public static ValidateIdentityResult ValidateIdentity(ulong dateEpoch, [NotNull] byte[] publicKeyX, [NotNull] byte[] publicKeyY, ulong nonce, byte targetDifficulty)
        {
            byte[] identityBytes;
            using (var ms = new MemoryStream())
            using (var bw = new BinaryWriter(ms))
            {
                bw.Write(dateEpoch);
                bw.Write(publicKeyX);
                bw.Write(publicKeyY);
                bw.Write(nonce);
                identityBytes = ms.ToArray();
            }

            using (var sha = SHA512.Create())
            {
                Debug.Assert(sha != null, "sha != null");
                var candidateHash = sha.ComputeHash(identityBytes);
                var candidateHashString = BitConverter.ToString(candidateHash).Replace("-", string.Empty);

                byte i = 0;
                foreach (var c in candidateHashString)
                {
                    if (c == '0')
                    {
                        i++;
                        if (i == targetDifficulty)
                        {
                            return new ValidateIdentityResult(true, i, candidateHashString);
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return new ValidateIdentityResult(false, targetDifficulty, null);
        }

        /// <summary>
        /// Validates the nonce of the identity matches the <paramref name="targetDifficulty"/> number of leading zeros required
        /// </summary>
        /// <param name="serverNodeIdentity">The identity to validate to the supplied <paramref name="targetDifficulty"/></param>
        /// <param name="targetDifficulty">The number of leading zeros required for the nonce-derived combined hash</param>
        /// <returns>A value indicating whether or not the <see cref="ServerNodeIdentity.Nonce"/> on the <paramref name="serverNodeIdentity"/> object has the requisite number of leading zeros when hashed together with other fields of this identity</returns>
        [NotNull, Pure]
        public static ValidateIdentityResult ValidateIdentity([NotNull] ServerNodeIdentity serverNodeIdentity, byte targetDifficulty)
        {
            if (serverNodeIdentity == null)
                throw new ArgumentNullException(nameof(serverNodeIdentity));

            return ValidateIdentity(serverNodeIdentity.DateEpoch, serverNodeIdentity.PublicKeyX, serverNodeIdentity.PublicKeyY, serverNodeIdentity.Nonce, targetDifficulty);
        }
    }
}


text:
/**
 * @namespace
 * @property {String} id=abc123   The identifier.
 * @property {Object} defaults    The default values.
 * @property {Number} defaults.a  The a property of the defaults.
 * @property {String} defaults.b  The b property of the defaults.
 */
var myobject = {
    id: "abc123",
    defaults: {
        a: 1,
        b: "Hit the light",
        c: true
    }
};


text:
namespace metis {

FreeList::FreeList(usize maxAlloc, MemPool *srcPool, MemPool *selfPool)
    : Opaque(make_private<FreeListPrivate>(this, selfPool)) {
  auto m = priv<FreeListPrivate>();
  if (maxAlloc > 0) {
    m->initialize(maxAlloc, srcPool);
  }
}

FreeList::~FreeList() {
  auto m = priv<FreeListPrivate>();
#if METIS_DEBUG_ENABLE
  METIS_ASSERT(m->n_used == 0);
#endif
  m->release_memory();
}

FreeListPrivate::~FreeListPrivate() {
}

void *FreeList::allocate(usize size, usize align) {
  auto m = priv<FreeListPrivate>();

  METIS_ASSERT(size > 0 && size <= m->node_capac);
  METIS_ASSERT(align > 0 && (align == 1 || (align % 2) == 0));
  METIS_ASSERT((size % align) == 0);

  MemNode *node;
  if (m->free_list.first()) {
    // If there's any free node, take the first one to be used
    node = MemNode::from_list_node(m->free_list.detach(m->free_list.first()));
    m->n_free -= 1;
  } else {
    // If there's no free node allocate a new one
    node = m->allocate_new_node();
  }

  // Add this node to the list of used nodes
  m->used_list.append(&node->node);

  // Ensure user-required alignment
  char *cursor = node->data();
  usize misalig = 0;
  if ((misalig = (reinterpret_cast<usize>(cursor) % align))) {
    misalig = (align - misalig);

    METIS_ASSERT((size + misalig) <= m->node_capac);
    cursor += misalig;
  }

  // Informs deallocate() the offset to the beginning of the node
  auto offset = reinterpret_cast<isize *>(cursor - sizeof(isize));
  *offset = isize(MemNode::header_size() + misalig);

  m->n_used += 1;

  METIS_ASSERT((reinterpret_cast<usize>(cursor) % align) == 0);
  return cursor;
}

void FreeList::deallocate(void *address, usize size) {
  auto m = priv<FreeListPrivate>();
  auto cursor = static_cast<char *>(address);

  METIS_ASSERT(address);
  METIS_ASSERT(size > 0 && size <= m->node_capac);

  // Gets the node from the user buffer
  auto offset = reinterpret_cast<isize *>(cursor - sizeof(isize));
  MemNode *node = reinterpret_cast<MemNode *>(cursor - (*offset));

  // Put this free'd node the the free list
  m->used_list.detach(&node->node);
  m->free_list.append(&node->node);
  m->n_used -= 1;
  m->n_free += 1;
}

void FreeList::initialize(usize maxAlloc, MemPool *srcPool) {
  priv<FreeListPrivate>()->initialize(maxAlloc, srcPool);
}

void FreeListPrivate::initialize(usize maxAlloc, MemPool *srcPool) {
  release_memory();

  METIS_ASSERT(maxAlloc >= 8 && maxAlloc <= consts::GIGA);

  this->src_pool = MemPool::ensure(srcPool);
  node_capac = maxAlloc;
  node_size = node_capac + MemNode::header_size();
}

void FreeList::release_memory() {
  priv<FreeListPrivate>()->release_memory();
}

void FreeListPrivate::release_memory() {

  if (src_pool) {
    free_list.clear([this](FreeListNode *link) {
      src_pool->deallocate(MemNode::from_list_node(link), node_size);
    });
    used_list.clear([this](FreeListNode *link) {
      src_pool->deallocate(MemNode::from_list_node(link), node_size);
    });

    n_used = 0;
    n_free = 0;
    node_size = 0;
    node_capac = 0;
  }
}

usize FreeList::max_alloc_size() const noexcept {
  auto m = priv<FreeListPrivate>();
  return m->node_capac;
}

}  // namespace metis


text:
package edu.uci.ics.hyracks.storage.am.lsm.invertedindex.impls;

import java.io.File;
import java.util.List;

import edu.uci.ics.hyracks.api.dataflow.value.IBinaryComparatorFactory;
import edu.uci.ics.hyracks.api.dataflow.value.ITypeTraits;
import edu.uci.ics.hyracks.api.io.FileReference;
import edu.uci.ics.hyracks.storage.am.bloomfilter.impls.BloomFilterFactory;
import edu.uci.ics.hyracks.storage.am.common.api.IVirtualFreePageManager;
import edu.uci.ics.hyracks.storage.am.common.api.IndexException;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMComponentFilterFactory;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMComponentFilterFrameFactory;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallback;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMIndexFileManager;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.ILSMOperationTracker;
import edu.uci.ics.hyracks.storage.am.lsm.common.api.IVirtualBufferCache;
import edu.uci.ics.hyracks.storage.am.lsm.common.impls.BTreeFactory;
import edu.uci.ics.hyracks.storage.am.lsm.common.impls.LSMComponentFilterManager;
import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.inmemory.InMemoryInvertedIndex;
import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.ondisk.OnDiskInvertedIndexFactory;
import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.tokenizers.IBinaryTokenizerFactory;
import edu.uci.ics.hyracks.storage.am.lsm.invertedindex.util.InvertedIndexUtils;
import edu.uci.ics.hyracks.storage.common.file.IFileMapProvider;

public class PartitionedLSMInvertedIndex extends LSMInvertedIndex {

    public PartitionedLSMInvertedIndex(List<IVirtualBufferCache> virtualBufferCaches,
            OnDiskInvertedIndexFactory diskInvIndexFactory, BTreeFactory deletedKeysBTreeFactory,
            BloomFilterFactory bloomFilterFactory, ILSMComponentFilterFactory filterFactory,
            ILSMComponentFilterFrameFactory filterFrameFactory, LSMComponentFilterManager filterManager,
            double bloomFilterFalsePositiveRate, ILSMIndexFileManager fileManager,
            IFileMapProvider diskFileMapProvider, ITypeTraits[] invListTypeTraits,
            IBinaryComparatorFactory[] invListCmpFactories, ITypeTraits[] tokenTypeTraits,
            IBinaryComparatorFactory[] tokenCmpFactories, IBinaryTokenizerFactory tokenizerFactory,
            ILSMMergePolicy mergePolicy, ILSMOperationTracker opTracker, ILSMIOOperationScheduler ioScheduler,
            ILSMIOOperationCallback ioOpCallback, int[] invertedIndexFields, int[] filterFields,
            int[] filterFieldsForNonBulkLoadOps, int[] invertedIndexFieldsForNonBulkLoadOps) throws IndexException {
        super(virtualBufferCaches, diskInvIndexFactory, deletedKeysBTreeFactory, bloomFilterFactory, filterFactory,
                filterFrameFactory, filterManager, bloomFilterFalsePositiveRate, fileManager, diskFileMapProvider,
                invListTypeTraits, invListCmpFactories, tokenTypeTraits, tokenCmpFactories, tokenizerFactory,
                mergePolicy, opTracker, ioScheduler, ioOpCallback, invertedIndexFields, filterFields,
                filterFieldsForNonBulkLoadOps, invertedIndexFieldsForNonBulkLoadOps);
    }

    @Override
    protected InMemoryInvertedIndex createInMemoryInvertedIndex(IVirtualBufferCache virtualBufferCache,
            IVirtualFreePageManager virtualFreePageManager, int id) throws IndexException {
        return InvertedIndexUtils.createPartitionedInMemoryBTreeInvertedindex(virtualBufferCache,
                virtualFreePageManager, invListTypeTraits, invListCmpFactories, tokenTypeTraits, tokenCmpFactories,
                tokenizerFactory, new FileReference(new File(fileManager.getBaseDir() + "_virtual_vocab_" + id)));
    }

}


text:
/* @flow */

import { destroyAll as _destroyAll } from 'xcomponent/src';
import { ZalgoPromise } from 'zalgo-promise/src';
import * as _postRobot from 'post-robot/src'; // eslint-disable-line import/no-namespace

import { isPayPalDomain } from './lib';
import {  Checkout as _Checkout, Login as _Login, enableCheckoutIframe as _enableCheckoutIframe } from './components';

export const postRobot = _postRobot;
export { ZalgoPromise as Promise } from 'zalgo-promise/src';
export { PopupOpenError } from 'xcomponent/src';

export { rest } from './api';
export { Button, allowIframe as forceIframe, allowIframe } from './components';
export { setup } from './setup';
export { config, ENV, USERS, SOURCE, FUNDING, CARD } from './config';
export { request, isEligible, isWebView } from './lib';
export { logExperimentTreatment } from './experiments';

export let onPossiblyUnhandledException = ZalgoPromise.onPossiblyUnhandledException;

export let version = __MINOR_VERSION__;

export let checkout;
export let apps;

if (__LEGACY_SUPPORT__) {
    let legacy = require('./legacy');
    checkout = legacy.checkout;
    apps = legacy.apps;
}

// -------------------------------------------------------------

export let Checkout;
export let PayPalCheckout;
export let Login;
export let destroyAll;
export let enableCheckoutIframe;

if (isPayPalDomain() || __TEST__) {
    Checkout = _Checkout;
    PayPalCheckout = _Checkout;
    Login = _Login;
    enableCheckoutIframe = _enableCheckoutIframe;
    destroyAll = _destroyAll;
}


text:
import OfflineGlobals from 'ember-flexberry/services/offline-globals';
import { merge } from '@ember/polyfills';

export default OfflineGlobals.reopen({
  init() {
    this._super(...arguments);

  },
  getOfflineSchema() {
    let parentSchema = this._super(...arguments);
    let returnedSchema = merge(parentSchema, {

    });

    return returnedSchema;
  }
});


text: Python Puzzlers in Codenvy


text:
import sbt._
import Keys._
import scala.collection.mutable.{ListBuffer}

trait Common {

  lazy val common = settings

  private[this] var settings = new ListBuffer[Setting[_]]

  settings ++= Project.defaultSettings

  settings += (organization := "us.stivers.blue")

  settings += (version := "0.11.1-SNAPSHOT")

  // Scala Compiler Options
  settings += (scalacOptions ++= Seq("-deprecation","-unchecked"))

  // disable publishing the main API jar
  settings += (publishArtifact in (Compile, packageDoc) := false)

  // disable publishing the main sources jar
  settings += (publishArtifact in (Compile, packageSrc) := false)

  // Runtime Dependencies
  settings += (libraryDependencies ++= Seq(
    "org.scalaz" %% "scalaz-core" % "6.0.4",
    "com.twitter" %% "util-core" % "1.12.13"    // Config
  ))

  // Test Dependencies
  settings += (libraryDependencies ++= Seq(
    "org.specs2" %% "specs2" % "1.12" % "test",
    "org.scala-tools.testing" %% "scalacheck" % "1.9" % "test"
  ))

  // Remote Resolvers
  settings += (resolvers ++= Seq(
    "scala-tools.org" at "http://scala-tools.org/repo-releases",
    "repo.codahale.com" at "http://repo.codahale.com",
    "maven.twitter.com" at "http://maven.twttr.com/",
    "repo.typesafe.com" at "http://repo.typesafe.com/typesafe/releases"
  ))

}


text:
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ptrace.h>
#include <linux/timer.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/kallsyms.h>
#include <linux/pci.h>
#include <linux/kdebug.h>
#include <linux/bug.h>
#include <linux/irq.h>
#include <asm/processor.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/atomic.h>
#include <asm/smp.h>
#include <asm/pgalloc.h>
#include <asm/cacheflush.h>
#include <asm/cpu-regs.h>
#include <asm/busctl-regs.h>
#include <unit/leds.h>
#include <asm/fpu.h>
#include <asm/gdb-stub.h>
#include <asm/sections.h>

#if (CONFIG_INTERRUPT_VECTOR_BASE & 0xffffff)
#error "INTERRUPT_VECTOR_BASE not aligned to 16MiB boundary!"
#endif

struct pt_regs *__frame; /* current frame pointer */
EXPORT_SYMBOL(__frame);

int kstack_depth_to_print = 24;

spinlock_t die_lock = __SPIN_LOCK_UNLOCKED(die_lock);

ATOMIC_NOTIFIER_HEAD(mn10300_die_chain);

/*
 * These constants are for searching for possible module text
 * segments. MODULE_RANGE is a guess of how much space is likely
 * to be vmalloced.
 */
#define MODULE_RANGE (8 * 1024 * 1024)

#define DO_ERROR(signr, prologue, str, name)			\
asmlinkage void name(struct pt_regs *regs, u32 intcode)		\
{								\
	prologue;						\
	if (die_if_no_fixup(str, regs, intcode))		\
		return;						\
	force_sig(signr, current);				\
}

#define DO_EINFO(signr, prologue, str, name, sicode)			\
asmlinkage void name(struct pt_regs *regs, u32 intcode)			\
{									\
	siginfo_t info;							\
	prologue;							\
	if (die_if_no_fixup(str, regs, intcode))			\
		return;							\
	info.si_signo = signr;						\
	if (signr == SIGILL && sicode == ILL_ILLOPC) {			\
		uint8_t opcode;						\
		if (get_user(opcode, (uint8_t __user *)regs->pc) == 0)	\
			if (opcode == 0xff)				\
				info.si_signo = SIGTRAP;		\
	}								\
	info.si_errno = 0;						\
	info.si_code = sicode;						\
	info.si_addr = (void *) regs->pc;				\
	force_sig_info(info.si_signo, &info, current);			\
}

DO_ERROR(SIGTRAP, {}, "trap",			trap);
DO_ERROR(SIGSEGV, {}, "ibreak",			ibreak);
DO_ERROR(SIGSEGV, {}, "obreak",			obreak);
DO_EINFO(SIGSEGV, {}, "access error",		access_error,	SEGV_ACCERR);
DO_EINFO(SIGSEGV, {}, "insn access error",	insn_acc_error,	SEGV_ACCERR);
DO_EINFO(SIGSEGV, {}, "data access error",	data_acc_error,	SEGV_ACCERR);
DO_EINFO(SIGILL,  {}, "privileged opcode",	priv_op,	ILL_PRVOPC);
DO_EINFO(SIGILL,  {}, "invalid opcode",		invalid_op,	ILL_ILLOPC);
DO_EINFO(SIGILL,  {}, "invalid ex opcode",	invalid_exop,	ILL_ILLOPC);
DO_EINFO(SIGBUS,  {}, "invalid address",	mem_error,	BUS_ADRERR);
DO_EINFO(SIGBUS,  {}, "bus error",		bus_error,	BUS_ADRERR);
DO_EINFO(SIGILL,  {}, "FPU invalid opcode", 	fpu_invalid_op,	ILL_COPROC);

DO_ERROR(SIGTRAP,
#ifndef CONFIG_MN10300_USING_JTAG
	 DCR &= ~0x0001,
#else
	 {},
#endif
	 "single step", istep);

/*
 * handle NMI
 */
asmlinkage void nmi(struct pt_regs *regs, enum exception_code code)
{
	/* see if gdbstub wants to deal with it */
#ifdef CONFIG_GDBSTUB
	if (gdbstub_intercept(regs, code))
		return;
#endif

	printk(KERN_WARNING "--- Register Dump ---\n");
	show_registers(regs);
	printk(KERN_WARNING "---------------------\n");
}

/*
 * show a stack trace from the specified stack pointer
 */
void show_trace(unsigned long *sp)
{
	unsigned long *stack, addr, module_start, module_end;
	int i;

	printk(KERN_EMERG "\nCall Trace:");

	stack = sp;
	i = 0;
	module_start = VMALLOC_START;
	module_end = VMALLOC_END;

	while (((long) stack & (THREAD_SIZE - 1)) != 0) {
		addr = *stack++;
		if (__kernel_text_address(addr)) {
#if 1
			printk(" [<%08lx>]", addr);
			print_symbol(" %s", addr);
			printk("\n");
#else
			if ((i % 6) == 0)
				printk(KERN_EMERG "  ");
			printk("[<%08lx>] ", addr);
			i++;
#endif
		}
	}

	printk("\n");
}

/*
 * show the raw stack from the specified stack pointer
 */
void show_stack(struct task_struct *task, unsigned long *sp)
{
	unsigned long *stack;
	int i;

	if (!sp)
		sp = (unsigned long *) &sp;

	stack = sp;
	printk(KERN_EMERG "Stack:");
	for (i = 0; i < kstack_depth_to_print; i++) {
		if (((long) stack & (THREAD_SIZE - 1)) == 0)
			break;
		if ((i % 8) == 0)
			printk(KERN_EMERG "  ");
		printk("%08lx ", *stack++);
	}

	show_trace(sp);
}

/*
 * the architecture-independent dump_stack generator
 */
void dump_stack(void)
{
	unsigned long stack;

	show_stack(current, &stack);
}
EXPORT_SYMBOL(dump_stack);

/*
 * dump the register file in the specified exception frame
 */
void show_registers_only(struct pt_regs *regs)
{
	unsigned long ssp;

	ssp = (unsigned long) regs + sizeof(*regs);

	printk(KERN_EMERG "PC:  %08lx EPSW:  %08lx  SSP: %08lx mode: %s\n",
	       regs->pc, regs->epsw, ssp, user_mode(regs) ? "User" : "Super");
	printk(KERN_EMERG "d0:  %08lx   d1:  %08lx   d2: %08lx   d3: %08lx\n",
	       regs->d0, regs->d1, regs->d2, regs->d3);
	printk(KERN_EMERG "a0:  %08lx   a1:  %08lx   a2: %08lx   a3: %08lx\n",
	       regs->a0, regs->a1, regs->a2, regs->a3);
	printk(KERN_EMERG "e0:  %08lx   e1:  %08lx   e2: %08lx   e3: %08lx\n",
	       regs->e0, regs->e1, regs->e2, regs->e3);
	printk(KERN_EMERG "e4:  %08lx   e5:  %08lx   e6: %08lx   e7: %08lx\n",
	       regs->e4, regs->e5, regs->e6, regs->e7);
	printk(KERN_EMERG "lar: %08lx   lir: %08lx  mdr: %08lx  usp: %08lx\n",
	       regs->lar, regs->lir, regs->mdr, regs->sp);
	printk(KERN_EMERG "cvf: %08lx   crl: %08lx  crh: %08lx  drq: %08lx\n",
	       regs->mcvf, regs->mcrl, regs->mcrh, regs->mdrq);
	printk(KERN_EMERG "threadinfo=%p task=%p)\n",
	       current_thread_info(), current);

	if ((unsigned long) current >= 0x90000000UL &&
	    (unsigned long) current < 0x94000000UL)
		printk(KERN_EMERG "Process %s (pid: %d)\n",
		       current->comm, current->pid);

	printk(KERN_EMERG "CPUP:   %04hx\n", CPUP);
	printk(KERN_EMERG "TBR:    %08x\n", TBR);
	printk(KERN_EMERG "DEAR:   %08x\n", DEAR);
	printk(KERN_EMERG "sISR:   %08x\n", sISR);
	printk(KERN_EMERG "NMICR:  %04hx\n", NMICR);
	printk(KERN_EMERG "BCBERR: %08x\n", BCBERR);
	printk(KERN_EMERG "BCBEAR: %08x\n", BCBEAR);
	printk(KERN_EMERG "MMUFCR: %08x\n", MMUFCR);
	printk(KERN_EMERG "IPTEU : %08x  IPTEL2: %08x\n", IPTEU, IPTEL2);
	printk(KERN_EMERG "DPTEU:  %08x  DPTEL2: %08x\n", DPTEU, DPTEL2);
}

/*
 * dump the registers and the stack
 */
void show_registers(struct pt_regs *regs)
{
	unsigned long sp;
	int i;

	show_registers_only(regs);

	if (!user_mode(regs))
		sp = (unsigned long) regs + sizeof(*regs);
	else
		sp = regs->sp;

	/* when in-kernel, we also print out the stack and code at the
	 * time of the fault..
	 */
	if (!user_mode(regs)) {
		printk(KERN_EMERG "\n");
		show_stack(current, (unsigned long *) sp);

#if 0
		printk(KERN_EMERG "\nCode: ");
		if (regs->pc < PAGE_OFFSET)
			goto bad;

		for (i = 0; i < 20; i++) {
			unsigned char c;
			if (__get_user(c, &((unsigned char *) regs->pc)[i]))
				goto bad;
			printk("%02x ", c);
		}
#else
		i = 0;
#endif
	}

	printk("\n");
	return;

#if 0
bad:
	printk(KERN_EMERG " Bad PC value.");
	break;
#endif
}

/*
 *
 */
void show_trace_task(struct task_struct *tsk)
{
	unsigned long sp = tsk->thread.sp;

	/* User space on another CPU? */
	if ((sp ^ (unsigned long) tsk) & (PAGE_MASK << 1))
		return;

	show_trace((unsigned long *) sp);
}

/*
 * note the untimely death of part of the kernel
 */
void die(const char *str, struct pt_regs *regs, enum exception_code code)
{
	console_verbose();
	spin_lock_irq(&die_lock);
	printk(KERN_EMERG "\n%s: %04x\n",
	       str, code & 0xffff);
	show_registers(regs);

	if (regs->pc >= 0x02000000 && regs->pc < 0x04000000 &&
	    (regs->epsw & (EPSW_IM | EPSW_IE)) != (EPSW_IM | EPSW_IE)) {
		printk(KERN_EMERG "Exception in usermode interrupt handler\n");
		printk(KERN_EMERG "\nPlease connect to kernel debugger !!\n");
		asm volatile ("0: bra 0b");
	}

	spin_unlock_irq(&die_lock);
	do_exit(SIGSEGV);
}

/*
 * see if there's a fixup handler we can force a jump to when an exception
 * happens due to something kernel code did
 */
int die_if_no_fixup(const char *str, struct pt_regs *regs,
		    enum exception_code code)
{
	if (user_mode(regs))
		return 0;

	peripheral_leds_display_exception(code);

	switch (code) {
		/* see if we can fixup the kernel accessing memory */
	case EXCEP_ITLBMISS:
	case EXCEP_DTLBMISS:
	case EXCEP_IAERROR:
	case EXCEP_DAERROR:
	case EXCEP_MEMERR:
	case EXCEP_MISALIGN:
	case EXCEP_BUSERROR:
	case EXCEP_ILLDATACC:
	case EXCEP_IOINSACC:
	case EXCEP_PRIVINSACC:
	case EXCEP_PRIVDATACC:
	case EXCEP_DATINSACC:
		if (fixup_exception(regs))
			return 1;
	case EXCEP_UNIMPINS:
		if (regs->pc && *(uint8_t *)regs->pc == 0xff)
			if (notify_die(DIE_BREAKPOINT, str, regs, code, 0, 0))
				return 1;
		break;
	default:
		break;
	}

	/* see if gdbstub wants to deal with it */
#ifdef CONFIG_GDBSTUB
	if (gdbstub_intercept(regs, code))
		return 1;
#endif

	if (notify_die(DIE_GPF, str, regs, code, 0, 0))
		return 1;

	/* make the process die as the last resort */
	die(str, regs, code);
}

/*
 * handle unsupported syscall instructions (syscall 1-15)
 */
static asmlinkage void unsupported_syscall(struct pt_regs *regs,
					   enum exception_code code)
{
	struct task_struct *tsk = current;
	siginfo_t info;

	/* catch a kernel BUG() */
	if (code == EXCEP_SYSCALL15 && !user_mode(regs)) {
		if (report_bug(regs->pc, regs) == BUG_TRAP_TYPE_BUG) {
#ifdef CONFIG_GDBSTUB
			gdbstub_intercept(regs, code);
#endif
		}
	}

	regs->pc -= 2; /* syscall return addr is _after_ the instruction */

	die_if_no_fixup("An unsupported syscall insn was used by the kernel\n",
			regs, code);

	info.si_signo	= SIGILL;
	info.si_errno	= ENOSYS;
	info.si_code	= ILL_ILLTRP;
	info.si_addr	= (void *) regs->pc;
	force_sig_info(SIGILL, &info, tsk);
}

/*
 * display the register file when the stack pointer gets clobbered
 */
asmlinkage void do_double_fault(struct pt_regs *regs)
{
	struct task_struct *tsk = current;

	strcpy(tsk->comm, "emergency tsk");
	tsk->pid = 0;
	console_verbose();
	printk(KERN_EMERG "--- double fault ---\n");
	show_registers(regs);
}

/*
 * asynchronous bus error (external, usually I/O DMA)
 */
asmlinkage void io_bus_error(u32 bcberr, u32 bcbear, struct pt_regs *regs)
{
	console_verbose();

	printk(KERN_EMERG "Asynchronous I/O Bus Error\n");
	printk(KERN_EMERG "==========================\n");

	if (bcberr & BCBERR_BEME)
		printk(KERN_EMERG "- Multiple recorded errors\n");

	printk(KERN_EMERG "- Faulting Buses:%s%s%s\n",
	       bcberr & BCBERR_BEMR_CI  ? " CPU-Ins-Fetch" : "",
	       bcberr & BCBERR_BEMR_CD  ? " CPU-Data" : "",
	       bcberr & BCBERR_BEMR_DMA ? " DMA" : "");

	printk(KERN_EMERG "- %s %s access made to %s at address %08x\n",
	       bcberr &	BCBERR_BEBST ? "Burst" : "Single",
	       bcberr &	BCBERR_BERW ? "Read" : "Write",
	       bcberr &	BCBERR_BESB_MON  ? "Monitor Space" :
	       bcberr &	BCBERR_BESB_IO   ? "Internal CPU I/O Space" :
	       bcberr &	BCBERR_BESB_EX   ? "External I/O Bus" :
	       bcberr &	BCBERR_BESB_OPEX ? "External Memory Bus" :
	       "On Chip Memory",
	       bcbear
	       );

	printk(KERN_EMERG "- Detected by the %s\n",
	       bcberr&BCBERR_BESD ? "Bus Control Unit" : "Slave Bus");

#ifdef CONFIG_PCI
#define BRIDGEREGB(X) (*(volatile __u8  *)(0xBE040000 + (X)))
#define BRIDGEREGW(X) (*(volatile __u16 *)(0xBE040000 + (X)))
#define BRIDGEREGL(X) (*(volatile __u32 *)(0xBE040000 + (X)))

	printk(KERN_EMERG "- PCI Memory Paging Reg:         %08x\n",
	       *(volatile __u32 *) (0xBFFFFFF4));
	printk(KERN_EMERG "- PCI Bridge Base Address 0:     %08x\n",
	       BRIDGEREGL(PCI_BASE_ADDRESS_0));
	printk(KERN_EMERG "- PCI Bridge AMPCI Base Address: %08x\n",
	       BRIDGEREGL(0x48));
	printk(KERN_EMERG "- PCI Bridge Command:                %04hx\n",
	       BRIDGEREGW(PCI_COMMAND));
	printk(KERN_EMERG "- PCI Bridge Status:                 %04hx\n",
	       BRIDGEREGW(PCI_STATUS));
	printk(KERN_EMERG "- PCI Bridge Int Status:         %08hx\n",
	       BRIDGEREGL(0x4c));
#endif

	printk(KERN_EMERG "\n");
	show_registers(regs);

	panic("Halted due to asynchronous I/O Bus Error\n");
}

/*
 * handle an exception for which a handler has not yet been installed
 */
asmlinkage void uninitialised_exception(struct pt_regs *regs,
					enum exception_code code)
{

	/* see if gdbstub wants to deal with it */
#ifdef CONFIG_GDBSTUB
	if (gdbstub_intercept(regs, code))
		return;
#endif

	peripheral_leds_display_exception(code);
	printk(KERN_EMERG "Uninitialised Exception 0x%04x\n", code & 0xFFFF);
	show_registers(regs);

	for (;;)
		continue;
}

/*
 * set an interrupt stub to jump to a handler
 * ! NOTE: this does *not* flush the caches
 */
void __init __set_intr_stub(enum exception_code code, void *handler)
{
	unsigned long addr;
	u8 *vector = (u8 *)(CONFIG_INTERRUPT_VECTOR_BASE + code);

	addr = (unsigned long) handler - (unsigned long) vector;
	vector[0] = 0xdc;		/* JMP handler */
	vector[1] = addr;
	vector[2] = addr >> 8;
	vector[3] = addr >> 16;
	vector[4] = addr >> 24;
	vector[5] = 0xcb;
	vector[6] = 0xcb;
	vector[7] = 0xcb;
}

/*
 * set an interrupt stub to jump to a handler
 */
void __init set_intr_stub(enum exception_code code, void *handler)
{
	unsigned long addr;
	u8 *vector = (u8 *)(CONFIG_INTERRUPT_VECTOR_BASE + code);

	addr = (unsigned long) handler - (unsigned long) vector;
	vector[0] = 0xdc;		/* JMP handler */
	vector[1] = addr;
	vector[2] = addr >> 8;
	vector[3] = addr >> 16;
	vector[4] = addr >> 24;
	vector[5] = 0xcb;
	vector[6] = 0xcb;
	vector[7] = 0xcb;

	mn10300_dcache_flush_inv();
	mn10300_icache_inv();
}

/*
 * set an interrupt stub to invoke the JTAG unit and then jump to a handler
 */
void __init set_jtag_stub(enum exception_code code, void *handler)
{
	unsigned long addr;
	u8 *vector = (u8 *)(CONFIG_INTERRUPT_VECTOR_BASE + code);

	addr = (unsigned long) handler - ((unsigned long) vector + 1);
	vector[0] = 0xff;		/* PI to jump into JTAG debugger */
	vector[1] = 0xdc;		/* jmp handler */
	vector[2] = addr;
	vector[3] = addr >> 8;
	vector[4] = addr >> 16;
	vector[5] = addr >> 24;
	vector[6] = 0xcb;
	vector[7] = 0xcb;

	mn10300_dcache_flush_inv();
	flush_icache_range((unsigned long) vector, (unsigned long) vector + 8);
}

/*
 * initialise the exception table
 */
void __init trap_init(void)
{
	set_excp_vector(EXCEP_TRAP,		trap);
	set_excp_vector(EXCEP_ISTEP,		istep);
	set_excp_vector(EXCEP_IBREAK,		ibreak);
	set_excp_vector(EXCEP_OBREAK,		obreak);

	set_excp_vector(EXCEP_PRIVINS,		priv_op);
	set_excp_vector(EXCEP_UNIMPINS,		invalid_op);
	set_excp_vector(EXCEP_UNIMPEXINS,	invalid_exop);
	set_excp_vector(EXCEP_MEMERR,		mem_error);
	set_excp_vector(EXCEP_MISALIGN,		misalignment);
	set_excp_vector(EXCEP_BUSERROR,		bus_error);
	set_excp_vector(EXCEP_ILLINSACC,	insn_acc_error);
	set_excp_vector(EXCEP_ILLDATACC,	data_acc_error);
	set_excp_vector(EXCEP_IOINSACC,		insn_acc_error);
	set_excp_vector(EXCEP_PRIVINSACC,	insn_acc_error);
	set_excp_vector(EXCEP_PRIVDATACC,	data_acc_error);
	set_excp_vector(EXCEP_DATINSACC,	insn_acc_error);
	set_excp_vector(EXCEP_FPU_DISABLED,	fpu_disabled);
	set_excp_vector(EXCEP_FPU_UNIMPINS,	fpu_invalid_op);
	set_excp_vector(EXCEP_FPU_OPERATION,	fpu_exception);

	set_excp_vector(EXCEP_NMI,		nmi);

	set_excp_vector(EXCEP_SYSCALL1,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL2,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL3,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL4,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL5,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL6,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL7,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL8,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL9,		unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL10,	unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL11,	unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL12,	unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL13,	unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL14,	unsupported_syscall);
	set_excp_vector(EXCEP_SYSCALL15,	unsupported_syscall);
}

/*
 * determine if a program counter value is a valid bug address
 */
int is_valid_bugaddr(unsigned long pc)
{
	return pc >= PAGE_OFFSET;
}


text:
r""" Places and Divisors :mod:`divisor`
==================================

A module defining places and divisors on a Riemann surface. A *regular
affine place* is simply given as an :math:`(x_0,y_0)` tuple on the curve
:math:`C : f(x,y) = 0` from which the Riemann surface is defined.

Classes
-------

.. autosummary::

    Divisor
    Place

Functions
---------

.. autosummary::

    ZeroDivisor

Examples
--------

Contents
--------

"""

from sage.all import infinity

class Divisor(object):
    r"""A divisor on a Riemann surface.

    A divisor is a formal sum of :py:class:`Place`s :math:`P_i` along
    with multiplicities :math:`m_i` usually written,

    .. math::

        D = m_1 P_1 + \cdots m_k P_k,

    where the places :math:`P_i` are distinct.

    Attributes
    ----------
    places : list
        A list of the distinct places in this divisor.
    multiplicities : list
        The corresponding multiplicities of the places in this divisor.

    """
    @property
    def places(self):
        return tuple(self._d.keys())

    @property
    def multiplicities(self):
        return tuple(self._d.values())

    @property
    def items(self):
        return tuple(self._d.items())

    @property
    def degree(self):
        return sum(self.multiplicities)

    @property
    def dict(self):
        return self._d

    @dict.setter
    def dict(self, value):
        d = {P: m for P, m in value.items() if m}
        self._d = d

    def __init__(self, RS, d):
        r"""Initialize a Divisor.

        Divisors can be constructed from a place, an iterable of places,
        or a dict with places as keys and multiplicities as values.

        Parameters
        ----------
        RS : RiemannSurface
            The surface on which the place is defined.
        d : dict
            A dictionary of places as keys and multiplicities as values.
        """
        self.RS = RS
        if isinstance(d, Divisor):
            self.__dict__ = d.__dict__.copy()
        elif isinstance(d, dict):
            self.dict = d
        elif d == 0:
            # construct the zero divisor
            self.dict = {}
        else:
            raise ValueError('d must be a dictionary')

    def __repr__(self):
        if not self.is_zero():
            s = ''
            for P,n in self:
                s += ' + '
                if n > 1:
                    s += str(n)
                elif n < 0:
                    s += '(' + str(n) + ')'
                s += P.name
            return s[3:]
        else:
            return 'Div0'

    def __getitem__(self, key):
        try:
            return self.dict[key]
        except KeyError:
            return 0

    def __iter__(self):
        return iter(self.dict.items())

    def __key(self):
        return (self.RS, self.dict)

    def __eq__(self, other):
        if isinstance(other, Divisor):
            return self.__key() == other.__key()
        return False

    def __hash__(self):
        # Unable to use dict in hash since dict is mutable
        return hash(self.RS)

    def __add__(self, other):
        if other == 0:
            return self

        if not isinstance(other,Divisor):
            raise ValueError('%s is not a Divisor on %s.'%(other,self.RS))

        if self.RS != other.RS:
            raise ValueError('Can only add or subtract divisors defined '
                             'on the same Riemann surface.')

        all_places = set(self.places + other.places)
        d = dict((P, self[P] + other[P]) for P in all_places)
        return Divisor(self.RS, d)

    def __radd__(self, other):
        return self.__add__(other)

    def __neg__(self):
        d = dict((P,-m) for P,m in self.items)
        return Divisor(self.RS, d)

    def __sub__(self, other):
        return self + other.__neg__()

    def __mul__(self, other):
        other = int(other)
        d = dict((P,other*m) for P,m in self.items)
        return Divisor(self.RS, d)

    def __rmul__(self, other):
        return self.__mul__(other)

    def is_zero(self):
        if self.dict == {}:
            return True
        return False

    def as_place(self):
        items = list(self.dict.items())
        if len(items) != 1:
            raise ValueError('Divisor contains more than one place. '
                             'Cannot coerce to place.')
        P, m = items[0]
        if m != 1:
            raise ValueError('Divisor contains place of multiplicity. '
                             'Cannot coerce to single place.')
        return P

class ZeroDivisor(Divisor):
    r"""A class representing the zero divisor on a Riemann surface."""
    def __init__(self, RS):
        Divisor.__init__(self, RS, {})

class Place(Divisor):
    r"""A Place on a Riemann surface.

    In `abelfunctions` a Riemann surface is obtained by desingularizing
    and compactifying a complex algebraic curve. Every place :math:`P`
    on the resulting Riemann surface can be described in terms of a
    Puiseux series in a local parameter :math:`t`.

    .. math::

        P = (x(t), y(t))
        x(t) = \alpha + \lambda t^e
        y(t) = \sum_k \beta_k t^{n_k}

    When :math:`\alpha` is not a discriminant point or infinity of the
    curve then :math:`P = (x(0), y(0)) = (\alpha, \beta)` is sufficient
    in representing the place from the curve. Otherwise, multiple places
    may have the same projection onto the curve.

    Attributes
    ----------
    x : complex
        The x-projection of the place onto the underlying curve.
    y : complex
        The y-projection of the palce onto the underlying curve.
    name : string, optional
        A name given to the place. Used when the place is a term in a
        :py:class:`Divisor`.

    Methods
    -------

    is_discriminant

    """
    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not value:
            value = str((self.x,self.y))
        self._name = value

    def __init__(self, RS, name=None):
        self.RS = RS
        self.name = name
        Divisor.__init__(self, RS, {self:1})

    def __repr__(self):
        return self.name

    def __eq__(self, other):
        raise NotImplementedError('Override in Place subtype.')

    def __hash__(self):
        raise NotImplementedError('Override in Place subtype.')

    def as_place(self):
        return self

    def is_discriminant(self):
        raise NotImplementedError('Override in Place subtype.')

    def is_infinite(self):
        raise NotImplementedError('Override in Place subtype.')

    def valuation(self, omega):
        r"""Returns the valuation of `omega` at this place.

        The valuation of :math:`\omega` at this place :math:`P` is an
        integer :math:`m` such that

        .. math::

            \omega |_P = c t^m + O(t^{m+1})

        where :math:`P = P(0)` is given in terms of some local parameter
        :math:`t`.

        This method is a key ingredient in determining the valuation
        divisor of a differential :math:`\omega`.

        Parameters
        ----------
        omega : Differential

        Returns
        -------
        int
        """
        raise NotImplementedError('Override in Place subtype')

class RegularPlace(Place):
    r"""A regular place on a Riemann surface.

    """
    def __init__(self, RS, x, y, **kwds):
        r"""Initialize a regular place from a point on the curve.

        Parameters
        ----------
        RS : RiemannSurface
        x : complex
            The x-projection of the place onto the curve.
        y : complex
            The y-projection of the place onto the curve.
        """
        self.x = x
        self.y = y
        Place.__init__(self, RS, **kwds)

    def __key(self):
        return (self.RS, self.x, self.y)

    def __eq__(self, other):
        if isinstance(other, RegularPlace):
            return self.__key() == other.__key()
        return False

    def __hash__(self):
        return hash(self.__key())

    def is_discriminant(self):
        return False

    def is_infinite(self):
        return False

    def valuation(self, omega):
        f = self.RS.f
        x,y = f.parent().gens()
        a,b = self.x, self.y

        def mult(p, a, b):
            r"""Returns the multiplicity of the zero `(a,b)` on `p`."""
            pab = p(x + a, y + b)
            degrees = [sum(exp) for exp in pab.exponents()]
            return min(degrees)

        numer,denom = omega.as_numer_denom() # XXX
        zero_mult = mult(numer,a,b)
        pole_mult = mult(denom,a,b)
        return zero_mult - pole_mult

class DiscriminantPlace(Place):
    r"""A discriminant place on a Riemann surface.
    """
    def __init__(self, RS, P, **kwds):
        r"""Initialize a disc. place from its Puiseux series representation.

        Parameters
        ----------
        RS : RiemannSurface
        P : PuiseuxTSeries
        """
        self.puiseux_series = P
        self.x = P.x0
        self.y = P.eval_y(0)
        Place.__init__(self, RS, **kwds)
        self.name = str(P)

    def __repr__(self):
        return str(self.puiseux_series)

    def __key(self):
        return (self.RS, self.puiseux_series)

    def __eq__(self, other):
        if isinstance(other, DiscriminantPlace):
            return self.__key() == other.__key()
        return False

    def __hash__(self):
        return hash(self.__key())

    def is_discriminant(self):
        return True

    def is_infinite(self):
        xval = self.puiseux_series.eval_x(0)
        if xval == infinity:
            return True
        return False

    def valuation(self, omega):
        omegat = omega.localize(self)
        valuation = omegat.valuation()
        return valuation


text:
<?php

namespace Controller\Cms;

use RedKiteCms\Rendering\Controller\Cms\DashboardController as BaseDashboardController;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

/**
 * This object implements the Silex controller to render RedKite CMS dashboard
 *
 * @author  RedKite Labs <webmaster@redkite-labs.com>
 * @package Controller\Cms
 */
class DashboardController extends BaseDashboardController
{
    /**
     * Show dashboard action
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @param \Silex\Application                        $app
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction(Request $request, Application $app)
    {
        $options = array(
            'template_assets' => $app["red_kite_cms.template_assets"],
            'twig' => $app["twig"],
            'request' => $app["request"],
            'routes' => $app["red_kite_cms.website_routes"],
        );

        return parent::show($options);
    }
}


text:
package com.intuit.karate.driver.appium;

import com.intuit.karate.FileUtils;
import com.intuit.karate.core.ScenarioRuntime;
import java.util.Map;

/**
 * @author babusekaran
 */
public class AndroidDriver extends AppiumDriver {

    public static final String DRIVER_TYPE = "android";

    protected AndroidDriver(MobileDriverOptions options) {
        super(options);
    }

    public static AndroidDriver start(Map<String, Object> map, ScenarioRuntime sr) {
        MobileDriverOptions options = new MobileDriverOptions(map, sr, 4723, FileUtils.isOsWindows() ? "cmd.exe" : "appium");
        // additional commands needed to start appium on windows
        if (FileUtils.isOsWindows()){
            options.arg("/C");
            options.arg("cmd.exe");
            options.arg("/K");
            options.arg("appium");
        }
        options.arg("--port=" + options.port);
        return new AndroidDriver(options);
    }

    @Override
    public void activate() {
        super.setContext("NATIVE_APP");
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ceuthospora ferulina Petr.

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../docs.css" rel="stylesheet">
    <link href="original.css" rel="stylesheet">

Original (control)

    <button type="button" class="btn">Button</button>
    <button type="button" class="btn btn-primary">Primary button</button>
    <button type="button" class="btn btn-danger">Danger button</button>

Back home


text:
package edu.mayo.qia.qin.sergeant;

import java.util.concurrent.ExecutionException;

import org.zeroturnaround.exec.StartedProcess;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class ProcessJobInfo extends JobInfo {
  @JsonIgnore
  public StartedProcess startedProcess;

  @Override
  public String getStatus() {
    if (startedProcess.future().isDone()) {
      return "done";
    }
    if (startedProcess.future().isCancelled()) {
      return "canceled";
    }
    return "running";
  }

  public int getExitValue() throws InterruptedException, ExecutionException {
    if (startedProcess.future().isDone()) {
      return startedProcess.future().get().exitValue();
    }
    return -1;
  }

  @Override
  public String getOutput() throws Exception {
    if (startedProcess.future().isDone()) {
      return startedProcess.future().get().outputUTF8();
    } else {
      return "";
    }
  }

  @Override
  public void shutdown() throws Exception {
    super.shutdown();
    if (!getStatus().equals("done")) {
      startedProcess.process().destroy();
    }
  }
}


text:
require 'enumerator'
require 'base64'

module ListSorting
  #
  # ListSorting.encoded
  #
  # if set to true, encodes the sorting parameter
  #
  mattr_accessor :encoded
  self.encoded = false

  #
  # ListSorting.encoding_proc
  #
  # what is used for encoding the sorting parameter if
  # ListSorting.encoded is set to true
  #
  mattr_accessor :encoding_proc
  self.encoding_proc = Proc.new { |s|
    s += ' ' until (s.size % 3).zero? # avoid '='s at the end
    Base64.encode64(s).chomp
  }

  #
  # ListSorting.decoding_proc
  #
  # what decodes the sorting parameter (reverse of ListSorting.encoding_proc)
  #
  mattr_accessor :decoding_proc
  self.decoding_proc = Proc.new { |s| Base64.decode64(s).strip }

  #
  # ListSorting.sort_parameter
  #
  # the 'sort' part in '/users?sort=login'
  #
  mattr_accessor :sort_parameter
  self.sort_parameter = :sort

  module Controller
    #
    # Paginate the model
    #
    # The model can be supplied as the name of the class or the class itself.
    # Note that the model has to have a 'paginate' method. (will_paginate usually)
    #
    # == Params
    #  model   = model name or model class
    #  options = paginate/find options
    #
    # == Examples
    #  paginate :users
    #  paginate @group.users
    #
    def paginate(model, options = {})
      if String === model or Symbol === model # user gave the model name
        model = model.to_s.classify.constantize
      end

      options = options.reverse_merge(:page => params[:page] || 1)

      sort = ListSorting.extract_sort_field_from params
      options[:order] = sort if sort

      model.paginate options
    end
  end

  module Helper
    #
    # Create a link that sorts the current list
    #
    # It also adds 'current-sort' and 'asc' or 'desc' class names to the
    # link if the link is for the current sorting order.
    #
    # == Params
    #  label   = label of the link
    #  field   = column/field name of the sort
    #  options = options + html options of the link combined
    #
    # == Options
    #  :default
    #    Identify this link as the default sorting order; therefore if the list is not
    #    custom sorted, then the link generated will be for the reverse order.
    #
    # == Examples
    #  sort_link('Country', 'country')
    #    # Country
    #    if currently selected:
    #    # Country
    #
    #  sort_link('Username', 'username', :default => true)
    #    if no sorting in params, the link will be for the reverse order
    #    # Username
    #
    #  sort_link('Last Updated', 'updated_at DESC')
    #    # Last Updated
    #    if currently selected:
    #    # Last Updated
    #
    #  sort_link('Name', 'last_name, first_name')
    #    # Name
    #
    def sort_link(label, field, options = {})
      default = options.delete(:default)
      sort = ListSorting.extract_sort_field_from params
      base = Proc.new { |f| f.sub(/\s*(ASC|DESC)$/,'') }
      current =
        if sort.blank?
          false
        elsif field =~ /,/
          fields, sorting = field.split(/\s*,\s*/), sort.split(/\s*,\s*/)
          fields.size == sorting.size and fields.enum_for(:each_with_index).all? { |f, i| sorting[i] =~ /^#{base.call(f)}(\s(ASC|DESC))?$/i }
        else
          sort =~ /^#{base.call(field)}(\s(ASC|DESC))?$/i
        end

      if current
        field = ActiveRecord::Base.__send__(:reverse_sql_order, sort).gsub(/\sASC$/i, '')
      elsif sort.blank? and default
        field = ActiveRecord::Base.__send__(:reverse_sql_order, field).gsub(/\sASC$/i, '')
      end

      options[:class] = 'current-sort ' + ((field =~ /DESC$/i) ? 'asc' : 'desc') if current
      field = ListSorting.encode(field)
      link_to label, url_for(ListSorting.sort_parameter => field, :params => params), options
    end
  end

  class << self
    alias :encoded? :encoded

    def encode(str)
      encoded? ? encoding_proc.call(str) : str
    end

    def decode(str)
      encoded? ? decoding_proc.call(str) : str
    end

    def extract_sort_field_from(params = {})
      (s = params[sort_parameter]) ? decode(s) : nil
    end
  end
end


text:
module.exports = function() {
  this.Before("@directconnect", function (callback) {
    this.client = new this.AWS.DirectConnect.Client();
    callback();
  });

  this.Given(/^I describe Direct Connect offerings$/, function(callback) {
    this.request(null, 'describeOfferings', {}, callback);
  });

  this.Given(/^I take the first offering ID$/, function(callback) {
    this.AWS.util.arrayEach.call(this, this.data.offerings, function(item) {
      if (item.region === this.client.config.region) {
        this.offering = item;
        return this.AWS.util.abort;
      }
    });
    callback();
  });

  this.When(/^I create a Direct Connect connection with name prefix "([^"]*)" and the offering ID$/, function(prefix, callback) {
    var params = {
      offeringId: this.offering.offeringId,
      connectionName: this.uniqueName(prefix)
    };
    this.request(null, 'createConnection', params, callback);
  });

  this.Then(/^I should get a Direct Connect connection ID$/, function(callback) {
    this.connectionId = this.data.connectionId;
    callback();
  });

  this.Then(/^the region should match the offering region$/, function(callback) {
    this.assert.equal(this.offering.region, this.data.region);
    callback();
  });

  this.Then(/^I describe connection details for the connection$/, function(callback) {
    var params = {connectionId: this.connectionId};
    this.request(null, 'describeConnectionDetail', params, callback);
  });

  this.Then(/^the bandwidth should match the offering bandwidth$/, function(callback) {
    this.assert.equal(this.offering.bandwidth, this.data.bandwidth);
    callback();
  });

  this.Then(/^I delete the Direct Connect connection$/, function(callback) {
    var params = {connectionId: this.connectionId};
    this.request(null, 'deleteConnection', params, callback);
  });

  this.Given(/^I create a Direct Connect connection with an invalid offering ID$/, function(callback) {
    var params = {
      offeringId: 'INVALID_OFFERING_ID',
      connectionName: this.uniqueName('aws-sdk-js')
    };
    this.request(null, 'createConnection', params, callback, false);
  });
};


text:
drop table if exists t;
create table t(col1 int,col2 varchar(20),col3 date);
insert into t values(1,'book1','2007-12-24');
insert into t values(2,'book2','2008-12-24');
insert into t values(3,'book3','2009-12-24');
insert into t values(4,'book4','2010-12-24');
insert into t values(5,'book2','2008-12-24');
insert into t values(6,'book2','2011-12-24');
insert into t values(7,'book5','2008-12-24');
insert into t select * from t;
insert into t select * from t;
insert into t select * from t;
insert into t select * from t;
CREATE INDEX idx1 ON t(year(col3),col1);
CREATE INDEX idx2 ON t(col2,col1);
CREATE INDEX idx3 ON t(year(col3),col2,col1);
delete FROM t WHERE year(col3)=2008 and col2='book2' using index idx1(+) keylimit 0+0+0+0+0+0+0,1-1+1;
delete FROM t WHERE year(col3)=2008 and col2='book2' using index idx2(+) keylimit 2-(2*1),1;
delete FROM t WHERE year(col3)=2008 or col2='book2' using index idx1(+) keylimit 0,3;
delete FROM t WHERE year(col3)=2008 or col2='book2' using index idx2(+) keylimit 1*(2-2),3;
drop table if exists t;