text:
exports.up = function (knex) {
    return knex.schema.createTable('pack_logs', function (table) {
        // table structure
        table.string('id', 36).primary();
        table
            .string('pack_id', 36)
            .nullable()
            .defaultTo(null);
        table
            .string('pack_version_id', 36)
            .nullable()
            .defaultTo(null);
        table
            .string('username', 16)
            .index()
            .notNullable();
        table
            .string('action', 32)
            .index()
            .notNullable();
        table
            .timestamp('created_at')
            .notNullable()
            .defaultTo(knex.fn.now());

        // foreign keys
        table
            .foreign('pack_id')
            .references('id')
            .inTable('packs')
            .onDelete('SET NULL')
            .onUpdate('cascade');
        table
            .foreign('pack_version_id')
            .references('id')
            .inTable('pack_versions')
            .onDelete('SET NULL')
            .onUpdate('cascade');
    });
};

exports.down = function (knex) {
    return knex.schema.dropTable('pack_logs');
};


text:
IMPORTANT: please note that the auto-format feature (AKA format-as-you-type) was removed in v8.0.0 - read more here: https://github.com/jackocnr/intl-tel-input/issues/346. Please do not open any new issues about this topic.

IMPORTANT: we use libphonenumber for formatting and validation - if your issue relates to one of these things, please check their test site first and if you see the problem there please file an issue with them instead: https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html. Please also check the intl-tel-input validation demo page to make sure it's not a problem with your code: https://intl-tel-input.com/node_modules/intl-tel-input/examples/gen/is-valid-number.html.

### Steps to reproduce
1.
2.
3.

### Expected behaviour
Tell us what should happen

### Actual behaviour
Tell us what actually happens

### Initialisation options
List any options you're using e.g. utilsScript or preferredCountries

redpajama_set_name: RedPajamaGithub


text:
import * as assert from 'assert';

describe('DropdownWithRemoteDataWithoutCustomControlsWebPart', () => {
  it('should do something', () => {
    assert.ok(true);
  });
});


text:
import { escapeRegExp } from "../utils";

const materialIconRegex = new RegExp(
	escapeRegExp('')
	+ "([\\w\\s_]+)"
	+ escapeRegExp(" —")
	+ "\\s+",
	"gi",
);
const cupertinoIconRegex = new RegExp(
	escapeRegExp(`<i class='cupertino-icons md-36'>`)
	+ "([\\w\\s_]+)"
	+ escapeRegExp(" —")
	+ "\\s+",
	"gi",
);
const dartDocDirectives = new RegExp(
	`(\\n\\s*{@.*?}$)|(^{@.*?}\\s*\\n)|(^{@.*?}$)`,
	"gim",
);
const dartDocCodeBlockSections = new RegExp(
	`(\`\`\`\\w+) +\\w+`,
	"gi",
);

export function cleanDartdoc(doc: string | undefined, iconPathFormat: string): string {
	if (!doc)
		return "";

	// Clean up some dart.core dartdoc.
	const index = doc.indexOf("## Other resources");
	if (index !== -1)
		doc = doc.substring(0, index);

	// Remove colons from old-style references like [:foo:].
	doc = doc.replace(/\[:\S+:\]/g, (match) => `[${match.substring(2, match.length - 2)}]`);

	// Replace material icon HTML blocks with markdown to load the images from the correct place.
	doc = doc.replace(materialIconRegex, (_fullMatch: string, variant: string, icon: string) => {
		if (variant) {
			variant = fixVariant(variant);
			icon = `${icon}_${variant}`;
		}
		icon = fixIcon(icon);
		const iconPath = iconPathFormat.replace("$1", `material/${icon}`);
		return `![${icon}](${iconPath}|width=32,height=32)\n\n`;
	});

	// Replace cupertino icon HTML blocks with markdown to load the images from the correct place.
	doc = doc.replace(cupertinoIconRegex, (_fullMatch: string, icon: string) => {
		const iconPath = iconPathFormat.replace("$1", `cupertino/${icon}`);
		return `![${icon}](${iconPath}|width=32,height=32)\n\n`;
	});

	// Remove any directives like {@template xxx}
	doc = doc.replace(dartDocDirectives, "");

	// Remove any code block section names like ```dart preamble
	doc = doc.replace(dartDocCodeBlockSections, "$1");

	return doc;
}

/// Strips markdown to make nicer plain text.
export function stripMarkdown(doc: string): string {
	if (!doc)
		return "";

	// Remove links like [foo](bar).
	doc = doc.replace(/\[(.+?)\]\(.+?\)/g, "$1");

	// Remove references like [foo].
	doc = doc.replace(/\[(.+?)\]/g, "$1");

	return doc;
}

function fixVariant(variant: string): string {
	// Class names don't always match the filenames.
	return variant === "round" ? "rounded" : variant;
}

const identifierPrefixRewritePattern = new RegExp(`3d|\\d+`);

const identifierPrefixRewrites: { [key: string]: string | undefined } = {
	// See identifierPrefixRewrites in
	// https://github.com/flutter/flutter/blob/master/dev/tools/update_icons.dart
	"1": "one_",
	"10": "ten_",
	"11": "eleven_",
	"12": "twelve_",
	"123": "onetwothree",
	"13": "thirteen_",
	"14": "fourteen_",
	"15": "fifteen_",
	"16": "sixteen_",
	"17": "seventeen_",
	"18": "eighteen_",
	"19": "nineteen_",
	"2": "two_",
	"20": "twenty_",
	"21": "twenty_one_",
	"22": "twenty_two_",
	"23": "twenty_three_",
	"24": "twenty_four_",
	"2d": "twod",
	"3": "three_",
	"30": "thirty_",
	"360": "threesixty",
	"3d": "threed",
	"4": "four_",
	"5": "five_",
	"6": "six_",
	"60": "sixty_",
	"7": "seven_",
	"8": "eight_",
	"9": "nine_",
};
const identifierExactRewrites: { [key: string]: string | undefined } = {
	// See identifierExactRewrites in
	// https://github.com/flutter/flutter/blob/master/dev/tools/update_icons.dart
	"class": "class_",
	"door_back": "door_back_door",
	"door_front": "door_front_door",
	"new": "new_",
	"switch": "switch_",
	"try": "try_sms_star",
};

function fixIcon(icon: string): string {
	// Things starting with numbers are textual in their names too.
	const prefixMatch = identifierPrefixRewritePattern.exec(icon);
	if (prefixMatch) {
		const prefix = prefixMatch[0]!;
		const newPrefix = identifierPrefixRewrites[prefix];
		if (newPrefix)
			return `${newPrefix}${icon.slice(prefix.length)}`;
	}

	// Also try exact rewrites.
	const newIdentifier = identifierExactRewrites[icon];
	if (newIdentifier)
		return newIdentifier;

	return icon;
}


text:
package org.txazo.designpattern.creational.builder;

/**
 * 指导者
 */
public class Director {

    private Builder builder;

    public Director(Builder builder) {
        this.builder = builder;
    }

    public Product getProduct() {
        builder.buildHead();
        builder.buildBody();
        builder.buildFoot();
        return builder.build();
    }

}


text:
package BrodalOkasakiHeap
import "fmt"

/*
"BOHeap" is a wrapper around "BONode". This structure is defines an entrypoint for a Brodal-Okasaki heap and
implements the priority queue interface using operations defined for "BONode" structure.
 */
type BOHeap struct {
    root	*BONode
    size 	int
}

/*
Create a new Brodal-Okasaki heap.
 */
func NewBOHeap() *BOHeap {
    return &BOHeap {
        root: nil,
        size: 0,
    }
}

/*
Insert a new value to the heap.

This function depends on another "insert" function, but executing this function always performs the insertion procedure
of the skew-binomial heaps, which is simply described as follows:
    1. Get two nodes from the children of root node that has the minimum ranks.
    2. Skew-link those two nodes and the new node.
    3. Insert this newly linked node among the children of root.

Much of the logical complexity is hidden in the "skew-linking" procedure. Read "BONode.skewLink".
 */
func (bq *BOHeap) Insert(value int) {
    newnode := newBONode(value)
    bq.size += 1
    bq.insert(newnode)
}

/*
Delete and return the minimum valued node.

Since we do almost everything under Pop(), this function is a bit complicated. I implemented Pop() as follows:

    1. Get the minimum node among the children of root.
    2. If this node has elements in its subqueue, add them to the original queue.
    3. For every children of the minimum node;
        3a. Insert the child again to the original heap.

All suboperations (1, 2, 3) take O(logn) time. As you can see, Pop() does every operation that takes O(logn) time, hence
the asymptotical optimality.

In the original paper, re-inserting the children of a node involves partitioning the children. I didn't bother understanding
what the authors really meant, and made a slight modification here. Figure out the difference.
 */
func (bq *BOHeap) Pop() int {
    bq.size -= 1
    retval := bq.root.value

    if bq.root.subqueue_head != nil {
        bq.merge_subqueue()
    }

    minchild := bq.root.getMinChild()

    if minchild == nil {
        // minchild == nil signifies the heap is empty.
        bq.root = nil
    } else {
        minchild.rogue()
        bq.reInsertChildren(minchild)
        bq.promoteToRoot(minchild)
    }

    return retval
}

/*
Return the minimum valued element in the queue.
 */
func (bq *BOHeap) Peek() int {
    // Minimum is the global root so we have O(1) access time.
    return bq.root.value
}

/*
Return the total keys present in the queue.
 */
func (bq *BOHeap) Size() int {
    return bq.size
}

/*
Instead of doing the merge operation immediately, we do it when we need it. This is also called "lazy-evaluation".
Implementation of this operation is:
    * Move the children head to the subqueue head.
    * Insert the root of other queue as if it is a singleton node.
 */
func (bq* BOHeap) Merge(other *BOHeap) {
    bq.size += other.size

    oroot := other.root
    oroot.moveChildrenToSubqueue()

    bq.insert(oroot)
}

// ====== Helper functions =======

/*
This method performs the actual insertion operation. It is a bit complicated because it has to deal with 4 cases:
    * Insertion when the queue is empty
    * Insertion when the new node's value is smaller than the root.
    * Insertion of nodes with rank 0
        * We perform the insertion procedure of skew binomial heaps.
    * Insertion of nodes with rank >0
        * We perform the insertion procedure of ordinary binomial heaps.
 */
func (bq* BOHeap) insert(newnode *BONode) {
    if bq.root == nil {
        // When the queue is empty.
        bq.root = newnode
    } else if newnode.value < bq.root.value {  // If you put "<=" instead of "<", an infinite loop occurs. Find why.
        oldroot := bq.swapWithRoot(newnode)
        bq.insert(oldroot)
    } else {
        if newnode.rank > 0 {
            bq.insert_binomial(newnode)
        } else {
            bq.insert_skew(newnode)
        }
    }
}

/*
Merge the subqueue. Essentially, re-insert the immediate children, but for the subqueue.
 */
func (bq* BOHeap) merge_subqueue() {
    for _, node := range bq.root.subqueueIterator() {
        node.rogue_subqueue()
        bq.insert(node)
    }
}

/*
Re-insert the children. Simple.
 */
func (bq* BOHeap) reInsertChildren(bon *BONode) {
    // Reinsert the children of the GIVEN node.
    for _, node := range bon.childrenIterator() {
        node.rogue()
        bq.insert(node)
    }
}

/*
This function performs skew-binomial insertion, which is;
    * Get the minimum ranked 2 children.
    * Compare the ranks of those 2 children
        * If they have the same rank, skew-link them, and simply insert the resulting node.
        * If they have different ranks, simply insert the newnode.
    It is important to note that "newnode" has a rank of 0. This method should not run for nodes that has rank <>0
 */
func (bq* BOHeap) insert_skew(newnode *BONode) {
    node1, node2 := bq.root.getSmallestRankChildren()
    mergednode := skewLink(node1, node2, newnode)
    bq.root.adopt(mergednode)
}

/*
This is the insertion procedure for ordinary binomial heaps, which is;
    * Get a child that has the same rank for the other node.
        * If such node exists, among those two who has smaller value adopts the other one. Insert the newly made node
          into the queue.
        * If not, simply insert the other node.

This operation can possibly take O(logn) time under normal implementation.
Consider the case, inserting a node of rank 3 to the binomial heap that has the following state (numbers imply ranks):

    * (4 3) <-- 3

This will cause another insertion operation

    * (4) <-- 4

In the worst case, this operation cascades up to "logn" time, but this fact doesn't harm the asymptotical optimality,
since it can only be executed under Pop().
 */
func (bq* BOHeap) insert_binomial(other *BONode) {
    // "other" is assumed to be rogue.

    srnode := bq.root.getSameRankChild(other.rank)

    if srnode == nil {
        bq.root.adopt(other)
    } else {
        newnode := simpleLink(srnode, other)
        // There is a recursion here. If the aforementioned cascading to be occur, it shall be done so by recursing
        // the next line of code. Figure it out yourself.
        bq.insert(newnode)
    }
}

/*
Swap the other node with the existing root.
 */
func (bq* BOHeap) swapWithRoot(newroot *BONode) *BONode {
    // "newroot" is assumed to be rogue and childless.
    oldroot := bq.root

    // Since the children has a reference to their parents, we need to iterate through all of them anyway.
    // Simply transferring "children_head" won't work.
    for _, node := range oldroot.childrenIterator() {
        node.rogue()
        newroot.adopt(node)
    }

    oldroot.rank = 0

    bq.root = newroot
    return oldroot
}

/*
Promote the selected node to be the new root.
 */
func (bq* BOHeap) promoteToRoot(minnode *BONode) {
    // There is a bug. What is it?
    bq.root.value = minnode.value
    bq.root.subqueue_head = minnode.subqueue_head
}

func (bq* BOHeap) print() {
    if bq.root == nil {
        fmt.Println("heap is empty.")
    } else {
        bq.root.print_recursive(0)
    }
}


text:
<link rel="stylesheet" href="vendor/bootstrap-css/css/bootstrap.min.css" />
<link rel="stylesheet" href="vendor/angular-chart.js/dist/angular-chart.css" />

<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/../../../xos/core/static/xosNgLib.css">


text:
#ifndef THIRD_PARTY_PY_KERAS_CV_OPS_BOX_UTIL_H_
#define THIRD_PARTY_PY_KERAS_CV_OPS_BOX_UTIL_H_

#include <string>
#include <vector>

#include "tensorflow/core/framework/tensor.h"

namespace tensorflow {
namespace kerascv {
namespace box {

// A vertex with (x, y) coordinate.
//
// This is an internal implementation detail of RotatedBox2D.
struct Vertex {
  // Creates an empty Vertex.
  Vertex() = default;

  Vertex(const double x, const double y) : x(x), y(y) {}

  double x = 0;
  double y = 0;
};

// A rotated 2D bounding box represented as (cx, cy, w, h, r). cx, cy are the
// box center coordinates; w, h are the box width and height; heading is the
// rotation angle in radian relative to the 'positive x' direction.
class RotatedBox2D {
 public:
  // Creates an empty rotated 2D box.
  RotatedBox2D() : RotatedBox2D(0, 0, 0, 0, 0) {}

  RotatedBox2D(const double cx, const double cy, const double w, const double h,
               const double heading);

  // Returns the area of the box.
  double Area() const;

  // Returns the intersection area between this box and the given box.
  double Intersection(const RotatedBox2D& other) const;

  // Returns the IoU between this box and the given box.
  double IoU(const RotatedBox2D& other) const;

  // Returns true if the box is valid (width and height are not extremely
  // large or small).
  bool NonZeroAndValid() const;

 private:
  // Computes / caches box_vertices_ calculation.
  const std::vector<Vertex>& box_vertices() const;

  // Returns true if this box and 'other' might intersect.
  //
  // If this returns false, the two boxes definitely do not intersect.  If this
  // returns true, it is still possible that the two boxes do not intersect, and
  // the more expensive intersection code will be called.
  bool MaybeIntersects(const RotatedBox2D& other) const;

  double cx_ = 0;
  double cy_ = 0;
  double w_ = 0;
  double h_ = 0;
  double heading_ = 0;

  // Loose boundaries for fast intersection test.
  double loose_min_x_ = -1;
  double loose_max_x_ = -1;
  double loose_min_y_ = -1;
  double loose_max_y_ = -1;

  // True if the dimensions of the box are very small or very large in any
  // dimension.
  bool extreme_box_dim_ = false;

  // The following fields are computed on demand.  They are logically
  // const.

  // Cached area.  Access via Area() public API.
  mutable double area_ = -1;

  // Stores the vertices of the box.  Access via box_vertices().
  mutable std::vector<Vertex> box_vertices_;
};

// A 3D box of 7-DOFs: only allows rotation around the z-axis.
struct Upright3DBox {
  RotatedBox2D rbox = RotatedBox2D();
  double z_min = 0;
  double z_max = 0;

  // Creates an empty rotated 3D box.
  Upright3DBox() = default;

  // Creates a 3D box from the raw input data with size 7. The data format is
  // (center_x, center_y, center_z, dimension_x, dimension_y, dimension_z,
  // heading)
  Upright3DBox(const std::vector<double>& raw)
      : rbox(raw[0], raw[1], raw[3], raw[4], raw[6]),
        z_min(raw[2] - raw[5] / 2.0),
        z_max(raw[2] + raw[5] / 2.0) {}

  Upright3DBox(const RotatedBox2D& rb, const double z_min, const double z_max)
      : rbox(rb), z_min(z_min), z_max(z_max) {}

  // Computes intersection over union (of the volume).
  double IoU(const Upright3DBox& other) const;

  // Computes overlap: intersection of this box and the given box normalized
  // over the volume of this box.
  double Overlap(const Upright3DBox& other) const;

  // Returns true if the box is valid (width and height are not extremely
  // large or small, and zmin < zmax).
  bool NonZeroAndValid() const;
};

// Converts a [N, 7] tensor to a vector of N Upright3DBox objects.
std::vector<Upright3DBox> ParseBoxesFromTensor(const Tensor& boxes_tensor);

}  // namespace box
}  // namespace kerascv
}  // namespace tensorflow

#endif  // THIRD_PARTY_PY_KERAS_CV_OPS_BOX_UTIL_H_


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 2: 791 (1883)

#### Original name
Xyloma hysterioides Pers., 1798

### Remarks
null


text:
<?php

namespace PagueVeloz\Api\v1;

use PagueVeloz\Api\InterfaceAPI;
use PagueVeloz\Common\PagueVeloz;
use PagueVeloz\Request\HttpContext;

class Ping extends PagueVeloz implements InterfaceAPI
{

	public function __construct()
 	{
 		$this->_requestURI = '/v1/ping';
 		parent::__construct();
 	}

 	public function Get()
 	{
 		$context = new HttpContext;

 		$context->setHeaders($this->_header);
 		$context->setAuthorization($this->auth);
 		$context->setMethod('GET');
 		$context->setHost($this->_host);
 		$context->setRequestURI($this->_requestURI);

 		return $this->_machine->Send($context);
 	}
}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class ConsultorioConfig(AppConfig):
    name = 'consultorio'


text:
* [List of projects hosted in Scenic](#list-of-projects-hosted-in-scenic)
* [Scenic projects](#scenic-projects)

## List of projects hosted in Scenic

*   [AdaTape](adatape)

    > AdaTape is an adaptive computation transformer with elastic input sequence.

*   [AdversarialTraining](adversarialtraining)

    > Adversarial training is an implementation of modern forms of adversarial
    > training that achieved state-of-the-art robustness results on image
    > classifications. This includes [AdvProp](https://arxiv.org/abs/1911.09665)
    > and (Pyramid Adversarial Training Improves ViT Performance)[https://arxiv.org/abs/2111.15121].

*   [ViViT](vivit)

    > ViViT is a family of pure-transformer based models for video
    > classification that achieved state-of-the-art results.
    > Details can be found in the [paper](https://arxiv.org/abs/2103.15691).

*   [Tasseo](tasseo)

    > Tasseo is a project that uses transformer based models for aberration
    > detection from chromosome karyotype images.

*   [TokenLearner](token_learner)

    > TokenLearner proposes dynamic tokenization of images and videos for faster
    > and more accurate video/image processing tasks. More can be found in
    > the [paper](https://arxiv.org/abs/2106.11297).

*   [FastViT](fast_vit)

    > FastViT is a project that aims at exploring ideas around making ViT faster
    > via using [efficient transformers](https://arxiv.org/abs/2009.06732), in
    > particular on higher resolution inputs (more tokens and thus longer
    > sequences).

*   [Omninet](omninet)

    > Omninet is a transformer model with
    > [omni-directional representations](https://arxiv.org/abs/2103.01075).

*   [CLAY](layout_denoise)

    > CLAY is a Transformer-based pipeline for mobile UI layout denoising. Read
    > more about this project in CLAY [paper](https://arxiv.org/abs/2201.04100).

*   [MBT](mbt)

    > MBT presents a transformer based architecture that uses "fusion
    > bottlenecks" for modality fusion at multiple layers.
    > Details can be found in the [paper](https://arxiv.org/abs/2201.04100).

*   [MTV](mtv)

    > MTV presents a state-of-the-art transformer based architecture for video
    > classification. MTV consists of separate encoders to represent different
    > views of the input video with lateral connections and a global encoder to
    > fuse information across views. More details are in the
    > [paper](https://arxiv.org/abs/2201.04288).

*   [OWL-ViT](owl_vit)

    > OWL-ViT is an open-vocabulary object detector that given an image and a
    > free-text query, it finds objects matching that query in the image. It can
    > also do one-shot object detection, i.e. detect objects based on a single
    > example image. More details are in the
    > [paper](https://arxiv.org/abs/2205.06230).

*   [NCR](ncr)

    > NCR is a regularization method which encourages the network to make
    > similar predictions for similar vectors in the feature space.
    > Details can be found in the [paper](https://arxiv.org/abs/2202.02200),
    > where we used this method to learn with noisy labels.

*   [PCT](pointcloud)

    > Point Cloud Transformer (PCT) is a Transformer-based model for
    > performing inference (classification/segmentation) for point cloud data.
    > Details can be found in the [paper](https://arxiv.org/abs/2012.09688).

## Scenic projects
A typical project consists of models, trainers, configs, a runner, and some
utility functions developed for the project.

### Models
Models are entities that define the network architecture, loss function, and
metrics. Network architectures are built using Flax `nn.Modules`. Common loss
functions and metrics can be included via a
[Base Model](../model_lib/README.md#base_model), or within the project
itself for more specific use-cases.

To be accessible by the trainer, a model newly-defined by a project needs to be
registered *within a specific project*. As an exception, the baseline models
are registered directly in `model_lib.models`.

### Trainers
Trainers implement the training and evaluation loops of the model. There are
already standard trainers that are provided in Scenic for classification,
segmentation, and adaptation (located in the `train_lib` module).
These trainers are directly registered  in `train_lib_deprecated/trainers` and
given the careful optimization of these trainers for fast and efficient training
on accelerators (in particular TPUs), they can be forked by projects for further
customization. Projects need to register the new trainers they define within
their project, or they can simply use the standard Scenic trainers when no
modification is needed.

### Configs
Config files are used to configure experiments. They define (hyper-)parameters
for the selected model, trainer, and dataset (e.g. number of layers, frequency
of logging, etc).

### Binaries
Binaries bind models, trainers, and datasets together based on the config and
start the training. Usually, this is a `main.py` within the project that also
contains the registry for the project specific models and trainers. Note that
baselines make use of Scenic's default binary `main.py`.

### Registries
There are three types of objects that can be registered in Scenic:
`model`, `trainer`, and `dataset`. A registry could be any simple data structure
that maps a string name to an object, for instance, a python dictionary.

Scenic defines a dataset registry that uses ad-hoc importing to lazy-load
the code for the input pipeline of a requested dataset. This registry lives in
`dataset_lib/datasets.py`. There are common trainers and models that are
registered in  `train_lib_deprecated/trainers.py` and `model_lib/models.py`. However,
a project can define its own dataset, model, and trainer and make a small
registry for these objects within the project, e.g. in the project's `main.py`
so that the right model, trainer, and dataset are selectable using the
configs specified in the config file.


text:
#ifndef __ASM_SH_SIGCONTEXT_H
#define __ASM_SH_SIGCONTEXT_H

struct sigcontext {
	unsigned long	oldmask;

#if defined(__SH5__) || defined(CONFIG_CPU_SH5)
	/* CPU registers */
	unsigned long long sc_regs[63];
	unsigned long long sc_tregs[8];
	unsigned long long sc_pc;
	unsigned long long sc_sr;

	/* FPU registers */
	unsigned long long sc_fpregs[32];
	unsigned int sc_fpscr;
	unsigned int sc_fpvalid;
#else
	/* CPU registers */
	unsigned long sc_regs[16];
	unsigned long sc_pc;
	unsigned long sc_pr;
	unsigned long sc_sr;
	unsigned long sc_gbr;
	unsigned long sc_mach;
	unsigned long sc_macl;

#if defined(__SH4__) || defined(CONFIG_CPU_SH4) || \
    defined(__SH2A__) || defined(CONFIG_CPU_SH2A)
	/* FPU registers */
	unsigned long sc_fpregs[16];
	unsigned long sc_xfpregs[16];
	unsigned int sc_fpscr;
	unsigned int sc_fpul;
	unsigned int sc_ownedfp;
#endif
#endif
};

#endif /* __ASM_SH_SIGCONTEXT_H */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Atomiv.Template.Lite.Entities;
using Atomiv.Template.Lite.Services.Interfaces;
using Atomiv.Template.Lite.Dtos.Products;

namespace Atomiv.Template.Lite.Controllers
{
    [Route("api/products")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProductService _service;

        public ProductsController(IProductService service)
        {
            _service = service;
        }

        // GET: api/Products
        [HttpGet]
        public async Task<ActionResult<GetProductQueryResponse>> GetProducts()
        {
            var products = await _service.GetProducts();
            return Ok(products);
        }

        // GET: api/Products/5
        [HttpGet("{id}")]
        public async Task<ActionResult<GetProductQueryResponse>> GetProduct(int id)
        {
            var product = await _service.GetProduct(id);

            if (product == null)
            {
                return NotFound();
            }

            return Ok(product);
        }

        // PUT: api/Products/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutProduct(int id, UpdateProductCommand request)
        {
            if (id != request.Id)
            {
                return BadRequest();
            }

            var response = await _service.UpdateProduct(request);

            if (response == null)
			{
                return NotFound();
			}

            return NoContent();

        }

        // POST: api/Products
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<Product>> PostProduct(CreateProductCommand request)
        {
            var response = await _service.CreateProduct(request);

            return CreatedAtAction(nameof(GetProduct), new { id = response.Id }, response);
        }

        // DELETE: api/Products/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<DeleteProductCommandResponse>> DeleteProduct(int id)
        {
            var product = await _service.DeleteProduct(id);
            if (product == null)
            {
                return NotFound();
            }

            return Ok(product);
        }

    }
}


text:
using System;
using System.Linq;

class MMSAOfNNumbers
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        double[] nums = new double[n];
        for (int i = 0; i < nums.Length; i++)
        {
            nums[i] = double.Parse(Console.ReadLine());
        }
        Console.WriteLine("min={0:f2}", nums.Min());
        Console.WriteLine("max={0:f2}", nums.Max());
        Console.WriteLine("sum={0:f2}", nums.Sum());
        Console.WriteLine("avg={0:f2}", nums.Average());
    }
}


text:
import { ExtensionContext, window } from "vscode";

import { PreviewProcessor } from "./previewProcessor";
import { ProxyResponse } from "../Proxy/proxyResponse";
import { TokenTreeContentProvider } from "../ContentProvider/tokenTreeContentProvider";

export class TokenTreeProcessor extends PreviewProcessor {
    provider: TokenTreeContentProvider;

    constructor(context: ExtensionContext) {
        super(context);
        this.provider = new TokenTreeContentProvider(context);
    }

    protected pageRefresh(response: ProxyResponse){
        this.provider.update(response.documentUri, response.markupResult);
    }
}


text:
package scouter.agent.asm;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import scouter.agent.ClassDesc;
import scouter.agent.Configure;
import scouter.agent.Logger;
import scouter.agent.asm.util.AsmUtil;
import scouter.agent.asm.util.MethodSet;
import scouter.agent.trace.TraceApiCall;
import scouter.org.objectweb.asm.ClassVisitor;
import scouter.org.objectweb.asm.Label;
import scouter.org.objectweb.asm.MethodVisitor;
import scouter.org.objectweb.asm.Opcodes;
import scouter.org.objectweb.asm.Type;
import scouter.org.objectweb.asm.commons.LocalVariablesSorter;

public class Apicall2ASM implements IASM, Opcodes {
	// private Map<String, MethodSet> target =
	// MethodSet.getHookingSet("hook.subcall");
	private List<MethodSet> target = MethodSet.getHookingMethodSet(Configure.getInstance().hook_apicall);
	private Map<String, MethodSet> reserved = new HashMap<String, MethodSet>();

	public Apicall2ASM() {
		AsmUtil.add(reserved, "sun/net/www/protocol/http/HttpURLConnection", "getInputStream()Ljava/io/InputStream;");
		AsmUtil.add(reserved, "sun/net/www/protocol/http/HttpURLConnection", "connect()V");
		AsmUtil.add(reserved, "org/apache/commons/httpclient/HttpClient", "executeMethod("
				+ "Lorg/apache/commons/httpclient/HostConfiguration;" + "Lorg/apache/commons/httpclient/HttpMethod;"
				+ "Lorg/apache/commons/httpclient/HttpState;" + ")I");
		AsmUtil.add(reserved, "org/apache/http/impl/client/InternalHttpClient", "doExecute");
		AsmUtil.add(reserved, "sun/net/www/http/HttpClient", "parseHTTP");
		AsmUtil.add(reserved, "org/apache/http/impl/client/AbstractHttpClient",//
				"execute(Lorg/apache/http/HttpHost;" + "Lorg/apache/http/HttpRequest;"
						+ "Lorg/apache/http/protocol/HttpContext;)Lorg/apache/http/HttpResponse;");

		// JCO CLIENT 추가..
		AsmUtil.add(reserved, "com/sap/mw/jco/JCO$Client", "execute(Ljava/lang/String;" + //
				"Lcom/sap/mw/jco/JCO$ParameterList;" + //
				"Lcom/sap/mw/jco/JCO$ParameterList;" + //
				"Lcom/sap/mw/jco/JCO$ParameterList;" + //
				"Lcom/sap/mw/jco/JCO$ParameterList;" + //
				"Ljava/lang/String;Ljava/lang/String;I)V");

	}

	public boolean isTarget(String className) {
		MethodSet mset = reserved.get(className);
		if (mset != null)
			return true;

		for (int i = 0; i < target.size(); i++) {
			mset = target.get(i);
			if (mset.classMatch.include(className)) {
				return true;
			}
		}
		return false;
	}

	public ClassVisitor transform(ClassVisitor cv, String className, ClassDesc classDesc) {

		MethodSet mset = reserved.get(className);
		if (mset != null)
			return new ApicallExtCV(cv, mset, className);

		for (int i = 0; i < target.size(); i++) {
			mset = target.get(i);
			if (mset.classMatch.include(className)) {
				return new ApicallExtCV(cv, mset, className);
			}
		}
		return cv;
	}

}

class ApicallExtCV extends ClassVisitor implements Opcodes {

	public String className;
	private MethodSet mset;

	public ApicallExtCV(ClassVisitor cv, MethodSet mset, String className) {
		super(ASM4, cv);
		this.mset = mset;
		this.className = className;

	}

	@Override
	public MethodVisitor visitMethod(int access, String methodName, String desc, String signature, String[] exceptions) {
		MethodVisitor mv = super.visitMethod(access, methodName, desc, signature, exceptions);

		if (mv == null || mset.isA(methodName, desc) == false) {
			return mv;
		}
		if (AsmUtil.isSpecial(methodName)) {
			return mv;
		}
		Logger.info("apicall: " + className + "." + methodName + desc);

		return new ApicallExtMV(access, desc, mv, Type.getArgumentTypes(desc), (access & ACC_STATIC) != 0, className,
				methodName, desc);
	}
}

// ///////////////////////////////////////////////////////////////////////////
class ApicallExtMV extends LocalVariablesSorter implements Opcodes {
	private static final String TRACESUBCALL = TraceApiCall.class.getName().replace('.', '/');
	private final static String START_METHOD = "startApicall";
	private static final String START_SIGNATURE = "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;";
	private final static String END_METHOD = "endApicall";
	private static final String END_SIGNATURE = "(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Throwable;)V";

	private Label startFinally = new Label();

	public ApicallExtMV(int access, String desc, MethodVisitor mv, Type[] paramTypes, boolean isStatic,
			String classname, String methodname, String methoddesc) {
		super(ASM4, access, desc, mv);
		this.paramTypes = paramTypes;
		this.returnType = Type.getReturnType(desc);
		this.isStatic = isStatic;
		this.className = classname;
		this.methodName = methodname;
		this.methodDesc = methoddesc;
	}

	private Type[] paramTypes;
	private Type returnType;
	private boolean isStatic;
	private String className;
	private String methodName;
	private String methodDesc;
	private int statIdx;

	public void visitCode() {

		int sidx = isStatic ? 0 : 1;

		int arrVarIdx = newLocal(Type.getType("[Ljava/lang/Object;"));
		AsmUtil.PUSH(mv, paramTypes.length);
		mv.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object");
		mv.visitVarInsn(Opcodes.ASTORE, arrVarIdx);

		for (int i = 0; i < paramTypes.length; i++) {
			Type tp = paramTypes[i];
			mv.visitVarInsn(Opcodes.ALOAD, arrVarIdx);
			AsmUtil.PUSH(mv, i);

			switch (tp.getSort()) {
			case Type.BOOLEAN:
				mv.visitVarInsn(Opcodes.ILOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;",
						false);
				break;
			case Type.BYTE:
				mv.visitVarInsn(Opcodes.ILOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false);
				break;
			case Type.CHAR:
				mv.visitVarInsn(Opcodes.ILOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;",
						false);
				break;
			case Type.SHORT:
				mv.visitVarInsn(Opcodes.ILOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false);
				break;
			case Type.INT:
				mv.visitVarInsn(Opcodes.ILOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;",
						false);
				break;
			case Type.LONG:
				mv.visitVarInsn(Opcodes.LLOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
				break;
			case Type.FLOAT:
				mv.visitVarInsn(Opcodes.FLOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
				break;
			case Type.DOUBLE:
				mv.visitVarInsn(Opcodes.DLOAD, sidx);
				mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
				break;
			default:
				mv.visitVarInsn(Opcodes.ALOAD, sidx);
			}
			mv.visitInsn(Opcodes.AASTORE);
			sidx += tp.getSize();
		}
		AsmUtil.PUSH(mv, className);
		AsmUtil.PUSH(mv, methodName);
		AsmUtil.PUSH(mv, methodDesc);
		if (isStatic) {
			AsmUtil.PUSHNULL(mv);
		} else {
			mv.visitVarInsn(Opcodes.ALOAD, 0);
		}
		mv.visitVarInsn(Opcodes.ALOAD, arrVarIdx);

		mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACESUBCALL, START_METHOD, START_SIGNATURE, false);

		statIdx = newLocal(Type.getType(Object.class));
		mv.visitVarInsn(Opcodes.ASTORE, statIdx);
		mv.visitLabel(startFinally);
		mv.visitCode();
	}

	@Override
	public void visitInsn(int opcode) {
		if ((opcode >= IRETURN && opcode <= RETURN)) {
			capReturn();
		}
		mv.visitInsn(opcode);
	}

	private void capReturn() {
		Type tp = returnType;

		if (tp == null || tp.equals(Type.VOID_TYPE)) {

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);
			mv.visitInsn(Opcodes.ACONST_NULL);
			mv.visitInsn(Opcodes.ACONST_NULL);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACESUBCALL, END_METHOD, END_SIGNATURE, false);
			return;
		}
		int i = newLocal(tp);
		switch (tp.getSort()) {
		case Type.BOOLEAN:
			mv.visitVarInsn(Opcodes.ISTORE, i);
			mv.visitVarInsn(Opcodes.ILOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ILOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Boolean", "valueOf", "(Z)Ljava/lang/Boolean;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.BYTE:
			mv.visitVarInsn(Opcodes.ISTORE, i);
			mv.visitVarInsn(Opcodes.ILOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ILOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Byte", "valueOf", "(B)Ljava/lang/Byte;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.CHAR:
			mv.visitVarInsn(Opcodes.ISTORE, i);
			mv.visitVarInsn(Opcodes.ILOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ILOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Character", "valueOf", "(C)Ljava/lang/Character;",
					false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.SHORT:
			mv.visitVarInsn(Opcodes.ISTORE, i);
			mv.visitVarInsn(Opcodes.ILOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ILOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Short", "valueOf", "(S)Ljava/lang/Short;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.INT:
			mv.visitVarInsn(Opcodes.ISTORE, i);
			mv.visitVarInsn(Opcodes.ILOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ILOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Integer", "valueOf", "(I)Ljava/lang/Integer;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.LONG:
			mv.visitVarInsn(Opcodes.LSTORE, i);
			mv.visitVarInsn(Opcodes.LLOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.LLOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Long", "valueOf", "(J)Ljava/lang/Long;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.FLOAT:
			mv.visitVarInsn(Opcodes.FSTORE, i);
			mv.visitVarInsn(Opcodes.FLOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.FLOAD, i);

			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Float", "valueOf", "(F)Ljava/lang/Float;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		case Type.DOUBLE:
			mv.visitVarInsn(Opcodes.DSTORE, i);
			mv.visitVarInsn(Opcodes.DLOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.DLOAD, i);
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/lang/Double", "valueOf", "(D)Ljava/lang/Double;", false);
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
			break;
		default:
			mv.visitVarInsn(Opcodes.ASTORE, i);
			mv.visitVarInsn(Opcodes.ALOAD, i);

			mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
			mv.visitVarInsn(Opcodes.ALOAD, i);// return
			mv.visitInsn(Opcodes.ACONST_NULL);// throwable
		}

		mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACESUBCALL, END_METHOD, END_SIGNATURE, false);
	}

	@Override
	public void visitMaxs(int maxStack, int maxLocals) {
		Label endFinally = new Label();
		mv.visitTryCatchBlock(startFinally, endFinally, endFinally, null);
		mv.visitLabel(endFinally);
		mv.visitInsn(DUP);
		int errIdx = newLocal(Type.getType(Throwable.class));
		mv.visitVarInsn(Opcodes.ASTORE, errIdx);

		mv.visitVarInsn(Opcodes.ALOAD, statIdx);// stat
		mv.visitInsn(Opcodes.ACONST_NULL);// return
		mv.visitVarInsn(Opcodes.ALOAD, errIdx);// throwable
		mv.visitMethodInsn(Opcodes.INVOKESTATIC, TRACESUBCALL, END_METHOD, END_SIGNATURE, false);
		mv.visitInsn(ATHROW);
		mv.visitMaxs(maxStack + 8, maxLocals + 2);
	}
}


text:
extern "C" {
#endif

#include "include/capi/cef_base_capi.h"

///
// Structure used to represent a web response. The functions of this structure
// may be called on any thread.
///
typedef struct _cef_response_t {
  ///
  // Base structure.
  ///
  cef_base_t base;

  ///
  // Get the response status code.
  ///
  int (CEF_CALLBACK *get_status)(struct _cef_response_t* self);

  ///
  // Set the response status code.
  ///
  void (CEF_CALLBACK *set_status)(struct _cef_response_t* self, int status);

  ///
  // Get the response status text.
  ///
  // The resulting string must be freed by calling cef_string_userfree_free().
  cef_string_userfree_t (CEF_CALLBACK *get_status_text)(
      struct _cef_response_t* self);

  ///
  // Set the response status text.
  ///
  void (CEF_CALLBACK *set_status_text)(struct _cef_response_t* self,
      const cef_string_t* statusText);

  ///
  // Get the response mime type.
  ///
  // The resulting string must be freed by calling cef_string_userfree_free().
  cef_string_userfree_t (CEF_CALLBACK *get_mime_type)(
      struct _cef_response_t* self);

  ///
  // Set the response mime type.
  ///
  void (CEF_CALLBACK *set_mime_type)(struct _cef_response_t* self,
      const cef_string_t* mimeType);

  ///
  // Get the value for the specified response header field.
  ///
  // The resulting string must be freed by calling cef_string_userfree_free().
  cef_string_userfree_t (CEF_CALLBACK *get_header)(struct _cef_response_t* self,
      const cef_string_t* name);

  ///
  // Get all response header fields.
  ///
  void (CEF_CALLBACK *get_header_map)(struct _cef_response_t* self,
      cef_string_multimap_t headerMap);

  ///
  // Set all response header fields.
  ///
  void (CEF_CALLBACK *set_header_map)(struct _cef_response_t* self,
      cef_string_multimap_t headerMap);
} cef_response_t;

#ifdef __cplusplus
}
#endif

#endif  // CEF_INCLUDE_CAPI_CEF_RESPONSE_CAPI_H_


text:
package com.cloud.cluster;

import static org.junit.Assert.assertTrue;

import com.cloud.utils.component.ComponentLifecycle;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class ClusterServiceServletAdapterTest {

    ClusterServiceServletAdapter clusterServiceServletAdapter;
    ClusterManagerImpl clusterManagerImpl;

    @Before
    public void setup() throws IllegalArgumentException,
            IllegalAccessException, NoSuchFieldException, SecurityException {
        clusterServiceServletAdapter = new ClusterServiceServletAdapter();
        clusterManagerImpl = new ClusterManagerImpl();
    }

    @Test
    public void testRunLevel() {
        final int runLevel = clusterServiceServletAdapter.getRunLevel();
        assertTrue(runLevel == ComponentLifecycle.RUN_LEVEL_FRAMEWORK);
        assertTrue(runLevel == clusterManagerImpl.getRunLevel());
    }
}


text:
package org.apache.drill.exec.rpc.control;

import io.netty.buffer.ByteBuf;
import org.apache.drill.exec.proto.BitControl;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import org.apache.drill.exec.proto.ExecProtos;
import org.apache.drill.exec.proto.GeneralRPCProtos;
import org.apache.drill.exec.proto.UserBitShared;
import org.apache.drill.exec.rpc.Acks;
import org.apache.drill.exec.rpc.RpcException;
import org.apache.drill.exec.rpc.RpcOutcomeListener;
import org.apache.drill.exec.work.batch.ControlMessageHandler;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.concurrent.CountDownLatch;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class TestLocalControlConnectionManager {

  private static final DrillbitEndpoint localEndpoint = DrillbitEndpoint.newBuilder()
    .setAddress("10.0.0.1")
    .setControlPort(31011)
    .setState(DrillbitEndpoint.State.STARTUP)
    .build();

  private static ControlConnectionConfig mockConfig;

  private static ControlMessageHandler mockHandler;

  private static ControlTunnel controlTunnel;

  private static CountDownLatch latch;

  private static final String NEGATIVE_ACK_MESSAGE = "Negative Ack received";

  private static final RpcOutcomeListener<GeneralRPCProtos.Ack> outcomeListener =
    new RpcOutcomeListener<GeneralRPCProtos.Ack>() {
    @Override
    public void failed(RpcException ex) {
      throw new IllegalStateException(ex);
    }

    @Override
    public void success(GeneralRPCProtos.Ack value, ByteBuf buffer) {
      if (value.getOk()) {
        latch.countDown();
      } else {
        throw new IllegalStateException(NEGATIVE_ACK_MESSAGE);
      }
    }

    @Override
    public void interrupted(InterruptedException e) {
      // Do nothing
    }
  };

  @Rule
  public ExpectedException exceptionThrown = ExpectedException.none();

  @BeforeClass
  public static void setup() {
    mockConfig = mock(ControlConnectionConfig.class);
    final ConnectionManagerRegistry registry = new ConnectionManagerRegistry(mockConfig);
    registry.setLocalEndpoint(localEndpoint);
    ControlConnectionManager manager = registry.getConnectionManager(localEndpoint);
    assertTrue(manager instanceof LocalControlConnectionManager);
    controlTunnel = new ControlTunnel(manager);
  }

  @Before
  public void setupForTest() {
    mockHandler = mock(ControlMessageHandler.class);
    when(mockConfig.getMessageHandler()).thenReturn(mockHandler);
  }

  /**
   * Verify that SendFragmentStatus is handled correctly using ControlTunnel with LocalControlConnectionManager
   */
  @Test
  public void testLocalSendFragmentStatus_Success() throws Exception {
    final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
    final UserBitShared.QueryProfile mockProfile = UserBitShared.QueryProfile.getDefaultInstance();
    when(mockHandler.requestQueryStatus(mockQueryId)).thenReturn(mockProfile);
    final UserBitShared.QueryProfile returnedProfile = controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
    assertEquals(returnedProfile, mockProfile);
  }

  /**
   * Verify that SendFragmentStatus failure scenario is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalSendFragmentStatus_Failure() throws Exception {
    final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
    final String exceptionMessage = "Testing failure case";
    exceptionThrown.expect(RpcException.class);
    exceptionThrown.expectMessage(exceptionMessage);
    when(mockHandler.requestQueryStatus(mockQueryId)).thenThrow(new RpcException(exceptionMessage));
    controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
  }

  /**
   * Verify that CancelFragment with positive ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalCancelFragment_PositiveAck() throws Exception {
    final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
    latch = new CountDownLatch(1);
    final GeneralRPCProtos.Ack mockResponse = Acks.OK;
    when(mockHandler.cancelFragment(mockHandle)).thenReturn(mockResponse);
    controlTunnel.cancelFragment(outcomeListener, mockHandle);
    latch.await();
  }

  /**
   * Verify that CancelFragment with negative ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalCancelFragment_NegativeAck() throws Exception {
    final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
    latch = new CountDownLatch(1);
    exceptionThrown.expect(IllegalStateException.class);
    exceptionThrown.expectMessage(NEGATIVE_ACK_MESSAGE);
    final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
    when(mockHandler.cancelFragment(mockHandle)).thenReturn(mockResponse);
    controlTunnel.cancelFragment(outcomeListener, mockHandle);
    latch.await();
  }

  /**
   * Verify that InitializeFragments with positive ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalSendFragments_PositiveAck() throws Exception {
    final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
    latch = new CountDownLatch(1);
    final GeneralRPCProtos.Ack mockResponse = Acks.OK;
    when(mockHandler.initializeFragment(mockFragments)).thenReturn(mockResponse);
    controlTunnel.sendFragments(outcomeListener, mockFragments);
    latch.await();
  }

  /**
   * Verify that InitializeFragments with negative ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalSendFragments_NegativeAck() throws Exception {
    final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
    latch = new CountDownLatch(1);
    exceptionThrown.expect(IllegalStateException.class);
    exceptionThrown.expectMessage(NEGATIVE_ACK_MESSAGE);
    final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
    when(mockHandler.initializeFragment(mockFragments)).thenReturn(mockResponse);
    controlTunnel.sendFragments(outcomeListener, mockFragments);
    latch.await();
  }

  /**
   * Verify that InitializeFragments failure case is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testLocalSendFragments_Failure() throws Exception {
    final BitControl.InitializeFragments mockFragments = BitControl.InitializeFragments.getDefaultInstance();
    latch = new CountDownLatch(1);
    exceptionThrown.expect(IllegalStateException.class);
    exceptionThrown.expectCause(new TypeSafeMatcher<Throwable>(RpcException.class) {
      @Override
      protected boolean matchesSafely(Throwable throwable) {
        return (throwable != null && throwable instanceof RpcException);
      }

      @Override
      public void describeTo(Description description) {
        // Do nothing
      }
    });
    when(mockHandler.initializeFragment(mockFragments)).thenThrow(new RpcException("Failed to initialize"));
    controlTunnel.sendFragments(outcomeListener, mockFragments);
    latch.await();
  }

  /**
   * Verify that UnpauseFragment is handled correctly using ControlTunnel with LocalControlConnectionManager
   */
  @Test
  public void testUnpauseFragments() throws Exception {
    final ExecProtos.FragmentHandle mockHandle = ExecProtos.FragmentHandle.getDefaultInstance();
    latch = new CountDownLatch(1);
    final GeneralRPCProtos.Ack mockResponse = Acks.OK;
    when(mockHandler.resumeFragment(mockHandle)).thenReturn(mockResponse);
    controlTunnel.unpauseFragment(outcomeListener, mockHandle);
    latch.await();
  }

  /**
   * Verify that RequestQueryStatus is handled correctly using ControlTunnel with LocalControlConnectionManager
   */
  @Test
  public void testRequestQueryStatus() throws Exception {
    final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
    final UserBitShared.QueryProfile mockProfile = UserBitShared.QueryProfile.getDefaultInstance();
    when(mockHandler.requestQueryStatus(mockQueryId)).thenReturn(mockProfile);
    final UserBitShared.QueryProfile returnedProfile = controlTunnel.requestQueryProfile(mockQueryId).checkedGet();
    assertEquals(returnedProfile, mockProfile);
  }

  /**
   * Verify that CancelQuery with positive ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testCancelQuery_PositiveAck() throws Exception {
    final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
    final GeneralRPCProtos.Ack mockResponse = Acks.OK;
    when(mockHandler.requestQueryCancel(mockQueryId)).thenReturn(mockResponse);
    GeneralRPCProtos.Ack response = controlTunnel.requestCancelQuery(mockQueryId).checkedGet();
    assertEquals(response, mockResponse);
  }

  /**
   * Verify that CancelQuery with negative ack is handled correctly using ControlTunnel with
   * LocalControlConnectionManager
   */
  @Test
  public void testCancelQuery_NegativeAck() throws Exception {
    final UserBitShared.QueryId mockQueryId = UserBitShared.QueryId.getDefaultInstance();
    final GeneralRPCProtos.Ack mockResponse = Acks.FAIL;
    when(mockHandler.requestQueryCancel(mockQueryId)).thenReturn(mockResponse);
    GeneralRPCProtos.Ack response = controlTunnel.requestCancelQuery(mockQueryId).checkedGet();
    assertEquals(response, mockResponse);
  }

  /**
   * Verify that FinishedReceiver is handled correctly using ControlTunnel with LocalControlConnectionManager
   */
  @Test
  public void testInformReceiverFinished_success() throws Exception {
    final BitControl.FinishedReceiver finishedReceiver = BitControl.FinishedReceiver.getDefaultInstance();
    latch = new CountDownLatch(1);
    final GeneralRPCProtos.Ack mockResponse = Acks.OK;
    when(mockHandler.receivingFragmentFinished(finishedReceiver)).thenReturn(mockResponse);
    controlTunnel.informReceiverFinished(outcomeListener, finishedReceiver);
    latch.await();
  }
}


text:
namespace SportsBook.Web.Areas.Facilities.ViewModels.Comments
{
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    using AutoMapper;
    using Data.Models;
    using Infrastructure.Mapping;
using System;

    public class CommentViewModel : IMapTo<SportsBook.Data.Models.FacilityComment>, IHaveCustomMappings
    {
        public int Id { get; set; }

        [Required]
        [AllowHtml]
        [RegularExpression(@"^[^<>]*$", ErrorMessage = "Invalid symbol")]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 2)]
        public string Content { get; set; }

        public DateTime CreatedOn { get; set; }

        public string AuthorName { get; set; }

        public string AuthorId { get; set; }

        public virtual AppUser Author { get; set; }

        public bool IsDeleted { get; set; }

        public void CreateMappings(IMapperConfiguration configuration)
        {
            configuration.CreateMap<FacilityComment, CommentViewModel>();
        }
    }
}


text:
var gulp = require('gulp');
var path = require('path');

var gutil = require('gulp-util');

var webpack = require('webpack');
var webpackStream = require('webpack-stream');
var HtmlWebpackPlugin = require('html-webpack-plugin');

// var browserSync = require('./server').browserSync;

var config = require('./toolkit.config.js');

var { unixifyPath } = require('./utils');
var { getTypeOfFile, encode } = require('./encodeTask');

var { convertDataSchema, filterDataSchema } = require('./resources/dataschema');
var { filterHyperties, convertHyperty } = require('./resources/hyperty');
var { filterProtostubs, convertProtoStub } = require('./resources/protostub');
var createDescriptor = require('./descriptors').createDescriptor;
var getTypeOfDescriptor = require('./descriptors').getTypeOfDescriptor;

function watchHTML() {

  gulp.watch([
    process.cwd() + '/server/*.*',
    process.env.HYPERTY_REPO + '/examples/main.js',
    process.env.HYPERTY_REPO + '/exmaples/**/*.hbs',
    process.env.HYPERTY_REPO + '/exmaples/**/*.js'], () => {
    bundleHTML();
  });

  return bundleHTML();
}

function bundleHTML() {

  var webpackConfig = {
    entry: {
      rethink: process.cwd() + '/server/rethink.js'
    },
    output: {
      path: process.cwd() + '/app',
      filename: '[name].js'
    },
    devtool: 'source-map',
    resolve: {
      modules: [
        'node_modules',
        path.resolve(process.env.HYPERTY_REPO + '/' + process.env.HYPERTY_TEMPLATES_PATH)
      ],
      alias: {
        app: path.resolve(process.env.HYPERTY_REPO + '/' + process.env.HYPERTY_TEMPLATES_PATH + '/main.js')
      }
    },
    plugins: [new HtmlWebpackPlugin({
      title: 'Hyperty Toolkit',
      template: process.cwd() + '/server/index.ejs',
      files: {
        css: [],
        js: []
      }
    })]
  };

  return gulp.src([process.cwd() +  '/server/*.*', process.env.HYPERTY_REPO + '/examples/main.js'])
    .pipe(webpackStream(webpackConfig, webpack))
    .pipe(gulp.dest('app/'));
}

function watchResources(done) {

  gulp.watch(['./resources/*.js'], function(event) {

    var type = getTypeOfFile(event.path);

    switch (type) {
      case 'Runtime':
        var transpileOpts = {};
        transpileOpts.isES6 = false;
        encode(event.path, {}, transpileOpts);
        break;
    }

  });

}

function watchHyperties(done) {

  var sourceCode = getListOfResources('hyperty');
  sourceCode = sourceCode.map(item => path.join(item, '*.js'));

  gulp.watch(sourceCode, function(event) {
    // console.log('event:', event);
    return watchResource(event, 'hyperty');
  });

  var descriptor = getListOfResources('hyperty');
  descriptor = descriptor.map(item => path.join(item, '*.hy.json'));

  gulp.watch(descriptor, function(event) {
    return generateDescriptor('hyperty', event.path);
  });

}

function watchProtostubs(done) {

  var sourceCode = getListOfResources('protocolstub');
  sourceCode = sourceCode.map(item => path.join(item, '*.js'));

  // console.log('Watch Protostubs SourceCode:', sourceCode);

  gulp.watch(sourceCode, function(event) {
    // console.log('Change Portostubs code:', event);
    return watchResource(event, 'protocolstub');
  });

  var descriptor = getListOfResources('protocolstub');
  descriptor = descriptor.map(item => path.join(item, '*.ps.json'));
  gulp.watch(descriptor, function(event) {
    // console.log('Change Portostubs descriptor:', event);
    return generateDescriptor('protocolstub', event.path);
  });

}

function watchIdpProxies(done) {

  var sourceCode = getListOfResources('idp-proxy');
  sourceCode = sourceCode.map(item => path.join(item, '*.idp.js'));

  // console.log('Watch SourceCode:', sourceCode);

  gulp.watch(sourceCode, function(event) {
    return watchResource(event, 'idp-proxy');
  });

  var descriptor = getListOfResources('idp-proxy');
  descriptor = descriptor.map(item => path.join(item, '*.idp.json'));
  gulp.watch(descriptor, function(event) {
    return generateDescriptor('idp-proxy', event.path);
  });

}

function watchDataSchemas(done) {
  var sourceCode = getListOfResources('dataschema');
  sourceCode = sourceCode.map(item => path.join(item, '*.ds.js'));

  // Watch the local resources for DataSchemas
  sourceCode.concat([process.cwd() + path.join('resources', 'schemas', '**', '*.ds.json')]);

  gulp.watch(sourceCode, function(event) {
    return watchResource(event, 'dataschema');
  });

  var descriptor = getListOfResources('dataschema');
  descriptor = descriptor.map(item => path.join(item, '*.ds.json'));

  // Watch the local resources for DataSchemas
  descriptor = descriptor.concat([process.cwd() + path.join('resources', 'schemas', '**', '*.ds.json')]);

  // console.log('Watch dataSchema: ', descriptor);
  gulp.watch(descriptor, function(event) {
    return generateDescriptor('dataschema', event.path);
  });
}

function watchResource(event, type) {

  if ((event.type === 'changed' || event.type === 'added') && !event.path.includes('node_modules')) {

    var fileObject = path.parse(event.path);
    var resource;
    var convertFunction;
    var filePath;

    switch (type) {

      case 'hyperty':
        resource = getTypeOfDescriptor('hyperty');
        convertFunction = convertHyperty;
        filePath = path.join(fileObject.dir, '*' + resource.extension + '.js');
        break;

      case 'protocolstub':
        resource = getTypeOfDescriptor('protocolstub');
        convertFunction = convertProtoStub;
        filePath = path.join(fileObject.dir, '*' + resource.extension + '.js');
        break;

      case 'idp-proxy':
        resource = getTypeOfDescriptor('idp-proxy');
        convertFunction = convertProtoStub;
        filePath = path.join(fileObject.dir, '*' + resource.extension + '.js');
        break;

      case 'dataschema':
        resource = getTypeOfDescriptor('dataschema');
        convertFunction = convertDataSchema;
        filePath = path.join(fileObject.dir, '*' + resource.extension + '.js');
        break;
    }

    return gulp.src(filePath)
      .pipe(convertFunction())
      .resume()
      .on('end', function() {
        // browserSync.reload();
      });

  }

}

function getListOfResources(type) {

  var resource = getTypeOfDescriptor(type);
  var list;
  var filtered;
  var resourcePath;
  var resourceSrc;

  switch (resource.type) {
    case 'idp-proxy':
    case 'protocolstub':
      list = config.protostubs.include_stubs || ['**'];
      filtered = filterProtostubs(process.env.ENVIRONMENT);
      resourcePath = config.protostubs.repository;
      resourceSrc = config.protostubs.sourceCode;
      break;

    case 'hyperty':
      list = config.hyperties.include_hyperties || ['**'];
      filtered = filterHyperties(process.env.ENVIRONMENT);
      resourcePath = config.hyperties.repository;
      resourceSrc = config.hyperties.sourceCode;
      break;

    case 'dataschema':
      list = config.hyperties.include_hyperties || ['**'];
      filtered = filterDataSchema(process.env.ENVIRONMENT);
      resourcePath = config.hyperties.repository;
      resourceSrc = config.hyperties.sourceCode;
      break;
  }

  if (list.length === 0) {
    list = filtered.map(resource => unixifyPath(resource.dir).replace('/', ''));
  }

  var resources = list.map((item) => {
    item = item.trim();
    return path.join(resourcePath, resourceSrc, item);
  }).filter((item) => {
    return !!filtered.filter(resource => item.includes(resource.dir)).length;
  });

  return resources;
}

/** Create descriptors and source code for Hyperties */

function createHypertiesSourceCode() {
  return generateSourceCode('hyperty');
}

function createHypertiesDescriptors() {
  return generateDescriptor('hyperty');
}

/** Create descriptors and source code for Protostubs */
function createProtoStubsSourceCode() {
  return generateSourceCode('protocolstub');
}

function createProtoStubsDescriptors() {
  return generateDescriptor('protocolstub');
}

/** Create descriptors and source code for IDP Proxies */
function createIDPProxySourceCode() {
  return generateSourceCode('idp-proxy');
}

function createIDPProxyDescriptors() {
  return generateDescriptor('idp-proxy');
}

/** Create descriptors and source code for IDP Proxies */
function createDataSchemasSourceCode() {
  return generateSourceCode('dataschema');
}

function createDataSchemasDescriptors() {
  return generateDescriptor('dataschema');
}

function generateSourceCode(type) {

  var resource = getTypeOfDescriptor(type);
  var list;
  var filtered;
  var repository;
  var convertFunction;

  // console.log('resource:', resource);

  switch (resource.type) {
    case 'idp-proxy':
    case 'protocolstub':
      list = config.protostubs.include_stubs;
      repository = path.join(config.protostubs.repository, config.protostubs.sourceCode);
      filtered = filterProtostubs(process.env.ENVIRONMENT);
      convertFunction = convertProtoStub;
      break;

    case 'hyperty':
      list = config.hyperties.include_hyperties;
      repository = path.join(config.hyperties.repository, config.hyperties.sourceCode);
      filtered = filterHyperties(process.env.ENVIRONMENT);
      convertFunction = convertHyperty;
      break;

    case 'dataschema':
      list = config.hyperties.include_hyperties;
      repository = path.join(config.hyperties.repository, config.hyperties.sourceCode);
      filtered = filterDataSchema(process.env.ENVIRONMENT);
      convertFunction = convertDataSchema;
      break;
  }

  if (list.length === 0) {
    list = filtered.map(resource => unixifyPath(resource.dir).replace('/', ''));
  }

  var sourceCode = list.map((item) => {
    item = item.trim();
    return path.join(repository, item, '*' + resource.extension + '.js');
  }).filter((item) => {
    return !!filtered.filter(resource => item.includes(resource.dir)).length;
  });

  return gulp.src(sourceCode)
    .pipe(convertFunction())
    .on('end', function() {
      // browserSync.reload();
    });

}

function generateDescriptor(type, filePath) {

  var resource = getTypeOfDescriptor(type);
  var list;
  var filtered;
  var repository;

  switch (resource.type) {
    case 'idp-proxy':
    case 'protocolstub':
      list = config.protostubs.include_stubs;
      repository = path.join(config.protostubs.repository, config.protostubs.sourceCode);
      filtered = filterProtostubs(process.env.ENVIRONMENT);
      break;

    case 'hyperty':
      list = config.hyperties.include_hyperties;
      repository = path.join(config.hyperties.repository, config.hyperties.sourceCode);
      filtered = filterHyperties(process.env.ENVIRONMENT);
      break;

    case 'dataschema':
      list = config.hyperties.include_hyperties;
      repository = path.join(config.hyperties.repository, config.hyperties.sourceCode);
      filtered = filterDataSchema(process.env.ENVIRONMENT);

  }

  if (list.length === 0) {
    list = filtered.map(resource => unixifyPath(resource.dir).replace('/', ''));
  }

  var descriptor = list.map((item) => {
    item = item.trim();
    return path.join(repository, item, '*' + resource.extension + '.json');
  }).filter((item) => {
    return !!filtered.filter(resource => item.includes(resource.dir)).length;
  });

  if (filePath) { descriptor = filePath; }

  if (resource.type === 'dataschema') {
    descriptor = descriptor.concat('./resources/schemas/**/*.ds.json');
    return gulp.src(descriptor)
      .pipe(convertDataSchema())
      .on('end', function() {
        gutil.log('the pre configuration of ' + resource.type + '  was changed, and the ' + resource.name + '.json was updated');

        // browserSync.reload();
      });
  }

  return gulp.src(descriptor)
    .pipe(createDescriptor(resource.type))
    .pipe(gulp.dest('./resources/descriptors/' + resource.name + '.json'))
    .on('end', function() {
      gutil.log('the pre configuration of ' + resource.type + '  was changed, and the ' + resource.name + '.json was updated');

      // browserSync.reload();
    });

}

module.exports = {
  createHypertiesSourceCode: createHypertiesSourceCode,
  createHypertiesDescriptors: createHypertiesDescriptors,

  createProtoStubsSourceCode: createProtoStubsSourceCode,
  createProtoStubsDescriptors: createProtoStubsDescriptors,

  createIDPProxySourceCode: createIDPProxySourceCode,
  createIDPProxyDescriptors: createIDPProxyDescriptors,

  createDataSchemasSourceCode: createDataSchemasSourceCode,
  createDataSchemasDescriptors: createDataSchemasDescriptors,

  watchDataSchemas: watchDataSchemas,
  watchIdpProxies: watchIdpProxies,
  watchProtostubs: watchProtostubs,
  watchHyperties: watchHyperties,
  watchResources: watchResources,
  watchHTML: watchHTML
};


text:
.pagination {
    display: inline-flex;
}

.pagination > li > a,
.pagination > li > span {
    border: 0;
    border-radius: 30px !important;
    transition: all .3s;
    padding: 0px 11px;
    margin: 0 3px;
    min-width: 30px;
    height: 30px;
    line-height: 30px;
    color: #999999;
    font-weight: 400;
    font-size: 12px;
    text-transform: uppercase;
    background: transparent;
}

.pagination > li > a:hover, .pagination > li > a:focus,
.pagination > li > span:hover,
.pagination > li > span:focus {
    color: #999999;
}

.pagination a.active,
.pagination span.active {
    color: #E40037;
}

.pager {
    text-align: right;
    margin: 0;
}

.pager > ul {
    padding: 10px 10px 10px 20px;
    border-radius: 0;
    text-align: right;
    margin: 0;
}

.pager .pagination a, .pager .pagination a:hover {
    border: #000 1px solid;
    border-radius: 5px !important;
    box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.2);
}

.pager .pagination a span {
    position: relative;
    top: -1.0px;
}

.pager .pagination .active a {
    background-color: black;
}

.pager .pagination .inactive a {
    color: black;
}

.pager .pagination .inactive a.disabled {
    box-shadow: none;
}

.pager .pagination .inactive a:hover {
    background-color: rgba(0, 0, 0, 0.1);
    border: #000 1px solid;
}

.pager .pagination .inactive a.disabled {
    border-color: #999999;
}

.pager .pagination .inactive a.disabled:hover, .pager .pagination .inactive a.disabled:focus {
    background-color: transparent;
}


text:
App.Posts = App.BaseCollection.extend({

  url: '/posts',

  key: 'posts'

});


text:
package com.googlecode.l10nmavenplugin.validators.property;

import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Before;
import org.junit.Test;

import com.googlecode.l10nmavenplugin.format.Formatter;
import com.googlecode.l10nmavenplugin.format.InnerResourcesFormatter;
import com.googlecode.l10nmavenplugin.format.MessageFormatFormatter;
import com.googlecode.l10nmavenplugin.log.L10nValidatorLogger;
import com.googlecode.l10nmavenplugin.model.Property;
import com.googlecode.l10nmavenplugin.model.PropertyImpl;
import com.googlecode.l10nmavenplugin.validators.AbstractL10nValidatorTest;
import com.googlecode.l10nmavenplugin.validators.L10nValidator;

public class HtmlValidatorTest extends AbstractL10nValidatorTest<Property> {

  private static HtmlValidator validator;

  @Override
  @Before
  public void setUp() {
    super.setUp();
    Formatter formatter = new MessageFormatFormatter();
    InnerResourcesFormatter innerResourcesFormatter = new InnerResourcesFormatter("\\[\\[([A-Za-z0-9\\._]+)\\]\\]");
    // Use XHTML5 schema as it is much faster
    validator = new HtmlValidator(HtmlValidator.XHTML5, logger, null, new String[] { ".text." }, formatter,
        innerResourcesFormatter);
    validator.setSpellCheckValidator(new AlwaysSucceedingValidator<Property>());
  }

  @Test
  public void testDataAttributePattern() {
    assertFalse(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("length=\"\"").find());
    assertFalse(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-=\"\"").find());
    assertFalse(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-param=\"'").find());

    assertTrue(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-length=\"\"").find());
    // Single quotes
    assertTrue(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-length=''").find());

    // Spaces
    assertTrue(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher(" data-length=\" \" ").find());
    assertTrue(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-123-456=\"789\"").find());

    // Double quotes inside value
    // assertFalse(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-length=\"\"\"").find());
    assertTrue(HtmlValidator.DATA_ATTRIBUTE_PATTERN.matcher("data-length=\"\\\"\"").find());
  }

  @Test
  public void testValidHtml() {
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "Some text", FILE), items));
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK,
        "
Some Text onGoogle
", FILE), items));
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK,
        "Google", FILE), items));
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, " ©–", FILE), items));
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "link", FILE), items));
    // Nested HTML escaping "
    // assertEquals(0, plugin.validateProperty(KEY_OK, "", null));
  }

  @Test
  public void testIncludedKeys() {
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK,
        "
Some Text onGoogle
", FILE), items));
    String value = "
\n
 li content with some anchor and new lines
\n
";
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, value, FILE), items));
  }

  @Test
  public void testInvalidHtml() {
    // Escaped = or : not consumed by Properties#load ?
    assertEquals(1,
        validator.validate(new PropertyImpl(KEY_KO, "link", FILE), items));
  }

  @Test
  public void testUnescapedHtmlEntity() {
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO,
        "Text", FILE), items));
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO, "A & B", FILE), items));
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO, " &nbsp", FILE), items));
  }

  @Test
  public void testUnclosedHtmlTag() {
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO, "
", FILE), items));
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO, "
Some Text", FILE), items));
  }

  @Test
  public void testParametricHTML() {
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "Some {0} text", FILE), items));
    //

 is valid
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "

", FILE), items));
    // Workaround to pass validation: use single quotes on the inside
    assertEquals(0,
        validator.validate(new PropertyImpl(KEY_OK, "", FILE), items));
    //

 is not valid
    assertTrue(1 <= validator.validate(new PropertyImpl(KEY_KO, "

", FILE), items));

    // Check '' is unescaped before validation
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "

", FILE), items));

    // Quoted text
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "'{Some quoted text}'", FILE), items));
    // TODO Quoted text with parameters
    // assertEquals(0, plugin.validateProperty(KEY_OK,"'{Some quoted text}' with {0}", FILE)));
  }

  @Test
  public void testMalformedMessageFormat() {
    assertEquals(1, validator.validate(new PropertyImpl(KEY_KO, "{0{1}}", FILE), items));
  }

  @Test
  public void customHtmlDataAttributesShouldPassValidation() {
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "

", FILE), items));
    assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "
", FILE), items));

    // Mixed double/single quotes
    assertEquals(1, validator.validate(new PropertyImpl(KEY_OK, "

", FILE), items));
  }

  @Test
  public void testSpellCheckChaining() {
    validator.setSpellCheckValidator(new AlwaysFailingValidator<Property>());

    assertEquals(2,
        validator.validate(new PropertyImpl(KEY_KO, "
Text1Text2
", FILE), items));
  }

  @Test
  public void testSpellCheck() {
    URL url = getClass().getClassLoader().getResource("");
    try {
      L10nValidator<Property> spellCheckValidator = new SpellCheckValidator(new L10nValidatorLogger(), new File(
          url.toURI()));
      validator.setSpellCheckValidator(spellCheckValidator);
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }

    validator.validate(new PropertyImpl(KEY_KO, "
BlablaplopEnglis
", FILE), items);
    assertEquals(2, items.size());
  }

  @Test
  public void testShouldValidate() {
    assertTrue(validator.shouldValidate(new PropertyImpl("page.text.key", "Some text", FILE)));
    assertFalse(validator.shouldValidate(new PropertyImpl(KEY_OK, "Some text", FILE)));
  }

  @Test
  public void testSeveralLis() {
    validator.validate(new PropertyImpl(KEY_OK, "
Item 1

Item 2

Item 3
", FILE), items);
    assertEquals(items.toString(), 0, items.size());
    items.clear();

    validator.validate(new PropertyImpl(KEY_KO, "

Item 1

Item 2

Item 3

", FILE),
        items);
    assertEquals(items.toString(), 1, items.size());
  }

  @Test
  public void invalidSchemaShouldDefaultToXhtml1() {
    validator = new HtmlValidator(new File("dummy"), logger, null, new String[] {}, null, null);

    verify(log).error(contains("Could not load XML schema"));
  }
}


text:
using namespace std;
using namespace cp;
using namespace cp::model;
using namespace cp::parse;
const string X_PATH = "BMPath.xml";

int main()
{
	clock_t  begin, end;
	XMLBuilder path_builder(X_PATH, XRT_BM_PATH);
	string bm_path = path_builder.GetBMFile();
	cout << bm_path << endl;
	XMLBuilder builder(bm_path, XRT_BM);
	XMLModel* xml_model = new XMLModel();
	builder.GenerateModelFromXml(xml_model);
	Network* nt = new Network();
	BuildModel(xml_model, nt);
	DestroyEXTModel(xml_model);
	//AC3* ac = new AC3(nt);
	//VarEvt* x_evt_ = new VarEvt(nt);
	//AC3rm* ac = new AC3rm(nt);
	//ac->EnforceGAC_arc(x_evt_);
	//MAC* mac = new MAC(nt, AC_3);
	MAC* mac = new MAC(nt, AC_3bit);
	//MAC* mac = new MAC(nt, AC_3rm);
	begin = clock();
	mac->enforce();
	end = clock();
	cout << "solutions = " << mac->sol_count() << endl;
	cout << "execute time = " << end - begin << endl;
	//delete x_evt_;
	//delete ac;
	delete mac;
	delete nt;
	mac = NULL;
	//x_evt_ = NULL;
	//ac = NULL;
	nt = NULL;
	return 0;
}


text:
<?php
namespace Finance\BackOfficeBundle\Repository;

use Doctrine\ORM\EntityRepository;

class CreditRepository extends EntityRepository {

}


text:
Installing TJ
====================

by Phil Christensen
phil@bubblehouse.org

Once you install Python and Twisted, the rest will be taken care of by
the setup.py file. I recommend using [pip](http://pypi.python.org/pypi/pip),
but any setuptools-compatible method should work fine.

    git clone git://github.com/philchristensen/TJ.git
    cd TJ
    pip install --editable .

Next you should be able to start up the server with:

    twistd -n tjbot

The -n will keep it in the foreground. Configuration options are kept in the
global settings file, *default.json*.